code
stringlengths
1
1.72M
language
stringclasses
1 value
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'HelpEntry' db.create_table('help_helpentry', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(unique=True, max_length=255)), ('db_help_category', self.gf('django.db.models.fields.CharField')(default='General', max_length=255)), ('db_entrytext', self.gf('django.db.models.fields.TextField')(blank=True)), ('db_permissions', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), ('db_lock_storage', self.gf('django.db.models.fields.TextField')(blank=True)), ('db_staff_only', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal('help', ['HelpEntry']) def backwards(self, orm): # Deleting model 'HelpEntry' db.delete_table('help_helpentry') models = { 'help.helpentry': { 'Meta': {'object_name': 'HelpEntry'}, 'db_entrytext': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_help_category': ('django.db.models.fields.CharField', [], {'default': "'General'", 'max_length': '255'}), 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_staff_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['help']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'HelpEntry.db_lock_storage' db.alter_column('help_helpentry', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512)) def backwards(self, orm): # Changing field 'HelpEntry.db_lock_storage' db.alter_column('help_helpentry', 'db_lock_storage', self.gf('django.db.models.fields.TextField')()) models = { 'help.helpentry': { 'Meta': {'object_name': 'HelpEntry'}, 'db_entrytext': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_help_category': ('django.db.models.fields.CharField', [], {'default': "'General'", 'max_length': '255'}), 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_staff_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['help']
Python
""" Custom manager for HelpEntry objects. """ from django.db import models from src.utils import logger, utils class HelpEntryManager(models.Manager): """ This implements different ways to search for help entries. """ def find_topicmatch(self, topicstr, exact=False): """ Searches for matching topics based on player's input. """ if utils.dbref(topicstr): return self.filter(id=utils.dbref(topicstr)) topics = self.filter(db_key__iexact=topicstr) if not topics and not exact: topics = self.filter(db_key__istartswith=topicstr) if not topics: topics = self.filter(db_key__icontains=topicstr) return topics def find_apropos(self, topicstr): """ Do a very loose search, returning all help entries containing the search criterion in their titles. """ return self.filter(db_key__icontains=topicstr) def find_topicsuggestions(self, topicstr): """ Do a fuzzy match, preferably within the category of the current topic. """ topics = self.find_apropos(topicstr) # we need to clean away the given help entry. return [topic for topic in topics if topic.key.lower() != topicstr.lower()] def find_topics_with_category(self, help_category): """ Search topics having a particular category """ topics = self.filter(db_help_category__iexact=help_category) return topics def get_all_topics(self): """ Return all topics. """ return self.all() def get_all_categories(self, pobject): """ Return all defined category names with at least one topic in them. """ return list(set(topic.help_category for topic in self.all())) def all_to_category(self, default_category): """ Shifts all help entries in database to default_category. This action cannot be reverted. It is used primarily by the engine when importing a default help database, making sure this ends up in one easily separated category. """ topics = self.all() for topic in topics: topic.help_category = default_category topic.save() string = "Help database moved to category %s" % default_category logger.log_infomsg(string) def search_help(self, ostring, help_category=None): """ Retrieve a search entry object. ostring - the help topic to look for category - limit the search to a particular help topic """ ostring = ostring.strip().lower() help_entries = self.filter(db_topicstr=ostring) if help_category: help_entries.filter(db_help_category=help_category) return help_entries
Python
# # This sets up how models are displayed # in the web admin interface. # from django import forms from django.conf import settings from django.contrib import admin from src.objects.models import ObjAttribute, ObjectDB, ObjectNick, Alias from src.utils.utils import mod_import class ObjAttributeInline(admin.TabularInline): model = ObjAttribute fields = ('db_key', 'db_value') extra = 0 class NickInline(admin.TabularInline): model = ObjectNick fields = ('db_nick', 'db_real', 'db_type') extra = 0 class AliasInline(admin.TabularInline): model = Alias fields = ("db_key",) extra = 0 class ObjectCreateForm(forms.ModelForm): "This form details the look of the fields" class Meta: model = ObjectDB db_key = forms.CharField(label="Name/Key", widget=forms.TextInput(attrs={'size':'78'}), help_text="Main identifier, like 'apple', 'strong guy', 'Elizabeth' etc. If creating a Character, check so the name is unique among characters!",) db_typeclass_path = forms.CharField(label="Typeclass",initial="Change to (for example) %s or %s." % (settings.BASE_OBJECT_TYPECLASS, settings.BASE_CHARACTER_TYPECLASS), widget=forms.TextInput(attrs={'size':'78'}), help_text="This defines what 'type' of entity this is. This variable holds a Python path to a module with a valid Evennia Typeclass. If you are creating a Character you should use the typeclass defined by settings.BASE_CHARACTER_TYPECLASS or one derived from that.") db_permissions = forms.CharField(label="Permissions", initial=settings.PERMISSION_PLAYER_DEFAULT, required=False, widget=forms.TextInput(attrs={'size':'78'}), help_text="a comma-separated list of text strings checked by certain locks. They are mainly of use for Character objects. Character permissions overload permissions defined on a controlling Player. Most objects normally don't have any permissions defined.") db_cmdset_storage = forms.CharField(label="CmdSet", initial=settings.CMDSET_DEFAULT, required=False, widget=forms.TextInput(attrs={'size':'78'}), help_text="Most non-character objects don't need a cmdset and can leave this field blank.") class ObjectEditForm(ObjectCreateForm): "Form used for editing. Extends the create one with more fields" db_lock_storage = forms.CharField(label="Locks", required=False, widget=forms.Textarea(attrs={'cols':'100', 'rows':'2'}), help_text="In-game lock definition string. If not given, defaults will be used. This string should be on the form <i>type:lockfunction(args);type2:lockfunction2(args);...") class ObjectDBAdmin(admin.ModelAdmin): list_display = ('id', 'db_key', 'db_location', 'db_player', 'db_typeclass_path') list_display_links = ('id', 'db_key') ordering = ['db_player', 'db_typeclass_path', 'id'] search_fields = ['^db_key', 'db_typeclass_path'] save_as = True save_on_top = True list_select_related = True list_filter = ('db_permissions', 'db_location', 'db_typeclass_path') # editing fields setup form = ObjectEditForm fieldsets = ( (None, { 'fields': (('db_key','db_typeclass_path'), ('db_permissions', 'db_lock_storage'), ('db_location', 'db_home'), 'db_destination','db_cmdset_storage' )}), ) #deactivated temporarily, they cause empty objects to be created in admin inlines = [AliasInline]#, ObjAttributeInline] # Custom modification to give two different forms wether adding or not. add_form = ObjectCreateForm add_fieldsets = ( (None, { 'fields': (('db_key','db_typeclass_path'), 'db_permissions', ('db_location', 'db_home'), 'db_destination','db_cmdset_storage' )}), ) def get_fieldsets(self, request, obj=None): if not obj: return self.add_fieldsets return super(ObjectDBAdmin, self).get_fieldsets(request, obj) def get_form(self, request, obj=None, **kwargs): """ Use special form during creation """ defaults = {} if obj is None: defaults.update({ 'form': self.add_form, 'fields': admin.util.flatten_fieldsets(self.add_fieldsets), }) defaults.update(kwargs) return super(ObjectDBAdmin, self).get_form(request, obj, **defaults) def save_model(self, request, obj, form, change): if not change: # adding a new object obj = obj.typeclass obj.basetype_setup() obj.basetype_posthook_setup() obj.at_object_creation() obj.at_init() admin.site.register(ObjectDB, ObjectDBAdmin)
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ObjAttribute' db.create_table('objects_objattribute', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(max_length=255)), ('db_value', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('db_mode', self.gf('django.db.models.fields.CharField')(max_length=20, null=True, blank=True)), ('db_lock_storage', self.gf('django.db.models.fields.TextField')(blank=True)), ('db_date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('db_obj', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['objects.ObjectDB'])), )) db.send_create_signal('objects', ['ObjAttribute']) # Adding model 'Alias' db.create_table('objects_alias', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(max_length=255)), ('db_obj', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['objects.ObjectDB'])), )) db.send_create_signal('objects', ['Alias']) # Adding model 'Nick' db.create_table('objects_nick', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_nick', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)), ('db_real', self.gf('django.db.models.fields.TextField')()), ('db_type', self.gf('django.db.models.fields.CharField')(default='inputline', max_length=16, null=True, blank=True)), ('db_obj', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['objects.ObjectDB'])), )) db.send_create_signal('objects', ['Nick']) # Adding unique constraint on 'Nick', fields ['db_nick', 'db_type', 'db_obj'] db.create_unique('objects_nick', ['db_nick', 'db_type', 'db_obj_id']) # Adding model 'ObjectDB' db.create_table('objects_objectdb', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(max_length=255)), ('db_typeclass_path', self.gf('django.db.models.fields.CharField')(max_length=255, null=True)), ('db_date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('db_permissions', self.gf('django.db.models.fields.CharField')(max_length=512, blank=True)), ('db_lock_storage', self.gf('django.db.models.fields.TextField')(blank=True)), # Moved to player migration #('db_player', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['players.PlayerDB'], null=True, blank=True)), ('db_location', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='locations_set', null=True, to=orm['objects.ObjectDB'])), ('db_home', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='homes_set', null=True, to=orm['objects.ObjectDB'])), ('db_cmdset_storage', self.gf('django.db.models.fields.TextField')(null=True)), )) db.send_create_signal('objects', ['ObjectDB']) def backwards(self, orm): # Removing unique constraint on 'Nick', fields ['db_nick', 'db_type', 'db_obj'] db.delete_unique('objects_nick', ['db_nick', 'db_type', 'db_obj_id']) # Deleting model 'ObjAttribute' db.delete_table('objects_objattribute') # Deleting model 'Alias' db.delete_table('objects_alias') # Deleting model 'Nick' db.delete_table('objects_nick') # Deleting model 'ObjectDB' db.delete_table('objects_objectdb') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.alias': { 'Meta': {'object_name': 'Alias'}, 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.nick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'Nick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objattribute': { 'Meta': {'object_name': 'ObjAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_mode': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['objects']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models, utils class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." # we need to add a default lock string to all objects, then a separate set to Characters. lockstring1 = 'control:id(1);get:all();edit:perm(Wizards);examine:perm(Builders);call:true();puppet:id(#4) or perm(Immortals) or pperm(Immortals);delete:id(1) or perm(Wizards)' lockstring2 = 'control:id(#3) or perm(Immortals);get:perm(Wizards);edit:perm(Wizards);examine:perm(Builders);call:false();puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals);delete:perm(Wizards)' try: for obj in orm.ObjectDB.objects.all().exclude(db_player__isnull=False): obj.db_lock_storage = lockstring1 obj.save() for obj in orm.ObjectDB.objects.filter(db_player__isnull=False): obj.db_lock_storage = lockstring2 % (obj.id, obj.db_player.id) obj.save() except utils.DatabaseError: # running from scatch. In this case we just ignore this. pass def backwards(self, orm): "Write your backwards methods here." raise RuntimeError("You cannot reverse this migration.") models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.alias': { 'Meta': {'object_name': 'Alias'}, 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objattribute': { 'Meta': {'object_name': 'ObjAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectnick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'ObjectNick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['objects']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding index on 'ObjectDB', fields ['db_key'] db.create_index('objects_objectdb', ['db_key']) # Adding index on 'Alias', fields ['db_key'] db.create_index('objects_alias', ['db_key']) # Adding index on 'ObjAttribute', fields ['db_key'] db.create_index('objects_objattribute', ['db_key']) def backwards(self, orm): # Removing index on 'ObjAttribute', fields ['db_key'] db.delete_index('objects_objattribute', ['db_key']) # Removing index on 'Alias', fields ['db_key'] db.delete_index('objects_alias', ['db_key']) # Removing index on 'ObjectDB', fields ['db_key'] db.delete_index('objects_objectdb', ['db_key']) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.alias': { 'Meta': {'object_name': 'Alias'}, 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objattribute': { 'Meta': {'object_name': 'ObjAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectnick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'ObjectNick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['objects']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from src.objects.models import ObjectDB class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'ObjectDB.db_destination' db.add_column('objects_objectdb', 'db_destination', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='destinations_set', null=True, to=orm['objects.ObjectDB']), keep_default=False) # move all exits to the new property for exi in ObjectDB.objects.get_objs_with_attr('_destination'): exi.destination = exi.db._destination exi.del_attribute('_destination') def backwards(self, orm): # Deleting field 'ObjectDB.db_destination' db.delete_column('objects_objectdb', 'db_destination_id') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.alias': { 'Meta': {'object_name': 'Alias'}, 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.nick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'Nick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objattribute': { 'Meta': {'object_name': 'ObjAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['objects']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'ObjAttribute.db_mode' from src.objects.models import ObjAttribute from src.typeclasses.models import PackedDBobject for attr in ObjAttribute.objects.all(): # resave attributes db_mode = attr.db_mode if db_mode and db_mode != 'pickle': # an object. We need to resave this. if db_mode == 'object': val = PackedDBobject(attr.db_value, "objectdb") elif db_mode == 'player': val = PackedDBobject(attr.db_value, "playerdb") elif db_mode == 'script': val = PackedDBobject(attr.db_value, "scriptdb") elif db_mode == 'help': val = PackedDBobject(attr.db_value, "helpentry") else: val = PackedDBobject(attr.db_value, db_mode) # channel, msg attr.value = val db.delete_column('objects_objattribute', 'db_mode') def backwards(self, orm): # Adding field 'ObjAttribute.db_mode' db.add_column('objects_objattribute', 'db_mode', self.gf('django.db.models.fields.CharField')(max_length=20, null=True, blank=True), keep_default=False) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.alias': { 'Meta': {'object_name': 'Alias'}, 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.nick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'Nick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objattribute': { 'Meta': {'object_name': 'ObjAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['objects']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models, utils class Migration(SchemaMigration): def forwards(self, orm): try: # if we migrate, we just rename the table. This will move over all values too. db.rename_table("objects_nick", "objects_objectnick") except utils.DatabaseError: # this happens if we start from scratch. In that case the old # database table doesn't exist, so we just create the new one. # Adding model 'ObjectNick' db.create_table('objects_objectnick', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_nick', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)), ('db_real', self.gf('django.db.models.fields.TextField')()), ('db_type', self.gf('django.db.models.fields.CharField')(default='inputline', max_length=16, null=True, blank=True)), ('db_obj', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['objects.ObjectDB'])), )) db.send_create_signal('objects', ['ObjectNick']) # Adding unique constraint on 'ObjectNick', fields ['db_nick', 'db_type', 'db_obj'] db.create_unique('objects_objectnick', ['db_nick', 'db_type', 'db_obj_id']) def backwards(self, orm): raise RuntimeError("This migration cannot be reversed.") models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.alias': { 'Meta': {'object_name': 'Alias'}, 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objattribute': { 'Meta': {'object_name': 'ObjAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectnick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'ObjectNick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['objects']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'ObjectDB.db_cmdset_storage' db.alter_column('objects_objectdb', 'db_cmdset_storage', self.gf('django.db.models.fields.CharField')(max_length=255, null=True)) # Changing field 'ObjectDB.db_lock_storage' db.alter_column('objects_objectdb', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512)) # Changing field 'ObjectDB.db_permissions' db.alter_column('objects_objectdb', 'db_permissions', self.gf('django.db.models.fields.CharField')(max_length=255)) # Changing field 'ObjAttribute.db_lock_storage' db.alter_column('objects_objattribute', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512)) def backwards(self, orm): # Changing field 'ObjectDB.db_cmdset_storage' db.alter_column('objects_objectdb', 'db_cmdset_storage', self.gf('django.db.models.fields.TextField')(null=True)) # Changing field 'ObjectDB.db_lock_storage' db.alter_column('objects_objectdb', 'db_lock_storage', self.gf('django.db.models.fields.TextField')()) # Changing field 'ObjectDB.db_permissions' db.alter_column('objects_objectdb', 'db_permissions', self.gf('django.db.models.fields.CharField')(max_length=512)) # Changing field 'ObjAttribute.db_lock_storage' db.alter_column('objects_objattribute', 'db_lock_storage', self.gf('django.db.models.fields.TextField')()) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.alias': { 'Meta': {'object_name': 'Alias'}, 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objattribute': { 'Meta': {'object_name': 'ObjAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectnick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'ObjectNick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['objects']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models, utils class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." lockstring1 = 'control:id(1);get:all();edit:perm(Wizards);view:all();examine:perm(Builders);call:true();puppet:id(#4) or perm(Immortals) or pperm(Immortals);delete:id(1) or perm(Wizards)' lockstring2 = 'control:id(#3) or perm(Immortals);get:perm(Wizards);edit:perm(Wizards);view:all();examine:perm(Builders);call:false();puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals);delete:perm(Wizards)' try: for obj in orm.ObjectDB.objects.all().exclude(db_player__isnull=False): obj.db_lock_storage = lockstring1 obj.save() for obj in orm.ObjectDB.objects.filter(db_player__isnull=False): obj.db_lock_storage = lockstring2 % (obj.id, obj.db_player.id) obj.save() except utils.DatabaseError: # running from scatch. In this case we just ignore this. pass def backwards(self, orm): "Write your backwards methods here." raise RuntimeError("You cannot reverse this migration.") models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.alias': { 'Meta': {'object_name': 'Alias'}, 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objattribute': { 'Meta': {'object_name': 'ObjAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectnick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'ObjectNick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['objects']
Python
""" Custom manager for Objects. """ from django.conf import settings from django.contrib.auth.models import User from django.db.models.fields import exceptions from src.typeclasses.managers import TypedObjectManager from src.typeclasses.managers import returns_typeclass, returns_typeclass_list from src.utils import utils # Try to use a custom way to parse id-tagged multimatches. AT_MULTIMATCH_INPUT = utils.mod_import(*settings.SEARCH_AT_MULTIMATCH_INPUT.rsplit('.', 1)) class ObjectManager(TypedObjectManager): """ This is the main ObjectManager for all in-game objects. It implements search functions specialized for objects of this type, such as searches based on user, contents or location. See src.dbobjects.TypedObjectManager for more general search methods. """ # # ObjectManager Get methods # # user/player related @returns_typeclass def get_object_with_user(self, user): """ Matches objects with obj.player.user matching the argument. A player<->user is a one-to-relationship, so this always returns just one result or None. user - may be a user object or user id. """ try: uid = int(user) except TypeError: try: uid = user.id except: return None try: return self.get(db_player__user__id=uid) except Exception: return None # This returns typeclass since get_object_with_user and get_dbref does. def get_object_with_player(self, search_string): """ Search for an object based on its player's name or dbref. This search is sometimes initiated by appending a * to the beginning of the search criterion (e.g. in local_and_global_search). search_string: (string) The name or dbref to search for. """ search_string = utils.to_unicode(search_string).lstrip('*') dbref = self.dbref(search_string) if not dbref: # not a dbref. Search by name. player_matches = User.objects.filter(username__iexact=search_string) if player_matches: dbref = player_matches[0].id # use the id to find the player return self.get_object_with_user(dbref) @returns_typeclass_list def get_objs_with_key_and_typeclass(self, oname, otypeclass_path): """ Returns objects based on simultaneous key and typeclass match. """ return self.filter(db_key__iexact=oname).filter(db_typeclass_path__exact=otypeclass_path) # attr/property related @returns_typeclass_list def get_objs_with_attr(self, attribute_name, location=None): """ Returns all objects having the given attribute_name defined at all. """ from src.objects.models import ObjAttribute lstring = "" if location: lstring = ", db_obj__db_location=location" attrs = eval("ObjAttribute.objects.filter(db_key=attribute_name%s)" % lstring) return [attr.obj for attr in attrs] @returns_typeclass_list def get_objs_with_attr_match(self, attribute_name, attribute_value, location=None, exact=False): """ Returns all objects having the valid attrname set to the given value. Note that no conversion is made to attribute_value, and so it can accept also non-strings. """ from src.objects.models import ObjAttribute lstring = "" if location: lstring = ", db_obj__db_location=location" attrs = eval("ObjAttribute.objects.filter(db_key=attribute_name%s)" % lstring) if exact: return [attr.obj for attr in attrs if attribute_value == attr.value] else: return [attr.obj for attr in attrs if utils.to_unicode(attribute_value) in str(attr.value)] @returns_typeclass_list def get_objs_with_db_property(self, property_name, location=None): """ Returns all objects having a given db field property. property_name = search string location - actual location object to restrict to """ lstring = "" if location: lstring = ".filter(db_location=location)" try: return eval("self.exclude(db_%s=None)%s" % (property_name, lstring)) except exceptions.FieldError: return [] @returns_typeclass_list def get_objs_with_db_property_match(self, property_name, property_value, location, exact=False): """ Returns all objects having a given db field property """ lstring = "" if location: lstring = ", db_location=location" try: if exact: return eval("self.filter(db_%s__iexact=property_value%s)" % (property_name, lstring)) else: return eval("self.filter(db_%s__icontains=property_value%s)" % (property_name, lstring)) except exceptions.FieldError: return [] @returns_typeclass_list def get_objs_with_key_or_alias(self, ostring, location, exact=False): """ Returns objects based on key or alias match """ lstring_key, lstring_alias, estring = "", "", "icontains" if location: lstring_key = ", db_location=location" lstring_alias = ", db_obj__db_location=location" if exact: estring = "__iexact" else: estring = "__istartswith" matches = eval("self.filter(db_key%s=ostring%s)" % (estring, lstring_key)) if not matches: alias_matches = eval("self.model.alias_set.related.model.objects.filter(db_key%s=ostring%s)" % (estring, lstring_alias)) matches = [alias.db_obj for alias in alias_matches] return matches # main search methods and helper functions @returns_typeclass_list def get_contents(self, location, excludeobj=None): """ Get all objects that has a location set to this one. """ estring = "" if excludeobj: estring = ".exclude(db_key=excludeobj)" return eval("self.filter(db_location__id=location.id)%s" % estring) @returns_typeclass_list def object_search(self, ostring, caller=None, global_search=False, attribute_name=None, location=None): """ Search as an object and return results. The result is always an Object. If * is appended (player search, a Character controlled by this Player is looked for. The Character is returned, not the Player. Use player_search to find Player objects. Always returns a list. ostring: (string) The string to compare names against. Can be a dbref. If name is appended by *, a player is searched for. caller: (Object) The object performing the search. global_search: Search all objects, not just the current location/inventory attribute_name: (string) Which attribute to search in each object. If None, the default 'key' attribute is used. location: If None, character.location will be used. """ #ostring = str(ostring).strip() if not ostring: return [] # Easiest case - dbref matching (always exact) dbref = self.dbref(ostring) if dbref: dbref_match = self.dbref_search(dbref) if dbref_match: return [dbref_match] if not location and caller and hasattr(caller, "location"): location = caller.location # Test some common self-references if location and ostring == 'here': return [location] if caller and ostring in ['me', 'self']: return [caller] if caller and ostring in ['*me', '*self']: return [caller] # Test if we are looking for an object controlled by a # specific player if utils.to_unicode(ostring).startswith("*"): # Player search - try to find obj by its player's name player_match = self.get_object_with_player(ostring) if player_match is not None: return [player_match] # Search for keys, aliases or other attributes search_locations = [None] # this means a global search if not global_search and location: # Test if we are referring to the current room if location and (ostring.lower() == location.key.lower() or ostring.lower() in [alias.lower() for alias in location.aliases]): return [location] # otherwise, setup the locations to search in search_locations = [location] if caller: search_locations.append(caller) def local_and_global_search(ostring, exact=False): "Helper method for searching objects" matches = [] for location in search_locations: if attribute_name: # Attribute/property search. First, search for db_<attrname> matches on the model matches.extend(self.get_objs_with_db_property_match(attribute_name, ostring, location, exact)) if not matches: # Next, try Attribute matches matches.extend(self.get_objs_with_attr_match(attribute_name, ostring, location, exact)) else: # No attribute/property named. Do a normal key/alias-search matches.extend(self.get_objs_with_key_or_alias(ostring, location, exact)) return matches # Search through all possibilities. match_number = None matches = local_and_global_search(ostring, exact=True) if not matches: # if we have no match, check if we are dealing with an "N-keyword" query - if so, strip it. match_number, ostring = AT_MULTIMATCH_INPUT(ostring) if match_number != None and ostring: # Run search again, without match number: matches = local_and_global_search(ostring, exact=True) if ostring and (len(matches) > 1 or not matches): # Already multimatch or no matches. Run a fuzzy matching. matches = local_and_global_search(ostring, exact=False) elif len(matches) > 1: # multiple matches already. Run a fuzzy search. This catches partial matches (suggestions) matches = local_and_global_search(ostring, exact=False) # deal with the result if len(matches) > 1 and match_number != None: # We have multiple matches, but a N-type match number is available to separate them. try: matches = [matches[match_number]] except IndexError: pass # This is always a list. return matches # # ObjectManager Copy method # def copy_object(self, original_object, new_key=None, new_location=None, new_player=None, new_home=None, new_permissions=None, new_locks=None, new_aliases=None, new_destination=None): """ Create and return a new object as a copy of the original object. All will be identical to the original except for the arguments given specifically to this method. original_object (obj) - the object to make a copy from new_key (str) - name the copy differently from the original. new_location (obj) - if not None, change the location new_home (obj) - if not None, change the Home new_aliases (list of strings) - if not None, change object aliases. new_destination (obj) - if not None, change destination """ # get all the object's stats typeclass_path = original_object.typeclass_path if not new_key: new_key = original_object.key if not new_location: new_location = original_object.location if not new_home: new_home = original_object.home if not new_player: new_player = original_object.player if not new_aliases: new_aliases = original_object.aliases if not new_locks: new_locks = original_object.db_lock_storage if not new_permissions: new_permissions = original_object.permissions if not new_destination: new_destination = original_object.destination # create new object from src.utils import create from src.scripts.models import ScriptDB new_object = create.create_object(typeclass_path, key=new_key, location=new_location, home=new_home, player=new_player, permissions=new_permissions, locks=new_locks, aliases=new_aliases, destination=new_destination) if not new_object: return None # copy over all attributes from old to new. for attr in original_object.get_all_attributes(): new_object.set_attribute(attr.key, attr.value) # copy over all cmdsets, if any for icmdset, cmdset in enumerate(original_object.cmdset.all()): if icmdset == 0: new_object.cmdset.add_default(cmdset) else: new_object.cmdset.add(cmdset) # copy over all scripts, if any for script in original_object.scripts.all(): ScriptDB.objects.copy_script(script, new_obj=new_object.dbobj) return new_object
Python
""" This module defines the database models for all in-game objects, that is, all objects that has an actual existence in-game. Each database object is 'decorated' with a 'typeclass', a normal python class that implements all the various logics needed by the game in question. Objects created of this class transparently communicate with its related database object for storing all attributes. The admin should usually not have to deal directly with this database object layer. Attributes are separate objects that store values persistently onto the database object. Like everything else, they can be accessed transparently through the decorating TypeClass. """ import traceback from django.db import models from django.conf import settings from django.contrib.contenttypes.models import ContentType from src.utils.idmapper.models import SharedMemoryModel from src.typeclasses.models import Attribute, TypedObject, TypeNick, TypeNickHandler from src.typeclasses.typeclass import TypeClass from src.objects.manager import ObjectManager from src.players.models import PlayerDB from src.server.models import ServerConfig from src.commands.cmdsethandler import CmdSetHandler from src.commands import cmdhandler from src.scripts.scripthandler import ScriptHandler from src.utils import logger from src.utils.utils import is_iter, to_unicode, to_str, mod_import #PlayerDB = ContentType.objects.get(app_label="players", model="playerdb").model_class() AT_SEARCH_RESULT = mod_import(*settings.SEARCH_AT_RESULT.rsplit('.', 1)) #------------------------------------------------------------ # # ObjAttribute # #------------------------------------------------------------ class ObjAttribute(Attribute): "Attributes for ObjectDB objects." db_obj = models.ForeignKey("ObjectDB") class Meta: "Define Django meta options" verbose_name = "Object Attribute" verbose_name_plural = "Object Attributes" #------------------------------------------------------------ # # Alias # #------------------------------------------------------------ class Alias(SharedMemoryModel): """ This model holds a range of alternate names for an object. These are intrinsic properties of the object. The split is so as to allow for effective global searches also by alias. """ db_key = models.CharField('alias', max_length=255, db_index=True) db_obj = models.ForeignKey("ObjectDB", verbose_name='object') class Meta: "Define Django meta options" verbose_name = "Object alias" verbose_name_plural = "Object aliases" def __unicode__(self): return u"%s" % self.db_key def __str__(self): return str(self.db_key) #------------------------------------------------------------ # # Object Nicks # #------------------------------------------------------------ class ObjectNick(TypeNick): """ The default nick types used by Evennia are: inputline (default) - match against all input player - match against player searches obj - match against object searches channel - used to store own names for channels """ db_obj = models.ForeignKey("ObjectDB", verbose_name='object') class Meta: "Define Django meta options" verbose_name = "Nickname for Objects" verbose_name_plural = "Nicknames for Objects" unique_together = ("db_nick", "db_type", "db_obj") class ObjectNickHandler(TypeNickHandler): """ Handles nick access and setting. Accessed through ObjectDB.nicks """ NickClass = ObjectNick #------------------------------------------------------------ # # ObjectDB # #------------------------------------------------------------ class ObjectDB(TypedObject): """ All objects in the game use the ObjectDB model to store data in the database. This is handled transparently through the typeclass system. Note that the base objectdb is very simple, with few defined fields. Use attributes to extend your type class with new database-stored variables. The TypedObject supplies the following (inherited) properties: key - main name name - alias for key typeclass_path - the path to the decorating typeclass typeclass - auto-linked typeclass date_created - time stamp of object creation permissions - perm strings locks - lock definitions (handler) dbref - #id of object db - persistent attribute storage ndb - non-persistent attribute storage The ObjectDB adds the following properties: player - optional connected player location - in-game location of object home - safety location for object (handler) scripts - scripts assigned to object (handler from typeclass) cmdset - active cmdset on object (handler from typeclass) aliases - aliases for this object (property) nicks - nicknames for *other* things in Evennia (handler) sessions - sessions connected to this object (see also player) has_player - bool if an active player is currently connected contents - other objects having this object as location exits - exits from this object """ # # ObjectDB Database model setup # # # inherited fields (from TypedObject): # db_key (also 'name' works), db_typeclass_path, db_date_created, # db_permissions # # These databse fields (including the inherited ones) are all set # using their corresponding properties, named same as the field, # but withtout the db_* prefix. # If this is a character object, the player is connected here. db_player = models.ForeignKey("players.PlayerDB", blank=True, null=True, verbose_name='player', help_text='a Player connected to this object, if any.') # The location in the game world. Since this one is likely # to change often, we set this with the 'location' property # to transparently handle Typeclassing. db_location = models.ForeignKey('self', related_name="locations_set",db_index=True, blank=True, null=True, verbose_name='game location') # a safety location, this usually don't change much. db_home = models.ForeignKey('self', related_name="homes_set", blank=True, null=True, verbose_name='home location') # destination of this object - primarily used by exits. db_destination = models.ForeignKey('self', related_name="destinations_set", db_index=True, blank=True, null=True, verbose_name='destination', help_text='a destination, used only by exit objects.') # database storage of persistant cmdsets. db_cmdset_storage = models.CharField('cmdset', max_length=255, null=True, blank=True, help_text="optional python path to a cmdset class.") # Database manager objects = ObjectManager() # Add the object-specific handlers def __init__(self, *args, **kwargs): "Parent must be initialized first." TypedObject.__init__(self, *args, **kwargs) # handlers self.cmdset = CmdSetHandler(self) self.cmdset.update(init_mode=True) self.scripts = ScriptHandler(self) self.nicks = ObjectNickHandler(self) # store the attribute class # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that allows the user to do self.attr = value, # value = self.attr and del self.attr respectively (where self # is the object in question). # aliases property (wraps (db_aliases) #@property def aliases_get(self): "Getter. Allows for value = self.aliases" return list(Alias.objects.filter(db_obj=self).values_list("db_key", flat=True)) #@aliases.setter def aliases_set(self, aliases): "Setter. Allows for self.aliases = value" if not is_iter(aliases): aliases = [aliases] for alias in aliases: new_alias = Alias(db_key=alias, db_obj=self) new_alias.save() #@aliases.deleter def aliases_del(self): "Deleter. Allows for del self.aliases" for alias in Alias.objects.filter(db_obj=self): alias.delete() aliases = property(aliases_get, aliases_set, aliases_del) # player property (wraps db_player) #@property def player_get(self): """ Getter. Allows for value = self.player. We have to be careful here since Player is also a TypedObject, so as to not create a loop. """ try: return object.__getattribute__(self, 'db_player') except AttributeError: return None #@player.setter def player_set(self, player): "Setter. Allows for self.player = value" if isinstance(player, TypeClass): player = player.dbobj self.db_player = player self.save() #@player.deleter def player_del(self): "Deleter. Allows for del self.player" self.db_player = None self.save() player = property(player_get, player_set, player_del) # location property (wraps db_location) #@property def location_get(self): "Getter. Allows for value = self.location." loc = self.db_location if loc: return loc.typeclass return None #@location.setter def location_set(self, location): "Setter. Allows for self.location = location" try: if location == None or type(location) == ObjectDB: # location is None or a valid object loc = location elif ObjectDB.objects.dbref(location): # location is a dbref; search loc = ObjectDB.objects.dbref_search(location) if loc and hasattr(loc,'dbobj'): loc = loc.dbobj else: loc = location.dbobj else: loc = location.dbobj self.db_location = loc self.save() except Exception: string = "Cannot set location: " string += "%s is not a valid location." self.msg(string % location) logger.log_trace(string) raise #@location.deleter def location_del(self): "Deleter. Allows for del self.location" self.db_location = None self.save() location = property(location_get, location_set, location_del) # home property (wraps db_home) #@property def home_get(self): "Getter. Allows for value = self.home" home = self.db_home if home: return home.typeclass return None #@home.setter def home_set(self, home): "Setter. Allows for self.home = value" try: if home == None or type(home) == ObjectDB: hom = home elif ObjectDB.objects.dbref(home): hom = ObjectDB.objects.dbref_search(home) if hom and hasattr(hom,'dbobj'): hom = hom.dbobj else: hom = home.dbobj else: hom = home.dbobj self.db_home = hom except Exception: string = "Cannot set home: " string += "%s is not a valid home." self.msg(string % home) logger.log_trace(string) #raise self.save() #@home.deleter def home_del(self): "Deleter. Allows for del self.home." self.db_home = None self.save() home = property(home_get, home_set, home_del) # destination property (wraps db_destination) #@property def destination_get(self): "Getter. Allows for value = self.destination." dest = self.db_destination if dest: return dest.typeclass return None #@destination.setter def destination_set(self, destination): "Setter. Allows for self.destination = destination" try: if destination == None or type(destination) == ObjectDB: # destination is None or a valid object dest = destination elif ObjectDB.objects.dbref(destination): # destination is a dbref; search dest = ObjectDB.objects.dbref_search(destination) if dest and hasattr(dest,'dbobj'): dest = dest.dbobj else: dest = destination.dbobj else: dest = destination.dbobj self.db_destination = dest self.save() except Exception: string = "Cannot set destination: " string += "%s is not a valid destination." self.msg(string % destination) logger.log_trace(string) raise #@destination.deleter def destination_del(self): "Deleter. Allows for del self.destination" self.db_destination = None self.save() destination = property(destination_get, destination_set, destination_del) #@property for consistent aliases access throughout Evennia #@aliases.setter def aliases_set(self, aliases): "Adds an alias to object" if not is_iter(aliases): aliases = [aliases] for alias in aliases: query = Alias.objects.filter(db_obj=self, db_key__iexact=alias) if query.count(): continue new_alias = Alias(db_key=alias, db_obj=self) new_alias.save() #@aliases.getter def aliases_get(self): "Return a list of all aliases defined on this object." return list(Alias.objects.filter(db_obj=self).values_list("db_key", flat=True)) #@aliases.deleter def aliases_del(self): "Removes aliases from object" query = Alias.objects.filter(db_obj=self) if query: query.delete() aliases = property(aliases_get, aliases_set, aliases_del) # cmdset_storage property #@property def cmdset_storage_get(self): "Getter. Allows for value = self.name. Returns a list of cmdset_storage." if self.db_cmdset_storage: return [path.strip() for path in self.db_cmdset_storage.split(',')] return [] #@cmdset_storage.setter def cmdset_storage_set(self, value): "Setter. Allows for self.name = value. Stores as a comma-separated string." if is_iter(value): value = ",".join([str(val).strip() for val in value]) self.db_cmdset_storage = value self.save() #@cmdset_storage.deleter def cmdset_storage_del(self): "Deleter. Allows for del self.name" self.db_cmdset_storage = "" self.save() cmdset_storage = property(cmdset_storage_get, cmdset_storage_set, cmdset_storage_del) class Meta: "Define Django meta options" verbose_name = "Object" verbose_name_plural = "Objects" # # ObjectDB class access methods/properties # # this is required to properly handle attributes and typeclass loading. #attribute_model_path = "src.objects.models" #attribute_model_name = "ObjAttribute" typeclass_paths = settings.OBJECT_TYPECLASS_PATHS attribute_class = ObjAttribute # this is used by all typedobjects as a fallback try: default_typeclass_path = settings.BASE_OBJECT_TYPECLASS except Exception: default_typeclass_path = "src.objects.objects.Object" #@property def sessions_get(self): """ Retrieve sessions connected to this object. """ # if the player is not connected, this will simply be an empty list. if self.player: return self.player.sessions return [] sessions = property(sessions_get) #@property def has_player_get(self): """ Convenience function for checking if an active player is currently connected to this object """ return any(self.sessions) has_player = property(has_player_get) is_player = property(has_player_get) #@property def is_superuser_get(self): "Check if user has a player, and if so, if it is a superuser." return any(self.sessions) and self.player.is_superuser is_superuser = property(is_superuser_get) #@property def contents_get(self, exclude=None): """ Returns the contents of this object, i.e. all objects that has this object set as its location. """ return ObjectDB.objects.get_contents(self, excludeobj=exclude) contents = property(contents_get) #@property def exits_get(self): """ Returns all exits from this object, i.e. all objects at this location having the property destination != None. """ return [exi for exi in self.contents if exi.destination] exits = property(exits_get) # # Main Search method # def search(self, ostring, global_search=False, attribute_name=None, use_nicks=False, location=None, ignore_errors=False, player=False): """ Perform a standard object search in the database, handling multiple results and lack thereof gracefully. ostring: (str) The string to match object names against. Obs - To find a player, append * to the start of ostring. global_search: Search all objects, not just the current location/inventory attribute_name: (string) Which attribute to match (if None, uses default 'name') use_nicks : Use nickname replace (off by default) location : If None, use caller's current location ignore_errors : Don't display any error messages even if there are none/multiple matches - just return the result as a list. player : Don't search for an Object but a Player. This will also find players that don't currently have a character. Use *<string> to search for objects controlled by a specific player. Note that the object controlled by the player will be returned, not the player object itself. This also means that this will not find Players without a character. Use the keyword player=True to find player objects. Note - for multiple matches, the engine accepts a number linked to the key in order to separate the matches from each other without showing the dbref explicitly. Default syntax for this is 'N-searchword'. So for example, if there are three objects in the room all named 'ball', you could address the individual ball as '1-ball', '2-ball', '3-ball' etc. """ if use_nicks: if ostring.startswith('*') or player: # player nick replace ostring = self.nicks.get(ostring.lstrip('*'), nick_type="player") if not player: ostring = "*%s" % ostring else: # object nick replace ostring = self.nicks.get(ostring, nick_type="object") if player: if ostring in ("me", "self", "*me", "*self"): results = [self.player] else: results = PlayerDB.objects.player_search(ostring.lstrip('*')) else: results = ObjectDB.objects.object_search(ostring, caller=self, global_search=global_search, attribute_name=attribute_name, location=location) if ignore_errors: return results # this import is cache after the first call. return AT_SEARCH_RESULT(self, ostring, results, global_search) # # Execution/action methods # def execute_cmd(self, raw_string): """ Do something as this object. This command transparently lets its typeclass execute the command. raw_string - raw command input coming from the command line. The return from this method is None for all default commands (it's the return value of cmd.func()) and is not used in any way by the engine. It might be useful for admins wanting to implement some sort of 'nested' command structure though, """ # nick replacement - we require full-word matching. # do text encoding conversion raw_string = to_unicode(raw_string) raw_list = raw_string.split(None) raw_list = [" ".join(raw_list[:i+1]) for i in range(len(raw_list)) if raw_list[:i+1]] for nick in ObjectNick.objects.filter(db_obj=self, db_type__in=("inputline","channel")): if nick.db_nick in raw_list: raw_string = raw_string.replace(nick.db_nick, nick.db_real, 1) break return cmdhandler.cmdhandler(self.typeclass, raw_string) def msg(self, message, from_obj=None, data=None): """ Emits something to any sessions attached to the object. message (str): The message to send from_obj (obj): object that is sending. data (object): an optional data object that may or may not be used by the protocol. """ # This is an important function that must always work. # we use a different __getattribute__ to avoid recursive loops. if object.__getattribute__(self, 'player'): object.__getattribute__(self, 'player').msg(message, from_obj=from_obj, data=data) def emit_to(self, message, from_obj=None, data=None): "Deprecated. Alias for msg" logger.log_depmsg("emit_to() is deprecated. Use msg() instead.") self.msg(message, from_obj, data) def msg_contents(self, message, exclude=None, from_obj=None, data=None): """ Emits something to all objects inside an object. exclude is a list of objects not to send to. See self.msg() for more info. """ contents = self.contents if exclude: if not is_iter(exclude): exclude = [exclude] contents = [obj for obj in contents if (obj not in exclude and obj not in exclude)] for obj in contents: obj.msg(message, from_obj=from_obj, data=data) def emit_to_contents(self, message, exclude=None, from_obj=None, data=None): "Deprecated. Alias for msg_contents" logger.log_depmsg("emit_to_contents() is deprecated. Use msg_contents() instead.") self.msg_contents(message, exclude=exclude, from_obj=from_obj, data=data) def move_to(self, destination, quiet=False, emit_to_obj=None): """ Moves this object to a new location. destination: (Object) Reference to the object to move to. This can also be an exit object, in which case the destination property is used as destination. quiet: (bool) If true, don't emit left/arrived messages. emit_to_obj: (Object) object to receive error messages """ def logerr(string=""): trc = traceback.format_exc() errstring = "%s%s" % (trc, string) logger.log_trace() self.msg(errstring) errtxt = "Couldn't perform move ('%s'). Contact an admin." if not emit_to_obj: emit_to_obj = self if not destination: emit_to_obj.msg("The destination doesn't exist.") return if destination.destination: # traverse exits destination = destination.destination # Before the move, call eventual pre-commands. try: if not self.at_before_move(destination): return except Exception: logerr(errtxt % "at_before_move()") #emit_to_obj.msg(errtxt % "at_before_move()") #logger.log_trace() return False # Save the old location source_location = self.location if not source_location: # there was some error in placing this room. # we have to set one or we won't be able to continue if self.home: source_location = self.home else: default_home = ObjectDB.objects.get_id(settings.CHARACTER_DEFAULT_HOME) source_location = default_home # Call hook on source location try: source_location.at_object_leave(self, destination) except Exception: logerr(errtxt % "at_object_leave()") #emit_to_obj.msg(errtxt % "at_object_leave()") #logger.log_trace() return False if not quiet: #tell the old room we are leaving try: self.announce_move_from(destination) except Exception: logerr(errtxt % "at_announce_move()") #emit_to_obj.msg(errtxt % "at_announce_move()" ) #logger.log_trace() return False # Perform move try: self.location = destination except Exception: emit_to_obj.msg(errtxt % "location change") logger.log_trace() return False if not quiet: # Tell the new room we are there. try: self.announce_move_to(source_location) except Exception: logerr(errtxt % "announce_move_to()") #emit_to_obj.msg(errtxt % "announce_move_to()") #logger.log_trace() return False # Perform eventual extra commands on the receiving location # (the object has already arrived at this point) try: destination.at_object_receive(self, source_location) except Exception: logerr(errtxt % "at_object_receive()") #emit_to_obj.msg(errtxt % "at_object_receive()") #logger.log_trace() return False # Execute eventual extra commands on this object after moving it # (usually calling 'look') try: self.at_after_move(source_location) except Exception: logerr(errtxt % "at_after_move") #emit_to_obj.msg(errtxt % "at_after_move()") #logger.log_trace() return False return True # # Object Swap, Delete and Cleanup methods # def clear_exits(self): """ Destroys all of the exits and any exits pointing to this object as a destination. """ for out_exit in [exi for exi in ObjectDB.objects.get_contents(self) if exi.db_destination]: out_exit.delete() for in_exit in ObjectDB.objects.filter(db_destination=self): in_exit.delete() def clear_contents(self): """ Moves all objects (players/things) to their home location or to default home. """ # Gather up everything that thinks this is its location. objs = ObjectDB.objects.filter(db_location=self) default_home_id = int(settings.CHARACTER_DEFAULT_HOME) try: default_home = ObjectDB.objects.get(id=default_home_id) if default_home.id == self.id: # we are deleting default home! default_home = None except Exception: string = "Could not find default home '(#%d)'." logger.log_errmsg(string % default_home_id) default_home = None for obj in objs: home = obj.home # Obviously, we can't send it back to here. if not home or (home and home.id == self.id): obj.home = default_home # If for some reason it's still None... if not obj.home: string = "Missing default home, '%s(#%d)' " string += "now has a null location." obj.location = None obj.msg("Something went wrong! You are dumped into nowhere. Contact an admin.") logger.log_errmsg(string % (obj.name, obj.id)) return if obj.has_player: if home: string = "Your current location has ceased to exist," string += " moving you to %s(#%d)." obj.msg(string % (home.name, home.id)) else: # Famous last words: The player should never see this. string = "This place should not exist ... contact an admin." obj.msg(string) obj.move_to(home) def copy(self, new_key=None): """ Makes an identical copy of this object and returns it. The copy will be named <key>_copy by default. If you want to customize the copy by changing some settings, use the manager method copy_object directly. """ if not new_key: new_key = "%s_copy" % self.key return ObjectDB.objects.copy_object(self, new_key=new_key) delete_iter = 0 def delete(self): """ Deletes this object. Before deletion, this method makes sure to move all contained objects to their respective home locations, as well as clean up all exits to/from the object. """ if self.delete_iter > 0: # make sure to only call delete once on this object # (avoid recursive loops) return False if not self.at_object_delete(): # this is an extra pre-check # run before deletion mechanism # is kicked into gear. self.delete_iter == 0 return False self.delete_iter += 1 # See if we need to kick the player off. for session in self.sessions: session.msg("Your character %s has been destroyed." % self.name) # no need to disconnect, Player just jumps to OOC mode. # sever the connection (important!) if object.__getattribute__(self, 'player') and self.player: self.player.character = None self.player = None for script in self.scripts.all(): script.stop() # if self.player: # self.player.user.is_active = False # self.player.user.save( # Destroy any exits to and from this room, if any self.clear_exits() # Clear out any non-exit objects located within the object self.clear_contents() # Perform the deletion of the object super(ObjectDB, self).delete() return True
Python
""" This is the basis of the typeclass system. The idea is have the object as a normal class with the database-connection tied to itself through a property. The instances of all the different object types are all tied to their own database object stored in the 'dbobj' property. All attribute get/set operations are channeled transparently to the database object as desired. You should normally never have to worry about the database abstraction, just do everything on the TypeClass object. That an object is controlled by a player/user is just defined by its 'user' property being set. This means a user may switch which object they control by simply linking to a new object's user property. """ from src.typeclasses.typeclass import TypeClass from src.commands import cmdset, command # # Base class to inherit from. # class Object(TypeClass): """ This is the base class for all in-game objects. Inherit from this to create different types of objects in the game. """ def __eq__(self, other): """ This has be located at this level, having it in the parent doesn't work. """ result = other and other.id == self.id try: uresult = other and (other.user.id == self.user.id) except AttributeError: uresult = False return result or uresult # hooks called by the game engine def basetype_setup(self): """ This sets up the default properties of an Object, just before the more general at_object_creation. Don't change this, instead edit at_object_creation() to overload the defaults (it is called after this one). """ # the default security setup fallback for a generic # object. Overload in child for a custom setup. Also creation # commands may set this (create an item and you should be its # controller, for example) dbref = self.dbobj.dbref self.locks.add("control:id(%s) or perm(Immortals)" % dbref) # edit locks/permissions, delete self.locks.add("examine:perm(Builders)") # examine properties self.locks.add("view:all()") # look at object (visibility) self.locks.add("edit:perm(Wizards)") # edit properties/attributes self.locks.add("delete:perm(Wizards)") # delete object self.locks.add("get:all()") # pick up object self.locks.add("call:true()") # allow to call commands on this object self.locks.add("puppet:id(%s) or perm(Immortals) or pperm(Immortals)" % dbref) # restricts puppeting of this object def at_object_creation(self): """ Called once, when this object is first created. """ pass def at_init(self): """ This is always called whenever this object is initiated -- that is, whenever it its typeclass is cached from memory. This happens on-demand first time the object is used or activated in some way after being created but also after each server restart or reload. """ pass def basetype_posthook_setup(self): """ Called once, after basetype_setup and at_object_creation. This should generally not be overloaded unless you are redefining how a room/exit/object works. It allows for basetype-like setup after the object is created. An example of this is EXITs, who need to know keys, aliases, locks etc to set up their exit-cmdsets. """ pass def at_server_reload(self): """ This hook is called whenever the server is shutting down for restart/reboot. If you want to, for example, save non-persistent properties across a restart, this is the place to do it. """ pass def at_server_shutdown(self): """ This hook is called whenever the server is shutting down fully (i.e. not for a restart). """ pass def at_cmdset_get(self): """ Called just before cmdsets on this object are requested by the command handler. If changes need to be done on the fly to the cmdset before passing them on to the cmdhandler, this is the place to do it. This is called also if the object currently have no cmdsets. """ pass def at_first_login(self): """ Only called once, the very first time the user logs in. """ pass def at_pre_login(self): """ Called every time the user logs in, before they are actually logged in. """ pass def at_post_login(self): """ Called at the end of the login process, just before letting them loose. """ pass def at_disconnect(self): """ Called just before user is disconnected. """ pass # hooks called when moving the object def at_before_move(self, destination): """ Called just before starting to move this object to destination. destination - the object we are moving to If this method returns False/None, the move is cancelled before it is even started. """ #return has_perm(self, destination, "can_move") return True def announce_move_from(self, destination): """ Called if the move is to be announced. This is called while we are still standing in the old location. destination - the place we are going to. """ if not self.location: return name = self.name loc_name = "" loc_name = self.location.name dest_name = destination.name string = "%s is leaving %s, heading for %s." self.location.msg_contents(string % (name, loc_name, dest_name), exclude=self) def announce_move_to(self, source_location): """ Called after the move if the move was not quiet. At this point we are standing in the new location. source_location - the place we came from """ name = self.name if not source_location and self.location.has_player: # This was created from nowhere and added to a player's # inventory; it's probably the result of a create command. string = "You now have %s in your possession." % name self.location.msg(string) return src_name = "nowhere" loc_name = self.location.name if source_location: src_name = source_location.name string = "%s arrives to %s from %s." self.location.msg_contents(string % (name, loc_name, src_name), exclude=self) def at_after_move(self, source_location): """ Called after move has completed, regardless of quiet mode or not. Allows changes to the object due to the location it is now in. source_location - where we came from """ pass def at_object_leave(self, moved_obj, target_location): """ Called just before an object leaves from inside this object moved_obj - the object leaving target_location - where the object is going. """ pass def at_object_receive(self, moved_obj, source_location): """ Called after an object has been moved into this object. moved_obj - the object moved into this one source_location - where moved_object came from. """ pass def at_before_traverse(self, traversing_object): """ Called just before an object uses this object to traverse to another object (i.e. this object is a type of Exit) The target location should normally be available as self.destination. """ pass def at_after_traverse(self, traversing_object, source_location): """ Called just after an object successfully used this object to traverse to another object (i.e. this object is a type of Exit) The target location should normally be available as self.destination. """ pass def at_failed_traverse(self, traversing_object): """ This is called if an object fails to traverse this object for some reason. It will not be called if the attribute err_traverse is defined, that attribute will then be echoed back instead. """ pass # hooks called by the default cmdset. def return_appearance(self, pobject): """ This is a convenient hook for a 'look' command to call. """ if not pobject: return string = "{c%s{n" % self.name desc = self.attr("desc") if desc: string += "\n %s" % desc exits = [] users = [] things = [] for content in [con for con in self.contents if con.access(pobject, 'view')]: if content == pobject: continue name = content.name if content.destination: exits.append(name) elif content.has_player: users.append(name) else: things.append(name) if exits: string += "\n{wExits:{n " + ", ".join(exits) if users or things: string += "\n{wYou see: {n" if users: string += "{c" + ", ".join(users) + "{n " if things: string += ", ".join(things) return string def at_msg_receive(self, msg, from_obj=None, data=None): """ This hook is called whenever someone sends a message to this object. Note that from_obj may be None if the sender did not include itself as an argument to the obj.msg() call - so you have to check for this. . Consider this a pre-processing method before msg is passed on to the user sesssion. If this method returns False, the msg will not be passed on. msg = the message received from_obj = the one sending the message """ return True def at_msg_send(self, msg, to_obj=None, data=None): """ This is a hook that is called when /this/ object sends a message to another object with obj.msg() while also specifying that it is the one sending. Note that this method is executed on the object passed along with the msg() function (i.e. using obj.msg(msg, caller) will then launch caller.at_msg()) and if no object was passed, it will never be called. """ pass def at_desc(self, looker=None): """ This is called whenever someone looks at this object. Looker is the looking object. """ pass def at_object_delete(self): """ Called just before the database object is permanently delete()d from the database. If this method returns False, deletion is aborted. """ return True def at_get(self, getter): """ Called when this object has been picked up. Obs- this method cannot stop the pickup - use permissions for that! getter - the object getting this object. """ pass def at_drop(self, dropper): """ Called when this object has been dropped. dropper - the object which just dropped this object. """ pass def at_say(self, speaker, message): """ Called on this object if an object inside this object speaks. The string returned from this method is the final form of the speech. Obs - you don't have to add things like 'you say: ' or similar, that is handled by the say command. speaker - the object speaking message - the words spoken. """ return message # # Base Player object # class Character(Object): """ This is just like the Object except it implements its own version of the at_object_creation to set up the script that adds the default cmdset to the object. """ def basetype_setup(self): """ Setup character-specific security Don't change this, instead edit at_object_creation() to overload the defaults (it is called after this one). """ super(Character, self).basetype_setup() self.locks.add("get:false()") # noone can pick up the character self.locks.add("call:false()") # no commands can be called on character from outside # add the default cmdset from settings import CMDSET_DEFAULT self.cmdset.add_default(CMDSET_DEFAULT, permanent=True) # no other character should be able to call commands on the Character. self.cmdset.outside_access = False def at_object_creation(self): """ All this does (for now) is to add the default cmdset. Since the script is permanently stored to this object (the permanent keyword creates a script to do this), we should never need to do this again for as long as this object exists. """ pass def at_after_move(self, source_location): "Default is to look around after a move." self.execute_cmd('look') def at_disconnect(self): """ We stove away the character when logging off, otherwise the character object will remain in the room also after the player logged off ("headless", so to say). """ if self.location: # have to check, in case of multiple connections closing self.location.msg_contents("%s has left the game." % self.name, exclude=[self]) self.db.prelogout_location = self.location self.location = None def at_post_login(self): """ This recovers the character again after having been "stoved away" at disconnect. """ if self.db.prelogout_location: # try to recover self.location = self.db.prelogout_location if self.location == None: # make sure location is never None (home should always exist) self.location = self.home # save location again to be sure self.db.prelogout_location = self.location self.location.msg_contents("%s has entered the game." % self.name, exclude=[self]) self.location.at_object_receive(self, self.location) # # Base Room object # class Room(Object): """ This is the base room object. It's basically like any Object except its location is None. """ def basetype_setup(self): """ Simple setup, shown as an example (since default is None anyway) Don't change this, instead edit at_object_creation() to overload the defaults (it is called after this one). """ super(Room, self).basetype_setup() self.locks.add("get:false();puppet:false()") # would be weird to puppet a room ... self.location = None # # Exits # class Exit(Object): """ This is the base exit object - it connects a location to another. This is done by the exit assigning a "command" on itself with the same name as the exit object (to do this we need to remember to re-create the command when the object is cached since it must be created dynamically depending on what the exit is called). This command (which has a high priority) will thus allow us to traverse exits simply by giving the exit-object's name on its own. """ # Helper classes and methods to implement the Exit. These need not # be overloaded unless one want to change the foundation for how # Exits work. See the end of the class for hook methods to overload. def create_exit_cmdset(self, exidbobj): """ Helper function for creating an exit command set + command. The command of this cmdset has the same name as the Exit object and allows the exit to react when the player enter the exit's name, triggering the movement between rooms. Note that exitdbobj is an ObjectDB instance. This is necessary for handling reloads and avoid tracebacks if this is called while the typeclass system is rebooting. """ class ExitCommand(command.Command): """ This is a command that simply cause the caller to traverse the object it is attached to. """ locks = "cmd:all()" # should always be set to this. obj = None def func(self): "Default exit traverse if no syscommand is defined." if self.obj.access(self.caller, 'traverse'): # we may traverse the exit. old_location = None if hasattr(self.caller, "location"): old_location = self.caller.location # call pre/post hooks and move object. self.obj.at_before_traverse(self.caller) self.caller.move_to(self.obj.destination) self.obj.at_after_traverse(self.caller, old_location) else: if self.obj.db.err_traverse: # if exit has a better error message, let's use it. self.caller.msg(self.obj.db.err_traverse) else: # No shorthand error message. Call hook. self.obj.at_failed_traverse(self.caller) # create an exit command. cmd = ExitCommand() cmd.key = exidbobj.db_key.strip().lower() cmd.obj = exidbobj cmd.aliases = exidbobj.aliases cmd.locks = str(exidbobj.locks) cmd.destination = exidbobj.db_destination # create a cmdset exit_cmdset = cmdset.CmdSet(None) exit_cmdset.key = '_exitset' exit_cmdset.priority = 9 exit_cmdset.duplicates = True # add command to cmdset exit_cmdset.add(cmd) return exit_cmdset # Command hooks def basetype_setup(self): """ Setup exit-security Don't change this, instead edit at_object_creation() to overload the default locks (it is called after this one). """ super(Exit, self).basetype_setup() # setting default locks (overload these in at_object_creation() self.locks.add("puppet:false()") # would be weird to puppet an exit ... self.locks.add("traverse:all()") # who can pass through exit by default self.locks.add("get:false()") # noone can pick up the exit # an exit should have a destination (this is replaced at creation time) if self.dbobj.location: self.destination = self.dbobj.location def at_cmdset_get(self): """ Called when the cmdset is requested from this object, just before the cmdset is actually extracted. If no Exit-cmdset is cached, create it now. """ if self.ndb.exit_reset or not self.cmdset.has_cmdset("_exitset", must_be_default=True): # we are resetting, or no exit-cmdset was set. Create one dynamically. self.cmdset.add_default(self.create_exit_cmdset(self.dbobj), permanent=False) self.ndb.exit_reset = False # this and other hooks are what usually can be modified safely. def at_object_creation(self): "Called once, when object is first created (after basetype_setup)." pass def at_failed_traverse(self, traversing_object): """ This is called if an object fails to traverse this object for some reason. It will not be called if the attribute "err_traverse" is defined, that attribute will then be echoed back instead as a convenient shortcut. (See also hooks at_before_traverse and at_after_traverse). """ traversing_object.msg("You cannot go there.")
Python
# -*- coding: utf-8 -*- """ Unit testing of the 'objects' Evennia component. Runs as part of the Evennia's test suite with 'manage.py test" Please add new tests to this module as needed. Guidelines: A 'test case' is testing a specific component and is defined as a class inheriting from unittest.TestCase. The test case class can have a method setUp() that creates and sets up the testing environment. All methods inside the test case class whose names start with 'test' are used as test methods by the runner. Inside the test methods, special member methods assert*() are used to test the behaviour. """ import sys try: from django.utils.unittest import TestCase except ImportError: from django.test import TestCase try: from django.utils import unittest except ImportError: import unittest from django.conf import settings from src.objects import models, objects from src.utils import create from src.commands.default import tests as commandtests from src.locks import tests as locktests class TestObjAttrs(TestCase): """ Test aspects of ObjAttributes """ def setUp(self): "set up the test" self.attr = models.ObjAttribute() self.obj1 = create.create_object(objects.Object, key="testobj1", location=None) self.obj2 = create.create_object(objects.Object, key="testobj2", location=self.obj1) def test_store_str(self): hstring = u"sdfv00=97sfjs842 ivfjlQKFos9GF^8dddsöäå-?%" self.obj1.db.testattr = hstring self.assertEqual(hstring, self.obj1.db.testattr) def test_store_obj(self): self.obj1.db.testattr = self.obj2 self.assertEqual(self.obj2 ,self.obj1.db.testattr) self.assertEqual(self.obj2.location, self.obj1.db.testattr.location) def suite(): """ This function is called automatically by the django test runner. This also runs the command tests defined in src/commands/default/tests.py. """ tsuite = unittest.TestSuite() tsuite.addTest(unittest.defaultTestLoader.loadTestsFromModule(sys.modules[__name__])) tsuite.addTest(unittest.defaultTestLoader.loadTestsFromModule(commandtests)) tsuite.addTest(unittest.defaultTestLoader.loadTestsFromModule(locktests)) return tsuite
Python
""" MSDP (Mud Server Data Protocol) This implements the MSDP protocol as per http://tintin.sourceforge.net/msdp/. MSDP manages out-of-band communication between the client and server, for updating health bars etc. !TODO - this is just a partial implementation and not used by telnet yet. """ import re # variables MSDP = chr(69) MSDP_VAR = chr(1) MSDP_VAL = chr(2) MSDP_TABLE_OPEN = chr(3) MSDP_TABLE_CLOSE = chr(4) MSDP_ARRAY_OPEN = chr(5) MSDP_ARRAY_CLOSE = chr(6) regex_array = re.compile(r"%s(.*?)%s%s(.*?)%s" % (MSDP_VAR, MSDP_VAL, MSDP_ARRAY_OPEN, MSDP_ARRAY_CLOSE)) # return 2-tuple regex_table = re.compile(r"%s(.*?)%s%s(.*?)%s" % (MSDP_VAR, MSDP_VAL, MSDP_TABLE_OPEN, MSDP_TABLE_CLOSE)) # return 2-tuple (may be nested) regex_varval = re.compile(r"%s(.*?)%s(.*?)[%s]" % (MSDP_VAR, MSDP_VAL, ENDING)) # return 2-tuple class Msdp(object): """ Implements the MSDP protocol. """ def __init__(self, protocol): """ Initiates by storing the protocol on itself and trying to determine if the client supports MSDP. """ self.protocol = protocol self.protocol.protocol_FLAGS['MSDP'] = False self.protocol.negotiationMap['MSDP'] = self.parse_msdp self.protocol.will(MSDP).addCallbacks(self.do_msdp, self.no_msdp) def no_msdp(self, option): "No msdp" pass def do_msdp(self, option): """ Called when client confirms that it can do MSDP. """ self.protocol.protocol_flags['MSDP'] = True def func_to_msdp(self, cmdname, data): """ handle return data from cmdname by converting it to a proper msdp structure. data can either be a single value (will be converted to a string), a list (will be converted to an MSDP_ARRAY), or a dictionary (will be converted to MSDP_TABLE). OBS - this supports nested tables and even arrays nested inside tables, as opposed to the receive method. Arrays cannot hold tables by definition (the table must be named with MSDP_VAR, and an array can only contain MSDP_VALs). """ def make_table(name, datadict, string): "build a table that may be nested with other tables or arrays." string += MSDP_VAR + name + MSDP_VAL + MSDP_TABLE_OPEN for key, val in datadict.items(): if type(val) == type({}): string += make_table(key, val, string) elif hasattr(val, '__iter__'): string += make_array(key, val, string) else: string += MSDP_VAR + key + MSDP_VAL + val string += MSDP_TABLE_CLOSE return string def make_array(name, string, datalist): "build a simple array. Arrays may not nest tables by definition." string += MSDP_VAR + name + MSDP_ARRAY_OPEN for val in datalist: string += MSDP_VAL + val string += MSDP_ARRAY_CLOSE return string if type(data) == type({}): msdp_string = make_table(cmdname, data, "") elif hasattr(data, '__iter__'): msdp_string = make_array(cmdname, data, "") else: msdp_string = MSDP_VAR + cmdname + MSDP_VAL + data return msdp_string def msdp_to_func(self, data): """ Handle a client's requested negotiation, converting it into a function mapping OBS-this does not support receiving nested tables from the client at this point! """ tables = {} arrays = {} variables = {} for table in regex_table.findall(data): tables[table[0]] = dict(regex_varval(table[1])) for array in regex_array.findall(data): arrays[array[0]] = dict(regex_varval(array[1])) variables = dict(regex._varval(regex_array.sub("", regex_table.sub("", data)))) # Some given MSDP (varname, value) pairs can also be treated as command + argument. # Generic msdp command map. The argument will be sent to the given command. # See http://tintin.sourceforge.net/msdp/ for definitions of each command. MSDP_COMMANDS = { "LIST": "msdp_list", "REPORT":"mspd_report", "RESET":"mspd_reset", "SEND":"mspd_send", "UNREPORT":"mspd_unreport" } # MSDP_MAP is a standard suggestions for making it easy to create generic guis. # this maps MSDP command names to Evennia commands found in OOB_FUNC_MODULE. It # is up to these commands to return data on proper form. MSDP_MAP = { # General "CHARACTER_NAME": "get_character_name", "SERVER_ID": "get_server_id", "SERVER_TIME": "get_server_time", # Character "AFFECTS": "char_affects", "ALIGNMENT": "char_alignment", "EXPERIENCE": "char_experience", "EXPERIENCE_MAX": "char_experience_max", "EXPERIENCE_TNL": "char_experience_tnl", "HEALTH": "char_health", "HEALTH_MAX": "char_health_max", "LEVEL": "char_level", "RACE": "char_race", "CLASS": "char_class", "MANA": "char_mana", "MANA_MAX": "char_mana_max", "WIMPY": "char_wimpy", "PRACTICE": "char_practice", "MONEY": "char_money", "MOVEMENT": "char_movement", "MOVEMENT_MAX": "char_movement_max", "HITROLL": "char_hitroll", "DAMROLL": "char_damroll", "AC": "char_ac", "STR": "char_str", "INT": "char_int", "WIS": "char_wis", "DEX": "char_dex", "CON": "char_con", # Combat "OPPONENT_HEALTH": "opponent_health", "OPPONENT_HEALTH_MAX":"opponent_health_max", "OPPONENT_LEVEL": "opponent_level", "OPPONENT_NAME": "opponent_name", # World "AREA_NAME": "area_name", "ROOM_EXITS": "area_room_exits", "ROOM_NAME": "room_name", "ROOM_VNUM": "room_dbref", "WORLD_TIME": "world_time", # Configurable variables "CLIENT_ID": "client_id", "CLIENT_VERSION": "client_version", "PLUGIN_ID": "plugin_id", "ANSI_COLORS": "ansi_colours", "XTERM_256_COLORS": "xterm_256_colors", "UTF_8": "utf_8", "SOUND": "sound", "MXP": "mxp", # GUI variables "BUTTON_1": "button1", "BUTTON_2": "button2", "BUTTON_3": "button3", "BUTTON_4": "button4", "BUTTON_5": "button5", "GAUGE_1": "gauge1", "GAUGE_2": "gauge2", "GAUGE_3": "gauge3", "GAUGE_4": "gauge4", "GAUGE_5": "gauge5"}
Python
# # This sets up how models are displayed # in the web admin interface. # from django.contrib import admin from src.server.models import ServerConfig class ServerConfigAdmin(admin.ModelAdmin): "Custom admin for server configs" list_display = ('db_key', 'db_value') list_display_links = ('db_key',) ordering = ['db_key', 'db_value'] search_fields = ['db_key'] save_as = True save_on_top = True list_select_related = True admin.site.register(ServerConfig, ServerConfigAdmin)
Python
""" This module implements the main Evennia server process, the core of the game engine. This module should be started with the 'twistd' executable since it sets up all the networking features. (this is done automatically by game/evennia.py). """ import time import sys import os if os.name == 'nt': # For Windows batchfile we need an extra path insertion here. sys.path.insert(0, os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__))))) from twisted.application import internet, service from twisted.internet import protocol, reactor from twisted.web import server, static from django.conf import settings from src.utils.utils import get_evennia_version from src.server.sessionhandler import PORTAL_SESSIONS if os.name == 'nt': # For Windows we need to handle pid files manually. PORTAL_PIDFILE = os.path.join(settings.GAME_DIR, 'portal.pid') # i18n from django.utils.translation import ugettext as _ #------------------------------------------------------------ # Evennia Portal settings #------------------------------------------------------------ VERSION = get_evennia_version() SERVERNAME = settings.SERVERNAME PORTAL_RESTART = os.path.join(settings.GAME_DIR, 'portal.restart') TELNET_PORTS = settings.TELNET_PORTS SSL_PORTS = settings.SSL_PORTS SSH_PORTS = settings.SSH_PORTS WEBSERVER_PORTS = settings.WEBSERVER_PORTS TELNET_INTERFACES = settings.TELNET_INTERFACES SSL_INTERFACES = settings.SSL_INTERFACES SSH_INTERFACES = settings.SSH_INTERFACES WEBSERVER_INTERFACES = settings.WEBSERVER_INTERFACES TELNET_ENABLED = settings.TELNET_ENABLED and TELNET_PORTS and TELNET_INTERFACES SSL_ENABLED = settings.SSL_ENABLED and SSL_PORTS and SSL_INTERFACES SSH_ENABLED = settings.SSH_ENABLED and SSH_PORTS and SSH_INTERFACES WEBSERVER_ENABLED = settings.WEBSERVER_ENABLED and WEBSERVER_PORTS and WEBSERVER_INTERFACES WEBCLIENT_ENABLED = settings.WEBCLIENT_ENABLED AMP_HOST = settings.AMP_HOST AMP_PORT = settings.AMP_PORT AMP_ENABLED = AMP_HOST and AMP_PORT #------------------------------------------------------------ # Portal Service object #------------------------------------------------------------ class Portal(object): """ The main Portal server handler. This object sets up the database and tracks and interlinks all the twisted network services that make up Portal. """ def __init__(self, application): """ Setup the server. application - an instantiated Twisted application """ sys.path.append('.') # create a store of services self.services = service.IServiceCollection(application) self.amp_protocol = None # set by amp factory self.sessions = PORTAL_SESSIONS self.sessions.portal = self print '\n' + '-'*50 # Make info output to the terminal. self.terminal_output() print '-'*50 # set a callback if the server is killed abruptly, # by Ctrl-C, reboot etc. reactor.addSystemEventTrigger('before', 'shutdown', self.shutdown, _abrupt=True) self.game_running = False def terminal_output(self): """ Outputs server startup info to the terminal. """ print _(' %(servername)s Portal (%(version)s) started.') % {'servername': SERVERNAME, 'version': VERSION} if AMP_ENABLED: print " amp (Server): %s" % AMP_PORT if TELNET_ENABLED: ports = ", ".join([str(port) for port in TELNET_PORTS]) ifaces = ",".join([" %s" % iface for iface in TELNET_INTERFACES if iface != '0.0.0.0']) print " telnet%s: %s" % (ifaces, ports) if SSH_ENABLED: ports = ", ".join([str(port) for port in SSH_PORTS]) ifaces = ",".join([" %s" % iface for iface in SSH_INTERFACES if iface != '0.0.0.0']) print " ssh%s: %s" % (ifaces, ports) if SSL_ENABLED: ports = ", ".join([str(port) for port in SSL_PORTS]) ifaces = ",".join([" %s" % iface for iface in SSL_INTERFACES if iface != '0.0.0.0']) print " ssl%s: %s" % (ifaces, ports) if WEBSERVER_ENABLED: clientstring = "" if WEBCLIENT_ENABLED: clientstring = '/client' ports = ", ".join([str(port) for port in WEBSERVER_PORTS]) ifaces = ",".join([" %s" % iface for iface in WEBSERVER_INTERFACES if iface != '0.0.0.0']) print " webserver%s%s: %s" % (clientstring, ifaces, ports) def set_restart_mode(self, mode=None): """ This manages the flag file that tells the runner if the server should be restarted or is shutting down. Valid modes are True/False and None. If mode is None, no change will be done to the flag file. """ if mode == None: return f = open(PORTAL_RESTART, 'w') print _("writing mode=%(mode)s to %(portal_restart)s") % {'mode': mode, 'portal_restart': PORTAL_RESTART} f.write(str(mode)) f.close() def shutdown(self, restart=None, _abrupt=False): """ Shuts down the server from inside it. restart - True/False sets the flags so the server will be restarted or not. If None, the current flag setting (set at initialization or previous runs) is used. _abrupt - this is set if server is stopped by a kill command, in which case the reactor is dead anyway. Note that restarting (regardless of the setting) will not work if the Portal is currently running in daemon mode. In that case it always needs to be restarted manually. """ self.set_restart_mode(restart) if not _abrupt: reactor.callLater(0, reactor.stop) if os.name == 'nt' and os.path.exists(PORTAL_PIDFILE): # for Windows we need to remove pid files manually os.remove(PORTAL_PIDFILE) #------------------------------------------------------------ # # Start the Portal proxy server and add all active services # #------------------------------------------------------------ # twistd requires us to define the variable 'application' so it knows # what to execute from. application = service.Application('Portal') # The main Portal server program. This sets up the database # and is where we store all the other services. PORTAL = Portal(application) if AMP_ENABLED: # The AMP protocol handles the communication between # the portal and the mud server. Only reason to ever deactivate # it would be during testing and debugging. from src.server import amp factory = amp.AmpClientFactory(PORTAL) amp_client = internet.TCPClient(AMP_HOST, AMP_PORT, factory) amp_client.setName('evennia_amp') PORTAL.services.addService(amp_client) # We group all the various services under the same twisted app. # These will gradually be started as they are initialized below. if TELNET_ENABLED: # Start telnet game connections from src.server import telnet for interface in TELNET_INTERFACES: ifacestr = "" if interface != '0.0.0.0' or len(TELNET_INTERFACES) > 1: ifacestr = "-%s" % interface for port in TELNET_PORTS: pstring = "%s:%s" % (ifacestr, port) factory = protocol.ServerFactory() factory.protocol = telnet.TelnetProtocol factory.sessionhandler = PORTAL_SESSIONS telnet_service = internet.TCPServer(port, factory, interface=interface) telnet_service.setName('EvenniaTelnet%s' % pstring) PORTAL.services.addService(telnet_service) if SSL_ENABLED: # Start SSL game connection (requires PyOpenSSL). from src.server import ssl for interface in SSL_INTERFACES: ifacestr = "" if interface != '0.0.0.0' or len(SSL_INTERFACES) > 1: ifacestr = "-%s" % interface for port in SSL_PORTS: pstring = "%s:%s" % (ifacestr, port) factory = protocol.ServerFactory() factory.sessionhandler = PORTAL_SESSIONS factory.protocol = ssl.SSLProtocol ssl_service = internet.SSLServer(port, factory, ssl.getSSLContext(), interface=interface) ssl_service.setName('EvenniaSSL%s' % pstring) PORTAL.services.addService(ssl_service) if SSH_ENABLED: # Start SSH game connections. Will create a keypair in evennia/game if necessary. from src.server import ssh for interface in SSH_INTERFACES: ifacestr = "" if interface != '0.0.0.0' or len(SSH_INTERFACES) > 1: ifacestr = "-%s" % interface for port in SSH_PORTS: pstring = "%s:%s" % (ifacestr, port) factory = ssh.makeFactory({'protocolFactory':ssh.SshProtocol, 'protocolArgs':(), 'sessions':PORTAL_SESSIONS}) ssh_service = internet.TCPServer(port, factory, interface=interface) ssh_service.setName('EvenniaSSH%s' % pstring) PORTAL.services.addService(ssh_service) if WEBSERVER_ENABLED: # Start a django-compatible webserver. from twisted.python import threadpool from src.server.webserver import DjangoWebRoot, WSGIWebServer # start a thread pool and define the root url (/) as a wsgi resource # recognized by Django threads = threadpool.ThreadPool() web_root = DjangoWebRoot(threads) # point our media resources to url /media web_root.putChild("media", static.File(settings.MEDIA_ROOT)) if WEBCLIENT_ENABLED: # create ajax client processes at /webclientdata from src.server.webclient import WebClient webclient = WebClient() webclient.sessionhandler = PORTAL_SESSIONS web_root.putChild("webclientdata", webclient) web_site = server.Site(web_root, logPath=settings.HTTP_LOG_FILE) for interface in WEBSERVER_INTERFACES: ifacestr = "" if interface != '0.0.0.0' or len(WEBSERVER_INTERFACES) > 1: ifacestr = "-%s" % interface for port in WEBSERVER_PORTS: pstring = "%s:%s" % (ifacestr, port) # create the webserver webserver = WSGIWebServer(threads, port, web_site, interface=interface) webserver.setName('EvenniaWebServer%s' % pstring) PORTAL.services.addService(webserver) if os.name == 'nt': # Windows only: Set PID file manually f = open(os.path.join(settings.GAME_DIR, 'portal.pid'), 'w') f.write(str(os.getpid())) f.close()
Python
""" This module implements the telnet protocol. This depends on a generic session module that implements the actual login procedure of the game, tracks sessions etc. """ from twisted.conch.telnet import Telnet, StatefulTelnetProtocol, IAC, LINEMODE, DO, DONT from src.server.session import Session from src.server import ttype, mssp from src.server.mccp import Mccp, mccp_compress, MCCP from src.utils import utils, ansi class TelnetProtocol(Telnet, StatefulTelnetProtocol, Session): """ Each player connecting over telnet (ie using most traditional mud clients) gets a telnet protocol instance assigned to them. All communication between game and player goes through here. """ def connectionMade(self): """ This is called when the connection is first established. """ # initialize the session client_address = self.transport.client self.init_session("telnet", client_address, self.factory.sessionhandler) # negotiate mccp (data compression) self.mccp = Mccp(self) # negotiate ttype (client info) self.ttype = ttype.Ttype(self) # negotiate mssp (crawler communication) self.mssp = mssp.Mssp(self) # add this new connection to sessionhandler so # the Server becomes aware of it. self.sessionhandler.connect(self) def enableRemote(self, option): """ This sets up the options we allow for this protocol. """ return (option == LINEMODE or option == ttype.TTYPE or option == MCCP or option == mssp.MSSP) def enableLocal(self, option): """ Allow certain options on this protocol """ return option == MCCP def disableLocal(self, option): if option == MCCP: self.mccp.no_mccp(option) return True else: return super(TelnetProtocol, self).disableLocal(option) def connectionLost(self, reason): """ This is executed when the connection is lost for whatever reason. It can also be called directly, from the disconnect method """ self.sessionhandler.disconnect(self) self.transport.loseConnection() def dataReceived(self, data): """ This method will split the incoming data depending on if it starts with IAC (a telnet command) or not. All other data will be handled in line mode. """ # print "dataRcv:", data, # try: # for b in data: # print ord(b), # print "" # except Exception, e: # print str(e) + ":", str(data) if data and data[0] == IAC: try: super(TelnetProtocol, self).dataReceived(data) return except Exception: pass StatefulTelnetProtocol.dataReceived(self, data) def _write(self, data): "hook overloading the one used in plain telnet" #print "_write (%s): %s" % (self.state, " ".join(str(ord(c)) for c in data)) data = data.replace('\n', '\r\n') super(TelnetProtocol, self)._write(mccp_compress(self, data)) def sendLine(self, line): "hook overloading the one used by linereceiver" #print "sendLine (%s):\n%s" % (self.state, line) #escape IAC in line mode, and correctly add \r\n line += self.delimiter line = line.replace(IAC, IAC + IAC).replace('\n', '\r\n') return self.transport.write(mccp_compress(self, line)) def lineReceived(self, string): """ Telnet method called when data is coming in over the telnet connection. We pass it on to the game engine directly. """ self.sessionhandler.data_in(self, string) # Session hooks def disconnect(self, reason=None): """ generic hook for the engine to call in order to disconnect this protocol. """ if reason: self.data_out(reason) self.connectionLost(reason) def data_out(self, string, data=None): """ generic hook method for engine to call in order to send data through the telnet connection. Data Evennia -> Player. 'data' argument is not used """ try: string = utils.to_str(string, encoding=self.encoding) except Exception, e: self.sendLine(str(e)) return xterm256 = self.protocol_flags.get('TTYPE', {}).get('256 COLORS') nomarkup = not (xterm256 or not self.protocol_flags.get('TTYPE') or self.protocol_flags.get('TTYPE', {}).get('ANSI')) raw = False if type(data) == dict: # check if we want escape codes to go through unparsed. raw = data.get("raw", False) # check if we want to remove all markup nomarkup = data.get("nomarkup", False) if raw: self.sendLine(string) else: self.sendLine(ansi.parse_ansi(string, strip_ansi=nomarkup, xterm256=xterm256))
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models, utils import pickle class Migration(SchemaMigration): no_dry_run = True def forwards(self, orm): try: db.rename_table("config_configvalue", "server_serverconfig") for conf in orm.ServerConfig.objects.all(): conf.db_value = pickle.dumps(conf.db_value) conf.save() except Exception: #utils.DatabaseError: # this will happen if we start db from scratch (the config # app will then already be gone and no data is to be transferred) # So instead of renaming the old we instead have to manually create the new model. # Adding model 'ServerConfig' db.create_table('server_serverconfig', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(unique=True, max_length=64)), ('db_value', self.gf('django.db.models.fields.TextField')(blank=True)), )) db.send_create_signal('server', ['ServerConfig']) def backwards(self, orm): raise RuntimeError("This migration cannot be reversed.") models = { 'config.configvalue': { 'Meta': {'object_name': 'ConfigValue'}, 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'db_value': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'server.serverconfig': { 'Meta': {'object_name': 'ServerConfig'}, 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}), 'db_value': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['config', 'server']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models, utils import pickle class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." # we are fixing a situation were the serverconfig value last_initial_setup_step was left at 1 instead of -1 # as it should (due to a bug in the setter). This causes db errors as the initial_setup thinks it needs to # run again. try: if orm['objects.ObjectDB'].objects.filter(id=1) and orm["objects.ObjectDB"].objects.filter(id=2): # only an issue the critical objects have already been created conf = orm.ServerConfig.objects.filter(db_key="last_initial_setup_step") if conf: conf = conf[0] if pickle.loads(str(conf.db_value)) == 1: # this shouldn't be 1 if objects already exists. This is the bug. Fix the error. conf.db_value = pickle.dumps(-1) conf.save() except utils.DatabaseError: # this will happen if we start the db from scratch (in which case this migration fix is not needed) pass def backwards(self, orm): "Write your backwards methods here." models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.alias': { 'Meta': {'object_name': 'Alias'}, 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.nick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'Nick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objattribute': { 'Meta': {'object_name': 'ObjAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'server.serverconfig': { 'Meta': {'object_name': 'ServerConfig'}, 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}), 'db_value': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['objects', 'server']
Python
""" This implements resources for twisted webservers using the wsgi interface of django. This alleviates the need of running e.g. an apache server to serve Evennia's web presence (although you could do that too if desired). The actual servers are started inside server.py as part of the Evennia application. (Lots of thanks to http://githup.com/clemensha/twisted-wsgi-django for a great example/aid on how to do this.) """ from twisted.web import resource from twisted.python import threadpool from twisted.internet import reactor from twisted.application import service, internet from twisted.web.wsgi import WSGIResource from django.core.handlers.wsgi import WSGIHandler # # Website server resource # class DjangoWebRoot(resource.Resource): """ This creates a web root (/) that Django understands by tweaking the way the child instancee are recognized. """ def __init__(self, pool): """ Setup the django+twisted resource """ resource.Resource.__init__(self) self.wsgi_resource = WSGIResource(reactor, pool , WSGIHandler()) def getChild(self, path, request): """ To make things work we nudge the url tree to make this the root. """ path0 = request.prepath.pop(0) request.postpath.insert(0, path0) return self.wsgi_resource # # Threaded Webserver # class WSGIWebServer(internet.TCPServer): """ This is a WSGI webserver. It makes sure to start the threadpool after the service itself started, so as to register correctly with the twisted daemon. call with WSGIWebServer(threadpool, port, wsgi_resource) """ def __init__(self, pool, *args, **kwargs ): "This just stores the threadpool" self.pool = pool internet.TCPServer.__init__(self, *args, **kwargs) def startService(self): "Start the pool after the service" internet.TCPServer.startService(self) self.pool.start() def stopService(self): "Safely stop the pool after service stop." internet.TCPServer.stopService(self) self.pool.stop()
Python
""" Web client server resource. The Evennia web client consists of two components running on twisted and django. They are both a part of the Evennia website url tree (so the testing website might be located on http://localhost:8000/, whereas the webclient can be found on http://localhost:8000/webclient.) /webclient - this url is handled through django's template system and serves the html page for the client itself along with its javascript chat program. /webclientdata - this url is called by the ajax chat using POST requests (long-polling when necessary) The WebClient resource in this module will handle these requests and act as a gateway to sessions connected over the webclient. """ import time from hashlib import md5 from twisted.web import server, resource from twisted.internet import defer, reactor from django.utils import simplejson from django.utils.functional import Promise from django.utils.encoding import force_unicode from django.conf import settings from src.utils import utils, logger, ansi from src.utils.text2html import parse_html from src.server import session SERVERNAME = settings.SERVERNAME ENCODINGS = settings.ENCODINGS # defining a simple json encoder for returning # django data to the client. Might need to # extend this if one wants to send more # complex database objects too. class LazyEncoder(simplejson.JSONEncoder): def default(self, obj): if isinstance(obj, Promise): return force_unicode(obj) return super(LazyEncoder, self).default(obj) def jsonify(obj): return utils.to_str(simplejson.dumps(obj, ensure_ascii=False, cls=LazyEncoder)) # # WebClient resource - this is called by the ajax client # using POST requests to /webclientdata. # class WebClient(resource.Resource): """ An ajax/comet long-polling transport """ isLeaf = True allowedMethods = ('POST',) def __init__(self): self.requests = {} self.databuffer = {} def getChild(self, path, request): """ This is the place to put dynamic content. """ return self def _responseFailed(self, failure, suid, request): "callback if a request is lost/timed out" try: self.requests.get(suid, []).remove(request) except ValueError: pass def lineSend(self, suid, string, data=None): """ This adds the data to the buffer and/or sends it to the client as soon as possible. """ requests = self.requests.get(suid, None) if requests: request = requests.pop(0) # we have a request waiting. Return immediately. request.write(jsonify({'msg':string, 'data':data})) request.finish() self.requests[suid] = requests else: # no waiting request. Store data in buffer dataentries = self.databuffer.get(suid, []) dataentries.append(jsonify({'msg':string, 'data':data})) self.databuffer[suid] = dataentries def client_disconnect(self, suid): """ Disconnect session with given suid. """ if self.requests.has_key(suid): for request in self.requests.get(suid, []): request.finish() del self.requests[suid] if self.databuffer.has_key(suid): del self.databuffer[suid] def mode_init(self, request): """ This is called by render_POST when the client requests an init mode operation (at startup) """ #csess = request.getSession() # obs, this is a cookie, not an evennia session! #csees.expireCallbacks.append(lambda : ) suid = request.args.get('suid', ['0'])[0] remote_addr = request.getClientIP() host_string = "%s (%s:%s)" % (SERVERNAME, request.getRequestHostname(), request.getHost().port) if suid == '0': # creating a unique id hash string suid = md5(str(time.time())).hexdigest() self.requests[suid] = [] self.databuffer[suid] = [] sess = WebClientSession() sess.client = self sess.init_session("comet", remote_addr, self.sessionhandler) sess.suid = suid sess.sessionhandler.connect(sess) return jsonify({'msg':host_string, 'suid':suid}) def mode_input(self, request): """ This is called by render_POST when the client is sending data to the server. """ suid = request.args.get('suid', ['0'])[0] if suid == '0': return '' sess = self.sessionhandler.session_from_suid(suid) if sess: sess = sess[0] string = request.args.get('msg', [''])[0] data = request.args.get('data', [None])[0] sess.sessionhandler.data_in(sess, string, data) return '' def mode_receive(self, request): """ This is called by render_POST when the client is telling us that it is ready to receive data as soon as it is available. This is the basis of a long-polling (comet) mechanism: the server will wait to reply until data is available. """ suid = request.args.get('suid', ['0'])[0] if suid == '0': return '' dataentries = self.databuffer.get(suid, []) if dataentries: return dataentries.pop(0) reqlist = self.requests.get(suid, []) request.notifyFinish().addErrback(self._responseFailed, suid, request) reqlist.append(request) self.requests[suid] = reqlist return server.NOT_DONE_YET def mode_close(self, request): """ This is called by render_POST when the client is signalling that it is about to be closed. """ suid = request.args.get('suid', ['0'])[0] if suid == '0': self.client_disconnect(suid) return '' def render_POST(self, request): """ This function is what Twisted calls with POST requests coming in from the ajax client. The requests should be tagged with different modes depending on what needs to be done, such as initializing or sending/receving data through the request. It uses a long-polling mechanism to avoid sending data unless there is actual data available. """ dmode = request.args.get('mode', [None])[0] if dmode == 'init': # startup. Setup the server. return self.mode_init(request) elif dmode == 'input': # input from the client to the server return self.mode_input(request) elif dmode == 'receive': # the client is waiting to receive data. return self.mode_receive(request) elif dmode == 'close': # the client is closing return self.mode_close(request) else: # this should not happen if client sends valid data. return '' # # A session type handling communication over the # web client interface. # class WebClientSession(session.Session): """ This represents a session running in a webclient. """ def disconnect(self, reason=None): """ Disconnect from server """ if reason: self.lineSend(self.suid, reason) self.client.client_disconnect(self.suid) def data_out(self, string='', data=None): """ Data Evennia -> Player access hook. data argument may be used depending on the client-server implementation. """ if data: # treat data? pass # string handling is similar to telnet try: string = utils.to_str(string, encoding=self.encoding) nomarkup = False raw = False if type(data) == dict: # check if we want escape codes to go through unparsed. raw = data.get("raw", False) # check if we want to remove all markup nomarkup = data.get("nomarkup", False) if raw: self.client.lineSend(self.suid, string) else: self.client.lineSend(self.suid, parse_html(ansi.parse_ansi(string, strip_ansi=nomarkup))) return except Exception, e: logger.log_trace()
Python
""" Custom manager for ServerConfig objects. """ from django.db import models class ServerConfigManager(models.Manager): """ This gives some access methods to search and edit the configvalue database. If no match is found, return default. """ def conf(self, key=None, value=None, delete=False, default=None): """ Access and manipulate config values """ if not key: return self.all() elif delete == True: for conf in self.filter(db_key=key): conf.delete() elif value != None: conf = self.filter(db_key=key) if conf: conf = conf[0] else: conf = self.model(db_key=key) conf.value = value # this will pickle else: conf = self.filter(db_key=key) if not conf: return default return conf[0].value
Python
""" MCCP - Mud Client Compression Protocol The implements the MCCP v2 telnet protocol as per http://tintin.sourceforge.net/mccp/. MCCP allows for the server to compress data when sending to supporting clients, reducing bandwidth by 70-90%.. The compression is done using Python's builtin zlib library. If the client doesn't support MCCP, server sends uncompressed as normal. Note: On modern hardware you are not likely to notice the effect of MCCP unless you have extremely heavy traffic or sits on a terribly slow connection. This protocol is implemented by the telnet protocol importing mccp_compress and calling it from its write methods. """ import zlib # negotiations for v1 and v2 of the protocol MCCP = chr(86) FLUSH = zlib.Z_SYNC_FLUSH def mccp_compress(protocol, data): "Handles zlib compression, if applicable" if hasattr(protocol, 'zlib'): return protocol.zlib.compress(data) + protocol.zlib.flush(FLUSH) return data class Mccp(object): """ Implements the MCCP protocol. Add this to a variable on the telnet protocol to set it up. """ def __init__(self, protocol): """ initialize MCCP by storing protocol on ourselves and calling the client to see if it supports MCCP. Sets callbacks to start zlib compression in that case. """ self.protocol = protocol self.protocol.protocol_flags['MCCP'] = False # ask if client will mccp, connect callbacks to handle answer self.protocol.will(MCCP).addCallbacks(self.do_mccp, self.no_mccp) def no_mccp(self, option): """ If client doesn't support mccp, don't do anything. """ if hasattr(self.protocol, 'zlib'): del self.protocol.zlib self.protocol.protocol_flags['MCCP'] = False def do_mccp(self, option): """ The client supports MCCP. Set things up by creating a zlib compression stream. """ self.protocol.protocol_flags['MCCP'] = True self.protocol.requestNegotiation(MCCP, '') self.protocol.zlib = zlib.compressobj(9)
Python
""" Server Configuration flags This holds persistent server configuration flags. Config values should usually be set through the manager's conf() method. """ try: import cPickle as pickle except ImportError: import pickle from django.db import models from src.utils.idmapper.models import SharedMemoryModel from src.utils import logger, utils from src.server.manager import ServerConfigManager # i18n from django.utils.translation import ugettext as _ #------------------------------------------------------------ # # ServerConfig # #------------------------------------------------------------ class ServerConfig(SharedMemoryModel): """ On-the fly storage of global settings. Properties defined on ServerConfig: key - main identifier value - value stored in key. This is a pickled storage. """ # # ServerConfig database model setup # # # These database fields are all set using their corresponding properties, # named same as the field, but withtout the db_* prefix. # main name of the database entry db_key = models.CharField(max_length=64, unique=True) # config value db_value = models.TextField(blank=True) objects = ServerConfigManager() # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that allows the user to do self.attr = value, # value = self.attr and del self.attr respectively (where self # is the object in question). # key property (wraps db_key) #@property def key_get(self): "Getter. Allows for value = self.key" return self.db_key #@key.setter def key_set(self, value): "Setter. Allows for self.key = value" self.db_key = value self.save() #@key.deleter def key_del(self): "Deleter. Allows for del self.key. Deletes entry." self.delete() key = property(key_get, key_set, key_del) # value property (wraps db_value) #@property def value_get(self): "Getter. Allows for value = self.value" return pickle.loads(str(self.db_value)) #@value.setter def value_set(self, value): "Setter. Allows for self.value = value" if utils.has_parent('django.db.models.base.Model', value): # we have to protect against storing db objects. logger.log_errmsg(_("ServerConfig cannot store db objects! (%s)" % value)) return self.db_value = pickle.dumps(value) self.save() #@value.deleter def value_del(self): "Deleter. Allows for del self.value. Deletes entry." self.delete() value = property(value_get, value_set, value_del) class Meta: "Define Django meta options" verbose_name = "Server Config value" verbose_name_plural = "Server Config values" # # ServerConfig other methods # def __unicode__(self): return "%s : %s" % (self.key, self.value) def store(key, value): """ Wrap the storage (handles pickling) """ self.key = key self.value = value
Python
""" MSSP - Mud Server Status Protocol This implements the MSSP telnet protocol as per http://tintin.sourceforge.net/mssp/. MSSP allows web portals and listings to have their crawlers find the mud and automatically extract relevant information about it, such as genre, how many active players and so on. Most of these settings are de """ from src.utils import utils MSSP = chr(70) MSSP_VAR = chr(1) MSSP_VAL = chr(2) # try to get the customized mssp info, if it exists. MSSPTable_CUSTOM = utils.variable_from_module("game.gamesrc.conf.mssp", "MSSPTable", default={}) class Mssp(object): """ Implements the MSSP protocol. Add this to a variable on the telnet protocol to set it up. """ def __init__(self, protocol): """ initialize MSSP by storing protocol on ourselves and calling the client to see if it supports MSSP. """ self.protocol = protocol self.protocol.will(MSSP).addCallbacks(self.do_mssp, self.no_mssp) def get_player_count(self): "Get number of logged-in players" return str(self.protocol.sessionhandler.count_loggedin()) def get_uptime(self): "Get how long the portal has been online (reloads are not counted)" return str(self.protocol.sessionhandler.uptime) def no_mssp(self, option): """ This is the normal operation. """ pass def do_mssp(self, option): """ Negotiate all the information. """ self.mssp_table = { # Required fields "NAME": "Evennia", "PLAYERS": self.get_player_count, "UPTIME" : self.get_uptime, # Generic "CRAWL DELAY": "-1", "HOSTNAME": "", # current or new hostname "PORT": ["4000"], # most important port should be last in list "CODEBASE": "Evennia", "CONTACT": "", # email for contacting the mud "CREATED": "", # year MUD was created "ICON": "", # url to icon 32x32 or larger; <32kb. "IP": "", # current or new IP address "LANGUAGE": "", # name of language used, e.g. English "LOCATION": "", # full English name of server country "MINIMUM AGE": "0", # set to 0 if not applicable "WEBSITE": "www.evennia.com", # Categorisation "FAMILY": "Custom", # evennia goes under 'Custom' "GENRE": "None", # Adult, Fantasy, Historical, Horror, Modern, None, or Science Fiction "GAMEPLAY": "None", # Adventure, Educational, Hack and Slash, None, # Player versus Player, Player versus Environment, # Roleplaying, Simulation, Social or Strategy "STATUS": "Open Beta", # Alpha, Closed Beta, Open Beta, Live "GAMESYSTEM": "Custom", # D&D, d20 System, World of Darkness, etc. Use Custom if homebrew "INTERMUD": "IMC2", # evennia supports IMC2. "SUBGENRE": "None", # LASG, Medieval Fantasy, World War II, Frankenstein, # Cyberpunk, Dragonlance, etc. Or None if not available. # World "AREAS": "0", "HELPFILES": "0", "MOBILES": "0", "OBJECTS": "0", "ROOMS": "0", # use 0 if room-less "CLASSES": "0", # use 0 if class-less "LEVELS": "0", # use 0 if level-less "RACES": "0", # use 0 if race-less "SKILLS": "0", # use 0 if skill-less # Protocols set to 1 or 0) "ANSI": "1", "GMCP": "0", "MCCP": "0", "MCP": "0", "MSDP": "0", "MSP": "0", "MXP": "0", "PUEBLO": "0", "UTF-8": "1", "VT100": "0", "XTERM 256 COLORS": "0", # Commercial set to 1 or 0) "PAY TO PLAY": "0", "PAY FOR PERKS": "0", # Hiring set to 1 or 0) "HIRING BUILDERS": "0", "HIRING CODERS": "0", # Extended variables # World "DBSIZE": "0", "EXITS": "0", "EXTRA DESCRIPTIONS": "0", "MUDPROGS": "0", "MUDTRIGS": "0", "RESETS": "0", # Game (set to 1, 0 or one of the given alternatives) "ADULT MATERIAL": "0", "MULTICLASSING": "0", "NEWBIE FRIENDLY": "0", "PLAYER CITIES": "0", "PLAYER CLANS": "0", "PLAYER CRAFTING": "0", "PLAYER GUILDS": "0", "EQUIPMENT SYSTEM": "None", # "None", "Level", "Skill", "Both" "MULTIPLAYING": "None", # "None", "Restricted", "Full" "PLAYERKILLING": "None", # "None", "Restricted", "Full" "QUEST SYSTEM": "None", # "None", "Immortal Run", "Automated", "Integrated" "ROLEPLAYING": "None", # "None", "Accepted", "Encouraged", "Enforced" "TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both" "WORLD ORIGINALITY": "None", # "All Stock", "Mostly Stock", "Mostly Original", "All Original" # Protocols (only change if you added/removed something manually) "ATCP": "0", "MSDP": "0", "MCCP": "1", "SSL": "1", "UTF-8": "1", "ZMP": "0", "XTERM 256 COLORS": "0"} # update the static table with the custom one self.mssp_table.update(MSSPTable_CUSTOM) varlist = '' for variable, value in self.mssp_table.items(): if callable(value): value = value() if utils.is_iter(value): for partval in value: varlist += MSSP_VAR + str(variable) + MSSP_VAL + str(partval) else: varlist += MSSP_VAR + str(variable) + MSSP_VAL + str(value) # send to crawler by subnegotiation self.protocol.requestNegotiation(MSSP, varlist)
Python
""" This is a simple context factory for auto-creating SSL keys and certificates. """ import os, sys from twisted.internet import ssl as twisted_ssl try: import OpenSSL except ImportError: print _(" SSL_ENABLED requires PyOpenSSL.") sys.exit(5) from src.server.telnet import TelnetProtocol class SSLProtocol(TelnetProtocol): """ Communication is the same as telnet, except data transfer is done with encryption. """ pass def verify_SSL_key_and_cert(keyfile, certfile): """ This function looks for RSA key and certificate in the current directory. If files ssl.key and ssl.cert does not exist, they are created. """ if not (os.path.exists(keyfile) and os.path.exists(certfile)): # key/cert does not exist. Create. import subprocess from Crypto.PublicKey import RSA from twisted.conch.ssh.keys import Key print _(" Creating SSL key and certificate ... "), try: # create the RSA key and store it. KEY_LENGTH = 1024 rsaKey = Key(RSA.generate(KEY_LENGTH)) keyString = rsaKey.toString(type="OPENSSH") file(keyfile, 'w+b').write(keyString) except Exception,e: print _("rsaKey error: %(e)s\n WARNING: Evennia could not auto-generate SSL private key.") % {'e': e} print _("If this error persists, create game/%(keyfile)s yourself using third-party tools.") % {'keyfile': keyfile} sys.exit(5) # try to create the certificate CERT_EXPIRE = 365 * 20 # twenty years validity # default: #openssl req -new -x509 -key ssl.key -out ssl.cert -days 7300 exestring = "openssl req -new -x509 -key %s -out %s -days %s" % (keyfile, certfile, CERT_EXPIRE) #print "exestring:", exestring try: err = subprocess.call(exestring)#, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except OSError, e: print " %s\n" % e print _(" Evennia's SSL context factory could not automatically create an SSL certificate game/%(cert)s.") % {'cert': certfile} print _(" A private key 'ssl.key' was already created. Please create %(cert)s manually using the commands valid") % {'cert': certfile} print _(" for your operating system.") print _(" Example (linux, using the openssl program): ") print " %s" % exestring sys.exit(5) print "done." def getSSLContext(): """ Returns an SSL context (key and certificate). This function verifies that key/cert exists before obtaining the context, and if not, creates them. """ keyfile, certfile = "ssl.key", "ssl.cert" verify_SSL_key_and_cert(keyfile, certfile) return twisted_ssl.DefaultOpenSSLContextFactory(keyfile, certfile)
Python
""" This module defines handlers for storing sessions when handles sessions of users connecting to the server. There are two similar but separate stores of sessions: ServerSessionHandler - this stores generic game sessions for the game. These sessions has no knowledge about how they are connected to the world. PortalSessionHandler - this stores sessions created by twisted protocols. These are dumb connectors that handle network communication but holds no game info. """ import time from django.conf import settings from django.contrib.auth.models import User from src.server.models import ServerConfig from src.utils import utils from src.commands.cmdhandler import CMD_LOGINSTART # i18n from django.utils.translation import ugettext as _ ALLOW_MULTISESSION = settings.ALLOW_MULTISESSION IDLE_TIMEOUT = settings.IDLE_TIMEOUT class SessionHandler(object): """ This handler holds a stack of sessions. """ def __init__(self): """ Init the handler. """ self.sessions = {} def get_sessions(self, include_unloggedin=False): """ Returns the connected session objects. """ if include_unloggedin: return self.sessions.values() else: return [session for session in self.sessions.values() if session.logged_in] def get_session(self, sessid): """ Get session by sessid """ return self.sessions.get(sessid, None) def get_all_sync_data(self): """ Create a dictionary of sessdata dicts representing all sessions in store. """ sessdict = {} for sess in self.sessions.values(): # copy all relevant data from all sessions sessdict[sess.sessid] = sess.get_sync_data() return sessdict #------------------------------------------------------------ # Server-SessionHandler class #------------------------------------------------------------ class ServerSessionHandler(SessionHandler): """ This object holds the stack of sessions active in the game at any time. A session register with the handler in two steps, first by registering itself with the connect() method. This indicates an non-authenticated session. Whenever the session is authenticated the session together with the related player is sent to the login() method. """ # AMP communication methods def __init__(self): """ Init the handler. """ self.sessions = {} self.server = None self.server_data = {"servername":settings.SERVERNAME} def portal_connect(self, sessid, session): """ Called by Portal when a new session has connected. Creates a new, unlogged-in game session. """ self.sessions[sessid] = session session.execute_cmd(CMD_LOGINSTART) def portal_disconnect(self, sessid): """ Called by Portal when portal reports a closing of a session from the portal side. """ session = self.sessions.get(sessid, None) if session: del self.sessions[session.sessid] self.session_count(-1) def portal_session_sync(self, sesslist): """ Syncing all session ids of the portal with the ones of the server. This is instantiated by the portal when reconnecting. sesslist is a complete list of (sessid, session) pairs, matching the list on the portal. if session was logged in, the amp handler will have logged them in before this point. """ for sess in self.sessions.values(): # we delete the old session to make sure to catch eventual lingering references. del sess for sess in sesslist: self.sessions[sess.sessid] = sess sess.at_sync() def portal_shutdown(self): """ Called by server when shutting down the portal. """ self.server.amp_protocol.call_remote_PortalAdmin(0, operation='SSHUTD', data="") # server-side access methods def disconnect(self, session, reason=""): """ Called from server side to remove session and inform portal of this fact. """ session = self.sessions.get(session.sessid, None) if session: sessid = session.sessid del self.sessions[sessid] # inform portal that session should be closed. self.server.amp_protocol.call_remote_PortalAdmin(sessid, operation='SDISCONN', data=reason) self.session_count(-1) def login(self, session): """ Log in the previously unloggedin session and the player we by now should know is connected to it. After this point we assume the session to be logged in one way or another. """ # prep the session with player/user info if not ALLOW_MULTISESSION: # disconnect previous sessions. self.disconnect_duplicate_sessions(session) session.logged_in = True self.session_count(1) # sync the portal to this session sessdata = session.get_sync_data() self.server.amp_protocol.call_remote_PortalAdmin(session.sessid, operation='SLOGIN', data=sessdata) def session_sync(self): """ This is called by the server when it reboots. It syncs all session data to the portal. """ sessdata = self.get_all_sync_data() self.server.amp_protocol.call_remote_PortalAdmin(0, 'SSYNC', data=sessdata) def disconnect_all_sessions(self, reason="You have been disconnected."): """ Cleanly disconnect all of the connected sessions. """ for session in self.sessions: del session self.session_count(0) # tell portal to disconnect all sessions self.server.amp_protocol.call_remote_PortalAdmin(0, operation='SDISCONNALL', data=reason) def disconnect_duplicate_sessions(self, curr_session): """ Disconnects any existing sessions with the same game object. """ curr_char = curr_session.get_character() doublet_sessions = [sess for sess in self.sessions if sess.logged_in and sess.get_character() == curr_char and sess != curr_session] reason = _("Logged in from elsewhere. Disconnecting.") for sessid in doublet_sessions: self.disconnect(session, reason) self.session_count(-1) def validate_sessions(self): """ Check all currently connected sessions (logged in and not) and see if any are dead. """ tcurr = time.time() invalid_sessions = [session for session in self.sessions.values() if session.logged_in and IDLE_TIMEOUT > 0 and (tcurr - session.cmd_last) > IDLE_TIMEOUT] for session in invalid_sessions: self.disconnect(session, reason=_("Idle timeout exceeded, disconnecting.")) self.session_count(-1) def session_count(self, num=None): """ Count up/down the number of connected, authenticated users. If num is None, the current number of sessions is returned. num can be a positive or negative value to be added to the current count. If 0, the counter will be reset to 0. """ if num == None: # show the current value. This also syncs it. return int(ServerConfig.objects.conf('nr_sessions', default=0)) elif num == 0: # reset value to 0 ServerConfig.objects.conf('nr_sessions', 0) else: # add/remove session count from value add = int(ServerConfig.objects.conf('nr_sessions', default=0)) num = max(0, num + add) ServerConfig.objects.conf('nr_sessions', str(num)) def player_count(self): """ Get the number of connected players (not sessions since a player may have more than one session connected if ALLOW_MULTISESSION is True) Only logged-in players are counted here. """ return len(set(session.uid for session in self.sessions.values() if session.logged_in)) def sessions_from_player(self, player): """ Given a player, return any matching sessions. """ username = player.user.username try: uobj = User.objects.get(username=username) except User.DoesNotExist: return None uid = uobj.id return [session for session in self.sessions.values() if session.logged_in and session.uid == uid] def sessions_from_character(self, character): """ Given a game character, return any matching sessions. """ player = character.player if player: return self.sessions_from_player(player) return None def announce_all(self, message): """ Send message to all connected sessions """ for sess in self.sessions.values(): self.data_out(sess, message) def data_out(self, session, string="", data=""): """ Sending data Server -> Portal """ self.server.amp_protocol.call_remote_MsgServer2Portal(sessid=session.sessid, msg=string, data=data) def data_in(self, sessid, string="", data=""): """ Data Portal -> Server """ session = self.sessions.get(sessid, None) if session: session.execute_cmd(string) # ignore 'data' argument for now; this is otherwise the place # to put custom effects on the server due to data input, e.g. # from a custom client. def oob_data_in(self, sessid, data): """ OOB (Out-of-band) Data Portal -> Server """ session = self.sessions.get(sessid, None) if session: session.oob_data_in(data) def oob_data_out(self, session, data): """ OOB (Out-of-band) Data Server -> Portal """ self.server.amp_protocol.call_remote_OOBServer2Portal(session.sessid, data=data) #------------------------------------------------------------ # Portal-SessionHandler class #------------------------------------------------------------ class PortalSessionHandler(SessionHandler): """ This object holds the sessions connected to the portal at any time. It is synced with the server's equivalent SessionHandler over the AMP connection. Sessions register with the handler using the connect() method. This will assign a new unique sessionid to the session and send that sessid to the server using the AMP connection. """ def __init__(self): """ Init the handler """ self.portal = None self.sessions = {} self.latest_sessid = 0 self.uptime = time.time() self.connection_time = 0 def at_server_connection(self): """ Called when the Portal establishes connection with the Server. At this point, the AMP connection is already established. """ self.connection_time = time.time() def connect(self, session): """ Called by protocol at first connect. This adds a not-yet authenticated session using an ever-increasing counter for sessid. """ self.latest_sessid += 1 sessid = self.latest_sessid session.sessid = sessid sessdata = session.get_sync_data() self.sessions[sessid] = session # sync with server-side self.portal.amp_protocol.call_remote_ServerAdmin(sessid, operation="PCONN", data=sessdata) def disconnect(self, session): """ Called from portal side when the connection is closed from the portal side. """ sessid = session.sessid self.portal.amp_protocol.call_remote_ServerAdmin(sessid, operation="PDISCONN") def server_disconnect(self, sessid, reason=""): """ Called by server to force a disconnect by sessid """ session = self.sessions.get(sessid, None) if session: session.disconnect(reason) del session def server_disconnect_all(self, reason=""): """ Called by server when forcing a clean disconnect for everyone. """ for session in self.sessions.values(): session.disconnect(reason) del session def count_loggedin(self, include_unloggedin=False): """ Count loggedin connections, alternatively count all connections. """ return len(self.get_sessions(include_unloggedin=include_unloggedin)) def session_from_suid(self, suid): """ Given a session id, retrieve the session (this is primarily intended to be called by web clients) """ return [sess for sess in self.get_sessions(include_unloggedin=True) if hasattr(sess, 'suid') and sess.suid == suid] def data_in(self, session, string="", data=""): """ Called by portal sessions for relaying data coming in from the protocol to the server. data is serialized before passed on. """ self.portal.amp_protocol.call_remote_MsgPortal2Server(session.sessid, msg=string, data=data) def announce_all(self, message): """ Send message to all connection sessions """ for session in self.sessions.values(): session.data_out(message) def data_out(self, sessid, string="", data=""): """ Called by server for having the portal relay messages and data to the correct session protocol. """ session = self.sessions.get(sessid, None) if session: session.data_out(string, data=data) def oob_data_in(self, session, data): """ OOB (Out-of-band) data Portal -> Server """ self.portal.amp_protocol.call_remote_OOBPortal2Server(session.sessid, data=data) def oob_data_out(self, sessid, data): """ OOB (Out-of-band) data Server -> Portal """ session = self.sessions.get(sessid, None) if session: session.oob_data_out(data) SESSIONS = ServerSessionHandler() PORTAL_SESSIONS = PortalSessionHandler()
Python
""" This defines a the Server's generic session object. This object represents a connection to the outside world but don't know any details about how the connection actually happens (so it's the same for telnet, web, ssh etc). It is stored on the Server side (as opposed to protocol-specific sessions which are stored on the Portal side) """ import time from datetime import datetime from django.conf import settings from src.scripts.models import ScriptDB from src.comms.models import Channel from src.utils import logger, utils from src.commands import cmdhandler, cmdsethandler from src.server.session import Session IDLE_COMMAND = settings.IDLE_COMMAND # load optional out-of-band function module OOB_FUNC_MODULE = settings.OOB_FUNC_MODULE if OOB_FUNC_MODULE: OOB_FUNC_MODULE = utils.mod_import(settings.OOB_FUNC_MODULE) # i18n from django.utils.translation import ugettext as _ #------------------------------------------------------------ # Server Session #------------------------------------------------------------ class ServerSession(Session): """ This class represents a player's session and is a template for individual protocols to communicate with Evennia. Each player gets a session assigned to them whenever they connect to the game server. All communication between game and player goes through their session. """ def at_sync(self): """ This is called whenever a session has been resynced with the portal. At this point all relevant attributes have already been set and self.player been assigned (if applicable). Since this is often called after a server restart we need to set up the session as it was. """ if not self.logged_in: # assign the unloggedin-command set. self.cmdset = cmdsethandler.CmdSetHandler(self) self.cmdset_storage = [settings.CMDSET_UNLOGGEDIN] self.cmdset.update(init_mode=True) self.cmdset.update(init_mode=True) return character = self.get_character() if character: # start (persistent) scripts on this object ScriptDB.objects.validate(obj=character) def session_login(self, player): """ Startup mechanisms that need to run at login. This is called by the login command (which need to have handled authentication already before calling this method) player - the connected player """ # actually do the login by assigning session data self.player = player self.user = player.user self.uid = self.user.id self.uname = self.user.username self.logged_in = True self.conn_time = time.time() # Update account's last login time. self.user.last_login = datetime.now() self.user.save() # player init #print "at_init() - player" player.at_init() # Check if this is the first time the *player* logs in if player.db.FIRST_LOGIN: player.at_first_login() del player.db.FIRST_LOGIN player.at_pre_login() character = player.character if character: # this player has a character. Check if it's the # first time *this character* logs in character.at_init() if character.db.FIRST_LOGIN: character.at_first_login() del character.db.FIRST_LOGIN # run character login hook character.at_pre_login() self.log(_('Logged in: %(self)s') % {'self': self}) # start (persistent) scripts on this object ScriptDB.objects.validate(obj=self.player.character) #add session to connected list self.sessionhandler.login(self) # post-login hooks player.at_post_login() if character: character.at_post_login() def session_disconnect(self): """ Clean up the session, removing it from the game and doing some accounting. This method is used also for non-loggedin accounts. """ if self.logged_in: player = self.get_player() character = self.get_character() if character: character.at_disconnect() uaccount = player.user uaccount.last_login = datetime.now() uaccount.save() self.logged_in = False self.sessionhandler.disconnect(self) def get_player(self): """ Get the player associated with this session """ if self.logged_in: return self.player else: return None def get_character(self): """ Returns the in-game character associated with this session. This returns the typeclass of the object. """ player = self.get_player() if player: return player.character return None def log(self, message, channel=True): """ Emits session info to the appropriate outputs and info channels. """ if channel: try: cchan = settings.CHANNEL_CONNECTINFO cchan = Channel.objects.get_channel(cchan[0]) cchan.msg("[%s]: %s" % (cchan.key, message)) except Exception: pass logger.log_infomsg(message) def update_session_counters(self, idle=False): """ Hit this when the user enters a command in order to update idle timers and command counters. """ # Store the timestamp of the user's last command. self.cmd_last = time.time() if not idle: # Increment the user's command counter. self.cmd_total += 1 # Player-visible idle time, not used in idle timeout calcs. self.cmd_last_visible = time.time() def execute_cmd(self, command_string): """ Execute a command string on the server. """ # handle the 'idle' command if str(command_string).strip() == IDLE_COMMAND: self.update_session_counters(idle=True) return # all other inputs, including empty inputs character = self.get_character() if character: character.execute_cmd(command_string) else: if self.logged_in: # there is no character, but we are logged in. Use player instead. self.get_player().execute_cmd(command_string) else: # we are not logged in. Use the session directly # (it uses the settings.UNLOGGEDIN cmdset) cmdhandler.cmdhandler(self, command_string) self.update_session_counters() def data_out(self, msg, data=None): """ Send Evennia -> Player """ self.sessionhandler.data_out(self, msg, data) def oob_data_in(self, data): """ This receives out-of-band data from the Portal. This method parses the data input (a dict) and uses it to launch correct methods from those plugged into the system. data = {funcname: ( [args], {kwargs]), funcname: ( [args], {kwargs}), ...} example: data = {"get_hp": ([], {}), "update_counter", (["counter1"], {"now":True}) } """ print "server: " outdata = {} entity = self.get_character() if not entity: entity = self.get_player() if not entity: entity = self for funcname, argtuple in data.items(): # loop through the data, calling available functions. func = OOB_FUNC_MODULE.__dict__.get(funcname, None) if func: try: outdata[funcname] = func(entity, *argtuple[0], **argtuple[1]) except Exception: logger.log_trace() else: logger.log_errmsg("oob_data_in error: funcname '%s' not found in OOB_FUNC_MODULE." % funcname) if outdata: self.oob_data_out(outdata) def oob_data_out(self, data): """ This sends data from Server to the Portal across the AMP connection. """ self.sessionhandler.oob_data_out(self, data) def __eq__(self, other): return self.address == other.address def __str__(self): """ String representation of the user session class. We use this a lot in the server logs. """ if self.logged_in: symbol = '#' else: symbol = '?' try: address = ":".join([str(part) for part in self.address]) except Exception: address = self.address return "<%s> %s@%s" % (symbol, self.uname, address) def __unicode__(self): """ Unicode representation """ return u"%s" % str(self) # easy-access functions def login(self, player): "alias for at_login" self.session_login(player) def disconnect(self): "alias for session_disconnect" self.session_disconnect() def msg(self, string='', data=None): "alias for at_data_out" self.data_out(string, data=data) # Dummy API hooks for use a non-loggedin operation def at_cmdset_get(self): "dummy hook all objects with cmdsets need to have" pass # Mock db/ndb properties for allowing easy storage on the session # (note that no databse is involved at all here. session.db.attr = # value just saves a normal property in memory, just like ndb). #@property def ndb_get(self): """ A non-persistent store (ndb: NonDataBase). Everything stored to this is guaranteed to be cleared when a server is shutdown. Syntax is same as for the _get_db_holder() method and property, e.g. obj.ndb.attr = value etc. """ try: return self._ndb_holder except AttributeError: class NdbHolder(object): "Holder for storing non-persistent attributes." def all(self): return [val for val in self.__dict__.keys() if not val.startswith['_']] def __getattribute__(self, key): # return None if no matching attribute was found. try: return object.__getattribute__(self, key) except AttributeError: return None self._ndb_holder = NdbHolder() return self._ndb_holder #@ndb.setter def ndb_set(self, value): "Stop accidentally replacing the db object" string = "Cannot assign directly to ndb object! " string = "Use ndb.attr=value instead." raise Exception(string) #@ndb.deleter def ndb_del(self): "Stop accidental deletion." raise Exception("Cannot delete the ndb object!") ndb = property(ndb_get, ndb_set, ndb_del) db = property(ndb_get, ndb_set, ndb_del) # Mock access method for the session (there is no lock info # at this stage, so we just present a uniform API) def access(self, *args, **kwargs): "Dummy method." return True
Python
""" This defines a generic session class. All connection instances (both on Portal and Server side) should inherit from this class. """ import time #------------------------------------------------------------ # Server Session #------------------------------------------------------------ class Session(object): """ This class represents a player's session and is a template for both portal- and server-side sessions. Each connection will see two session instances created: 1) A Portal session. This is customized for the respective connection protocols that Evennia supports, like Telnet, SSH etc. The Portal session must call init_session() as part of its initialization. The respective hook methods should be connected to the methods unique for the respective protocol so that there is a unified interface to Evennia. 2) A Server session. This is the same for all connected players, regardless of how they connect. The Portal and Server have their own respective sessionhandlers. These are synced whenever new connections happen or the Server restarts etc, which means much of the same information must be stored in both places e.g. the portal can re-sync with the server when the server reboots. """ # names of attributes that should be affected by syncing. _attrs_to_sync = ['protocol_key', 'address', 'suid', 'sessid', 'uid', 'uname', 'logged_in', 'cid', 'encoding', 'conn_time', 'cmd_last', 'cmd_last_visible', 'cmd_total', 'server_data'] def init_session(self, protocol_key, address, sessionhandler): """ Initialize the Session. This should be called by the protocol when a new session is established. protocol_key - telnet, ssh, ssl or web address - client address sessionhandler - reference to the sessionhandler instance """ # This is currently 'telnet', 'ssh', 'ssl' or 'web' self.protocol_key = protocol_key # Protocol address tied to this session self.address = address # suid is used by some protocols, it's a hex key. self.suid = None # unique id for this session self.sessid = 0 # no sessid yet # database id for the user connected to this session self.uid = None # user name, for easier tracking of sessions self.uname = None # if user has authenticated already or not self.logged_in = False # database id of character/object connected to this player session (if any) self.cid = None self.encoding = "utf-8" # session time statistics self.conn_time = time.time() self.cmd_last_visible = self.conn_time self.cmd_last = self.conn_time self.cmd_total = 0 self.protocol_flags = {} self.server_data = {} # a back-reference to the relevant sessionhandler this # session is stored in. self.sessionhandler = sessionhandler def get_sync_data(self): """ Return all data relevant to sync the session """ sessdata = {} for attrname in self._attrs_to_sync: sessdata[attrname] = self.__dict__.get(attrname, None) return sessdata def load_sync_data(self, sessdata): """ Takes a session dictionary, as created by get_sync_data, and loads it into the correct attributes of the session. """ for attrname, value in sessdata.items(): self.__dict__[attrname] = value def at_sync(self): """ Called after a session has been fully synced (including secondary operations such as setting self.player based on uid etc). """ pass # access hooks def disconnect(self, reason=None): """ generic hook called from the outside to disconnect this session should be connected to the protocols actual disconnect mechanism. """ pass def data_out(self, msg, data=None): """ generic hook for sending data out through the protocol. Server protocols can use this right away. Portal sessions should overload this to format/handle the outgoing data as needed. """ pass def data_in(self, msg, data=None): """ hook for protocols to send incoming data to the engine. """ pass def oob_data_out(self, data): """ for Portal, this receives out-of-band data from Server across the AMP. for Server, this sends out-of-band data to Portal. data is a dictionary """ pass def oob_data_in(self, data): """ for Portal, this sends out-of-band requests to Server over the AMP. for Server, this receives data from Portal. data is a dictionary """ pass
Python
""" TTYPE (MTTS) - Mud Terminal Type Standard This module implements the TTYPE telnet protocol as per http://tintin.sourceforge.net/mtts/. It allows the server to ask the client about its capabilities. If the client also supports TTYPE, it will return with information such as its name, if it supports colour etc. If the client does not support TTYPE, this will be ignored. All data will be stored on the protocol's protocol_flags dictionary, under the 'TTYPE' key. """ # telnet option codes TTYPE = chr(24) IS = chr(0) SEND = chr(1) # terminal capabilities and their codes MTTS = [(128,'PROXY'), (64, 'SCREEN READER'), (32, 'OSC COLOR PALETTE'), (16, 'MOUSE TRACKING'), (8, '256 COLORS'), (4, 'UTF-8'), (2, 'VT100'), (1, 'ANSI')] class Ttype(object): """ Handles ttype negotiations. Called and initiated by the telnet protocol. """ def __init__(self, protocol): """ initialize ttype by storing protocol on ourselves and calling the client to see if it supporst ttype. the ttype_step indicates how far in the data retrieval we've gotten. """ self.ttype_step = 0 self.protocol = protocol self.protocol.protocol_flags['TTYPE'] = {} # setup protocol to handle ttype initialization and negotiation self.protocol.negotiationMap[TTYPE] = self.do_ttype # ask if client will ttype, connect callback if it does. self.protocol.will(TTYPE).addCallbacks(self.do_ttype, self.no_ttype) def no_ttype(self, option): """ Callback if ttype is not supported by client. """ pass def do_ttype(self, option): """ Handles negotiation of the ttype protocol once the client has confirmed that it supports the ttype protocol. The negotiation proceeds in several steps, each returning a certain piece of information about the client. All data is stored on protocol.protocol_flags under the TTYPE key. """ self.ttype_step += 1 if self.ttype_step == 1: # set up info storage and initialize subnegotiation self.protocol.requestNegotiation(TTYPE, SEND) else: # receive data option = "".join(option).lstrip(IS) if self.ttype_step == 2: self.protocol.protocol_flags['TTYPE']['CLIENTNAME'] = option self.protocol.requestNegotiation(TTYPE, SEND) elif self.ttype_step == 3: self.protocol.protocol_flags['TTYPE']['TERM'] = option self.protocol.requestNegotiation(TTYPE, SEND) elif self.ttype_step == 4: option = int(option.strip('MTTS ')) self.protocol.protocol_flags['TTYPE']['MTTS'] = option for codenum, standard in MTTS: if option == 0: break status = option % codenum < option self.protocol.protocol_flags['TTYPE'][standard] = status if status: option = option % codenum #print "ttype results:", self.protocol.protocol_flags['TTYPE']
Python
""" This module implements the ssh (Secure SHell) protocol for encrypted connections. This depends on a generic session module that implements the actual login procedure of the game, tracks sessions etc. Using standard ssh client, """ import os from twisted.cred.checkers import credentials from twisted.cred.portal import Portal from twisted.conch.ssh.keys import Key from twisted.conch.interfaces import IConchUser from twisted.conch.ssh.userauth import SSHUserAuthServer from twisted.conch.ssh import common from twisted.conch.insults import insults from twisted.conch.manhole_ssh import TerminalRealm, _Glue, ConchFactory from twisted.conch.manhole import Manhole, recvline from twisted.internet import defer from twisted.conch import interfaces as iconch from twisted.python import components from django.conf import settings from src.server import session from src.players.models import PlayerDB from src.utils import ansi, utils, logger # i18n from django.utils.translation import ugettext as _ ENCODINGS = settings.ENCODINGS CTRL_C = '\x03' CTRL_D = '\x04' CTRL_BACKSLASH = '\x1c' CTRL_L = '\x0c' class SshProtocol(Manhole, session.Session): """ Each player connecting over ssh gets this protocol assigned to them. All communication between game and player goes through here. """ def __init__(self, starttuple): """ For setting up the player. If player is not None then we'll login automatically. """ self.authenticated_player = starttuple[0] self.cfactory = starttuple[1] # obs may not be called self.factory, it gets overwritten! def terminalSize(self, width, height): """ Initialize the terminal and connect to the new session. """ # Clear the previous input line, redraw it at the new # cursor position self.terminal.eraseDisplay() self.terminal.cursorHome() self.width = width self.height = height # initialize the session client_address = self.getClientAddress() self.init_session("ssh", client_address, self.cfactory.sessionhandler) # since we might have authenticated already, we might set this here. if self.authenticated_player: self.logged_in = True self.uid = self.authenticated_player.user.id self.sessionhandler.connect(self) def connectionMade(self): """ This is called when the connection is first established. """ recvline.HistoricRecvLine.connectionMade(self) self.keyHandlers[CTRL_C] = self.handle_INT self.keyHandlers[CTRL_D] = self.handle_EOF self.keyHandlers[CTRL_L] = self.handle_FF self.keyHandlers[CTRL_BACKSLASH] = self.handle_QUIT # initalize def handle_INT(self): """ Handle ^C as an interrupt keystroke by resetting the current input variables to their initial state. """ self.lineBuffer = [] self.lineBufferIndex = 0 self.terminal.nextLine() self.terminal.write("KeyboardInterrupt") self.terminal.nextLine() def handle_EOF(self): """ Handles EOF generally used to exit. """ if self.lineBuffer: self.terminal.write('\a') else: self.handle_QUIT() def handle_FF(self): """ Handle a 'form feed' byte - generally used to request a screen refresh/redraw. """ self.terminal.eraseDisplay() self.terminal.cursorHome() def handle_QUIT(self): """ Quit, end, and lose the connection. """ self.terminal.loseConnection() def connectionLost(self, reason=None): """ This is executed when the connection is lost for whatever reason. It can also be called directly, from the disconnect method. """ insults.TerminalProtocol.connectionLost(self, reason) self.sessionhandler.disconnect(self) self.terminal.loseConnection() def getClientAddress(self): """ Returns the client's address and port in a tuple. For example ('127.0.0.1', 41917) """ return self.terminal.transport.getPeer() def lineReceived(self, string): """ Communication Player -> Evennia. Any line return indicates a command for the purpose of the MUD. So we take the user input and pass it on to the game engine. """ self.sessionhandler.data_in(self, string) def lineSend(self, string): """ Communication Evennia -> Player Any string sent should already have been properly formatted and processed before reaching this point. """ for line in string.split('\n'): self.terminal.write(line) #this is the telnet-specific method for sending self.terminal.nextLine() # session-general method hooks def disconnect(self, reason="Connection closed. Goodbye for now."): """ Disconnect from server """ if reason: self.data_out(reason) self.connectionLost(reason) def data_out(self, string, data=None): """ Data Evennia -> Player access hook. 'data' argument is a dict parsed for string settings. """ try: string = utils.to_str(string, encoding=self.encoding) except Exception, e: self.lineSend(str(e)) return nomarkup = False raw = False if type(data) == dict: # check if we want escape codes to go through unparsed. raw = data.get("raw", False) # check if we want to remove all markup nomarkup = data.get("nomarkup", False) if raw: self.lineSend(string) else: self.lineSend(ansi.parse_ansi(string, strip_ansi=nomarkup)) class ExtraInfoAuthServer(SSHUserAuthServer): def auth_password(self, packet): """ Password authentication. Used mostly for setting up the transport so we can query username and password later. """ password = common.getNS(packet[1:])[0] c = credentials.UsernamePassword(self.user, password) c.transport = self.transport return self.portal.login(c, None, IConchUser).addErrback( self._ebPassword) class PlayerDBPasswordChecker(object): """ Checks the django db for the correct credentials for username/password otherwise it returns the player or None which is useful for the Realm. """ credentialInterfaces = (credentials.IUsernamePassword,) def __init__(self, factory): self.factory = factory super(PlayerDBPasswordChecker, self).__init__() def requestAvatarId(self, c): "Generic credentials" up = credentials.IUsernamePassword(c, None) username = up.username password = up.password player = PlayerDB.objects.get_player_from_name(username) res = (None, self.factory) if player and player.user.check_password(password): res = (player, self.factory) return defer.succeed(res) class PassAvatarIdTerminalRealm(TerminalRealm): """ Returns an avatar that passes the avatarId through to the protocol. This is probably not the best way to do it. """ def _getAvatar(self, avatarId): comp = components.Componentized() user = self.userFactory(comp, avatarId) sess = self.sessionFactory(comp) sess.transportFactory = self.transportFactory sess.chainedProtocolFactory = lambda : self.chainedProtocolFactory(avatarId) comp.setComponent(iconch.IConchUser, user) comp.setComponent(iconch.ISession, sess) return user class TerminalSessionTransport_getPeer: """ Taken from twisted's TerminalSessionTransport which doesn't provide getPeer to the transport. This one does. """ def __init__(self, proto, chainedProtocol, avatar, width, height): self.proto = proto self.avatar = avatar self.chainedProtocol = chainedProtocol session = self.proto.session self.proto.makeConnection( _Glue(write=self.chainedProtocol.dataReceived, loseConnection=lambda: avatar.conn.sendClose(session), name="SSH Proto Transport")) def loseConnection(): self.proto.loseConnection() def getPeer(): session.conn.transport.transport.getPeer() self.chainedProtocol.makeConnection( _Glue(getPeer=getPeer, write=self.proto.write, loseConnection=loseConnection, name="Chained Proto Transport")) self.chainedProtocol.terminalProtocol.terminalSize(width, height) def getKeyPair(pubkeyfile, privkeyfile): """ This function looks for RSA keypair files in the current directory. If they do not exist, the keypair is created. """ if not (os.path.exists(pubkeyfile) and os.path.exists(privkeyfile)): # No keypair exists. Generate a new RSA keypair print _(" Generating SSH RSA keypair ..."), from Crypto.PublicKey import RSA KEY_LENGTH = 1024 rsaKey = Key(RSA.generate(KEY_LENGTH)) publicKeyString = rsaKey.public().toString(type="OPENSSH") privateKeyString = rsaKey.toString(type="OPENSSH") # save keys for the future. file(pubkeyfile, 'w+b').write(publicKeyString) file(privkeyfile, 'w+b').write(privateKeyString) print " done." else: publicKeyString = file(pubkeyfile).read() privateKeyString = file(privkeyfile).read() return Key.fromString(publicKeyString), Key.fromString(privateKeyString) def makeFactory(configdict): """ Creates the ssh server factory. """ pubkeyfile = "ssh-public.key" privkeyfile = "ssh-private.key" def chainProtocolFactory(username=None): return insults.ServerProtocol( configdict['protocolFactory'], *configdict.get('protocolConfigdict', (username,)), **configdict.get('protocolKwArgs', {})) rlm = PassAvatarIdTerminalRealm() rlm.transportFactory = TerminalSessionTransport_getPeer rlm.chainedProtocolFactory = chainProtocolFactory factory = ConchFactory(Portal(rlm)) factory.sessionhandler = configdict['sessions'] try: # create/get RSA keypair publicKey, privateKey = getKeyPair(pubkeyfile, privkeyfile) factory.publicKeys = {'ssh-rsa': publicKey} factory.privateKeys = {'ssh-rsa': privateKey} except Exception, e: print _(" getKeyPair error: %(e)s\n WARNING: Evennia could not auto-generate SSH keypair. Using conch default keys instead.") % {'e': e} print _(" If this error persists, create game/%(pub)s and game/%(priv)s yourself using third-party tools.") % {'pub': pubkeyfile, 'priv': privkeyfile} factory.services = factory.services.copy() factory.services['ssh-userauth'] = ExtraInfoAuthServer factory.portal.registerChecker(PlayerDBPasswordChecker(factory)) return factory
Python
""" Contains the protocols, commands, and client factory needed for the server to service the MUD portal proxy. The separation works like this: Portal - (AMP client) handles protocols. It contains a list of connected sessions in a dictionary for identifying the respective player connected. If it looses the AMP connection it will automatically try to reconnect. Server - (AMP server) Handles all mud operations. The server holds its own list of sessions tied to player objects. This is synced against the portal at startup and when a session connects/disconnects """ import os try: import cPickle as pickle except ImportError: import pickle from twisted.protocols import amp from twisted.internet import protocol, defer, reactor from django.conf import settings from src.utils import utils from src.server.models import ServerConfig from src.scripts.models import ScriptDB from src.players.models import PlayerDB from src.server.serversession import ServerSession PORTAL_RESTART = os.path.join(settings.GAME_DIR, "portal.restart") SERVER_RESTART = os.path.join(settings.GAME_DIR, "server.restart") # i18n from django.utils.translation import ugettext as _ def get_restart_mode(restart_file): """ Parse the server/portal restart status """ if os.path.exists(restart_file): flag = open(restart_file, 'r').read() return flag == "True" return False class AmpServerFactory(protocol.ServerFactory): """ This factory creates new AMPProtocol protocol instances to use for accepting connections from TCPServer. """ def __init__(self, server): """ server: The Evennia server service instance protocol: The protocol the factory creates instances of. """ self.server = server self.protocol = AMPProtocol def buildProtocol(self, addr): """ Start a new connection, and store it on the service object """ #print "Evennia Server connected to Portal at %s." % addr self.server.amp_protocol = AMPProtocol() self.server.amp_protocol.factory = self return self.server.amp_protocol class AmpClientFactory(protocol.ReconnectingClientFactory): """ This factory creates new AMPProtocol protocol instances to use to connect to the MUD server. It also maintains the portal attribute on the ProxyService instance, which is used for piping input from Telnet to the MUD server. """ # Initial reconnect delay in seconds. initialDelay = 1 #factor = 1.5 maxDelay = 1 def __init__(self, portal): self.portal = portal self.protocol = AMPProtocol def startedConnecting(self, connector): """ Called when starting to try to connect to the MUD server. """ pass #print 'AMP started to connect:', connector def buildProtocol(self, addr): """ Creates an AMPProtocol instance when connecting to the server. """ #print "Portal connected to Evennia server at %s." % addr self.resetDelay() self.portal.amp_protocol = AMPProtocol() self.portal.amp_protocol.factory = self return self.portal.amp_protocol def clientConnectionLost(self, connector, reason): """ Called when the AMP connection to the MUD server is lost. """ if not get_restart_mode(SERVER_RESTART): self.portal.sessions.announce_all(_(" Portal lost connection to Server.")) protocol.ReconnectingClientFactory.clientConnectionLost(self, connector, reason) def clientConnectionFailed(self, connector, reason): """ Called when an AMP connection attempt to the MUD server fails. """ self.portal.sessions.announce_all(" ...") protocol.ReconnectingClientFactory.clientConnectionFailed(self, connector, reason) class MsgPortal2Server(amp.Command): """ Message portal -> server """ arguments = [('sessid', amp.Integer()), ('msg', amp.String()), ('data', amp.String())] errors = [(Exception, 'EXCEPTION')] response = [] class MsgServer2Portal(amp.Command): """ Message server -> portal """ arguments = [('sessid', amp.Integer()), ('msg', amp.String()), ('data', amp.String())] errors = [(Exception, 'EXCEPTION')] response = [] class OOBPortal2Server(amp.Command): """ OOB data portal -> server """ arguments = [('sessid', amp.Integer()), ('data', amp.String())] errors = [(Exception, "EXCEPTION")] response = [] class OOBServer2Portal(amp.Command): """ OOB data server -> portal """ arguments = [('sessid', amp.Integer()), ('data', amp.String())] errors = [(Exception, "EXCEPTION")] response = [] class ServerAdmin(amp.Command): """ Portal -> Server Sent when the portal needs to perform admin operations on the server, such as when a new session connects or resyncs """ arguments = [('sessid', amp.Integer()), ('operation', amp.String()), ('data', amp.String())] errors = [(Exception, 'EXCEPTION')] response = [] class PortalAdmin(amp.Command): """ Server -> Portal Sent when the server needs to perform admin operations on the portal. """ arguments = [('sessid', amp.Integer()), ('operation', amp.String()), ('data', amp.String())] errors = [(Exception, 'EXCEPTION')] response = [] dumps = lambda data: utils.to_str(pickle.dumps(data, pickle.HIGHEST_PROTOCOL)) loads = lambda data: pickle.loads(utils.to_str(data)) #------------------------------------------------------------ # Core AMP protocol for communication Server <-> Portal #------------------------------------------------------------ class AMPProtocol(amp.AMP): """ This is the protocol that the MUD server and the proxy server communicate to each other with. AMP is a bi-directional protocol, so both the proxy and the MUD use the same commands and protocol. AMP specifies responder methods here and connect them to amp.Command subclasses that specify the datatypes of the input/output of these methods. """ # helper methods def connectionMade(self): """ This is called when a connection is established between server and portal. It is called on both sides, so we need to make sure to only trigger resync from the server side. """ if hasattr(self.factory, "portal"): sessdata = self.factory.portal.sessions.get_all_sync_data() #print sessdata self.call_remote_ServerAdmin(0, "PSYNC", data=sessdata) if get_restart_mode(SERVER_RESTART): msg = _(" ... Server restarted.") self.factory.portal.sessions.announce_all(msg) self.factory.portal.sessions.at_server_connection() # Error handling def errback(self, e, info): "error handler, to avoid dropping connections on server tracebacks." e.trap(Exception) print _("AMP Error for %(info)s: %(e)s") % {'info': info, 'e': e.getErrorMessage()} # Message definition + helper methods to call/create each message type # Portal -> Server Msg def amp_msg_portal2server(self, sessid, msg, data): """ Relays message to server. This method is executed on the Server. """ #print "msg portal -> server (server side):", sessid, msg self.factory.server.sessions.data_in(sessid, msg, loads(data)) return {} MsgPortal2Server.responder(amp_msg_portal2server) def call_remote_MsgPortal2Server(self, sessid, msg, data=""): """ Access method called by the Portal and executed on the Portal. """ #print "msg portal->server (portal side):", sessid, msg self.callRemote(MsgPortal2Server, sessid=sessid, msg=msg, data=dumps(data)).addErrback(self.errback, "MsgPortal2Server") # Server -> Portal message def amp_msg_server2portal(self, sessid, msg, data): """ Relays message to Portal. This method is executed on the Portal. """ #print "msg server->portal (portal side):", sessid, msg self.factory.portal.sessions.data_out(sessid, msg, loads(data)) return {} MsgServer2Portal.responder(amp_msg_server2portal) def call_remote_MsgServer2Portal(self, sessid, msg, data=""): """ Access method called by the Server and executed on the Server. """ #print "msg server->portal (server side):", sessid, msg, data self.callRemote(MsgServer2Portal, sessid=sessid, msg=utils.to_str(msg), data=dumps(data)).addErrback(self.errback, "OOBServer2Portal") # OOB Portal -> Server # Portal -> Server Msg def amp_oob_portal2server(self, sessid, data): """ Relays out-of-band data to server. This method is executed on the Server. """ #print "oob portal -> server (server side):", sessid, loads(data) self.factory.server.sessions.oob_data_in(sessid, loads(data)) return {} OOBPortal2Server.responder(amp_oob_portal2server) def call_remote_OOBPortal2Server(self, sessid, data=""): """ Access method called by the Portal and executed on the Portal. """ #print "oob portal->server (portal side):", sessid, data self.callRemote(OOBPortal2Server, sessid=sessid, data=dumps(data)).addErrback(self.errback, "OOBPortal2Server") # Server -> Portal message def amp_oob_server2portal(self, sessid, data): """ Relays out-of-band data to Portal. This method is executed on the Portal. """ #print "oob server->portal (portal side):", sessid, data self.factory.portal.sessions.oob_data_out(sessid, loads(data)) return {} OOBServer2Portal.responder(amp_oob_server2portal) def call_remote_OOBServer2Portal(self, sessid, data=""): """ Access method called by the Server and executed on the Server. """ #print "oob server->portal (server side):", sessid, data self.callRemote(OOBServer2Portal, sessid=sessid, data=dumps(data)).addErrback(self.errback, "OOBServer2Portal") # Server administration from the Portal side def amp_server_admin(self, sessid, operation, data): """ This allows the portal to perform admin operations on the server. This is executed on the Server. """ data = loads(data) #print "serveradmin (server side):", sessid, operation, data if operation == 'PCONN': #portal_session_connect # create a new session and sync it sess = ServerSession() sess.sessionhandler = self.factory.server.sessions sess.load_sync_data(data) if sess.logged_in and sess.uid: # this can happen in the case of auto-authenticating protocols like SSH sess.player = PlayerDB.objects.get_player_from_uid(sess.uid) sess.at_sync() # this runs initialization without acr self.factory.server.sessions.portal_connect(sessid, sess) elif operation == 'PDISCONN': #'portal_session_disconnect' # session closed from portal side self.factory.server.sessions.portal_disconnect(sessid) elif operation == 'PSYNC': #'portal_session_sync' # force a resync of sessions when portal reconnects to server (e.g. after a server reboot) # the data kwarg contains a dict {sessid: {arg1:val1,...}} representing the attributes # to sync for each session. sesslist = [] server_sessionhandler = self.factory.server.sessions for sessid, sessdict in data.items(): sess = ServerSession() sess.sessionhandler = server_sessionhandler sess.load_sync_data(sessdict) if sess.uid: sess.player = PlayerDB.objects.get_player_from_uid(sess.uid) sesslist.append(sess) # replace sessions on server server_sessionhandler.portal_session_sync(sesslist) # after sync is complete we force-validate all scripts (this starts everthing) init_mode = ServerConfig.objects.conf("server_restart_mode", default=None) ScriptDB.objects.validate(init_mode=init_mode) ServerConfig.objects.conf("server_restart_mode", delete=True) else: raise Exception(_("operation %(op)s not recognized.") % {'op': operation}) return {} ServerAdmin.responder(amp_server_admin) def call_remote_ServerAdmin(self, sessid, operation="", data=""): """ Access method called by the Portal and Executed on the Portal. """ #print "serveradmin (portal side):", sessid, operation, data data = dumps(data) self.callRemote(ServerAdmin, sessid=sessid, operation=operation, data=data).addErrback(self.errback, "ServerAdmin") # Portal administraton from the Server side def amp_portal_admin(self, sessid, operation, data): """ This allows the server to perform admin operations on the portal. This is executed on the Portal. """ data = loads(data) #print "portaladmin (portal side):", sessid, operation, data if operation == 'SLOGIN': # 'server_session_login' # a session has authenticated; sync it. sess = self.factory.portal.sessions.get_session(sessid) sess.load_sync_data(data) elif operation == 'SDISCONN': #'server_session_disconnect' # the server is ordering to disconnect the session self.factory.portal.sessions.server_disconnect(sessid, reason=data) elif operation == 'SDISCONNALL': #'server_session_disconnect_all' # server orders all sessions to disconnect self.factory.portal.sessions.server_disconnect_all(reason=data) elif operation == 'SSHUTD': #server_shutdown' # the server orders the portal to shut down self.factory.portal.shutdown(restart=False) elif operation == 'SSYNC': #'server_session_sync' # server wants to save session data to the portal, maybe because # it's about to shut down. We don't overwrite any sessions, # just update data on them and remove eventual ones that are # out of sync (shouldn't happen normally). portal_sessionhandler = self.factory.portal.sessions.sessions to_save = [sessid for sessid in data if sessid in portal_sessionhandler.sessions] to_delete = [sessid for sessid in data if sessid not in to_save] # save protocols for sessid in to_save: portal_sessionhandler.sessions[sessid].load_sync_data(data[sessid]) # disconnect missing protocols for sessid in to_delete: portal_sessionhandler.server_disconnect(sessid) else: raise Exception(_("operation %(op)s not recognized.") % {'op': operation}) return {} PortalAdmin.responder(amp_portal_admin) def call_remote_PortalAdmin(self, sessid, operation="", data=""): """ Access method called by the server side. """ #print "portaladmin (server side):", sessid, operation, data data = dumps(data) self.callRemote(PortalAdmin, sessid=sessid, operation=operation, data=data).addErrback(self.errback, "PortalAdmin")
Python
""" This module handles initial database propagation, which is only run the first time the game starts. It will create some default channels, objects, and other things. Everything starts at handle_setup() """ from django.contrib.auth.models import User from django.core import management from django.conf import settings from src.server.models import ServerConfig from src.help.models import HelpEntry from src.utils import create # i18n from django.utils.translation import ugettext as _ def create_config_values(): """ Creates the initial config values. """ ServerConfig.objects.conf("site_name", settings.SERVERNAME) ServerConfig.objects.conf("idle_timeout", settings.IDLE_TIMEOUT) def get_god_user(): """ Returns the initially created 'god' User object. """ return User.objects.get(id=1) def create_objects(): """ Creates the #1 player and Limbo room. """ print _(" Creating objects (Player #1 and Limbo room) ...") # Set the initial User's account object's username on the #1 object. # This object is pure django and only holds name, email and password. god_user = get_god_user() # Create a Player 'user profile' object to hold eventual # mud-specific settings for the bog standard User object. This is # accessed by user.get_profile() and can also store attributes. # It also holds mud permissions, but for a superuser these # have no effect anyhow. character_typeclass = settings.BASE_CHARACTER_TYPECLASS # Create the Player object as well as the in-game god-character # for user #1. We can't set location and home yet since nothing # exists. Also, all properties (name, email, password, is_superuser) # is inherited from the user so we don't specify it again here. god_character = create.create_player(god_user.username, None, None, user=god_user, create_character=True, character_typeclass=character_typeclass) if not god_character: raise Exception(_("#1 could not be created. Check the Player/Character typeclass for bugs.")) god_character.id = 1 god_character.db.desc = _('This is User #1.') god_character.locks.add("examine:perm(Immortals);edit:false();delete:false();boot:false();msg:all();puppet:false()") god_character.save() # Limbo is the default "nowhere" starting room room_typeclass = settings.BASE_ROOM_TYPECLASS limbo_obj = create.create_object(room_typeclass, _('Limbo')) limbo_obj.id = 2 string = " Welcome to your new {wEvennia{n-based game." string += " From here you are ready to begin development." string += " If you should need help or would like to participate" string += " in community discussions, visit http://evennia.com." string = _(string) limbo_obj.db.desc = string limbo_obj.save() # Now that Limbo exists, try to set the user up in Limbo (unless # the creation hooks already fixed this). if not god_character.location: god_character.location = limbo_obj if not god_character.home: god_character.home = limbo_obj def create_channels(): """ Creates some sensible default channels. """ print _(" Creating default channels ...") # public channel key, aliases, desc, locks = settings.CHANNEL_PUBLIC pchan = create.create_channel(key, aliases, desc, locks=locks) # mudinfo channel key, aliases, desc, locks = settings.CHANNEL_MUDINFO ichan = create.create_channel(key, aliases, desc, locks=locks) # connectinfo channel key, aliases, desc, locks = settings.CHANNEL_CONNECTINFO cchan = create.create_channel(key, aliases, desc, locks=locks) # connect the god user to all these channels by default. goduser = get_god_user() from src.comms.models import PlayerChannelConnection PlayerChannelConnection.objects.create_connection(goduser, pchan) PlayerChannelConnection.objects.create_connection(goduser, ichan) PlayerChannelConnection.objects.create_connection(goduser, cchan) def import_MUX_help_files(): """ Imports the MUX help files. """ print _(" Importing MUX help database (devel reference only) ...") management.call_command('loaddata', '../src/help/mux_help_db.json', verbosity=0) # categorize the MUX help files into its own category. default_category = "MUX" print _(" Moving imported help db to help category '%(default)s'." \ % {'default': default_category}) HelpEntry.objects.all_to_category(default_category) def create_system_scripts(): """ Setup the system repeat scripts. They are automatically started by the create_script function. """ from src.scripts import scripts print _(" Creating and starting global scripts ...") # check so that all sessions are alive. script1 = create.create_script(scripts.CheckSessions) # validate all scripts in script table. script2 = create.create_script(scripts.ValidateScripts) # update the channel handler to make sure it's in sync script3 = create.create_script(scripts.ValidateChannelHandler) if not script1 or not script2 or not script3: print _(" Error creating system scripts.") def start_game_time(): """ This starts a persistent script that keeps track of the in-game time (in whatever accelerated reference frame), but also the total run time of the server as well as its current uptime (the uptime can also be found directly from the server though). """ print _(" Starting in-game time ...") from src.utils import gametime gametime.init_gametime() def create_admin_media_links(): """ This traverses to src/web/media and tries to create a symbolic link to the django media files from within the MEDIA_ROOT. These are files we normally don't want to mess with (use templates to customize the admin look). Linking is needed since the Twisted webserver otherwise has no notion of where the default files are - and we cannot hard-code it since the django install may be at different locations depending on system. """ import django, os dpath = os.path.join(django.__path__[0], 'contrib', 'admin', 'media') apath = os.path.join(settings.ADMIN_MEDIA_ROOT) if os.path.isdir(apath): print _(" ADMIN_MEDIA_ROOT already exists. Ignored.") return if os.name == 'nt': print _(" Admin-media files copied to ADMIN_MEDIA_ROOT (Windows mode).") os.mkdir(apath) os.system('xcopy "%s" "%s" /e /q /c' % (dpath, apath)) if os.name == 'posix': os.symlink(dpath, apath) print _(" Admin-media symlinked to ADMIN_MEDIA_ROOT.") else: print _(" Admin-media files should be copied manually to ADMIN_MEDIA_ROOT.") def at_initial_setup(): """ Custom hook for users to overload some or all parts of the initial setup. Called very last in the sequence. It tries to import and run a module settings.AT_INITIAL_SETUP_HOOK_MODULE and will fail silently if this does not exist or fails to load. """ try: mod = __import__(settings.AT_INITIAL_SETUP_HOOK_MODULE, fromlist=[None]) except ImportError: return print _(" Running at_initial_setup() hook.") if mod.__dict__.get("at_initial_setup", None): mod.at_initial_setup() def handle_setup(last_step): """ Main logic for the module. It allows for restarting the initialization at any point if one of the modules should crash. """ if last_step < 0: # this means we don't need to handle setup since # it already ran sucessfully once. return elif last_step == None: # config doesn't exist yet. First start of server last_step = 0 # setting up the list of functions to run setup_queue = [ create_config_values, create_objects, create_channels, create_system_scripts, start_game_time, create_admin_media_links, import_MUX_help_files, at_initial_setup] if not settings.IMPORT_MUX_HELP: # skip importing of the MUX helpfiles, they are # not interesting except for developers. del setup_queue[-2] #print " Initial setup: %s steps." % (len(setup_queue)) # step through queue, from last completed function for num, setup_func in enumerate(setup_queue[last_step:]): # run the setup function. Note that if there is a # traceback we let it stop the system so the config # step is not saved. #print "%s..." % num try: setup_func() except Exception: if last_step + num == 2: from src.players.models import PlayerDB from src.objects.models import ObjectDB for obj in ObjectDB.objects.all(): obj.delete() for profile in PlayerDB.objects.all(): profile.delete() elif last_step + num == 3: from src.comms.models import Channel, PlayerChannelConnection for chan in Channel.objects.all(): chan.delete() for conn in PlayerChannelConnection.objects.all(): conn.delete() raise ServerConfig.objects.conf("last_initial_setup_step", last_step + num + 1) # We got through the entire list. Set last_step to -1 so we don't # have to run this again. ServerConfig.objects.conf("last_initial_setup_step", -1)
Python
""" This module implements the main Evennia server process, the core of the game engine. This module should be started with the 'twistd' executable since it sets up all the networking features. (this is done automatically by game/evennia.py). """ import time import sys import os import signal if os.name == 'nt': # For Windows batchfile we need an extra path insertion here. sys.path.insert(0, os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__))))) from twisted.application import internet, service from twisted.internet import protocol, reactor, defer from twisted.web import server, static import django from django.db import connection from django.conf import settings from src.scripts.models import ScriptDB from src.server.models import ServerConfig from src.server import initial_setup from src.utils.utils import get_evennia_version from src.comms import channelhandler from src.server.sessionhandler import SESSIONS if os.name == 'nt': # For Windows we need to handle pid files manually. SERVER_PIDFILE = os.path.join(settings.GAME_DIR, 'server.pid') SERVER_RESTART = os.path.join(settings.GAME_DIR, 'server.restart') # i18n from django.utils.translation import ugettext as _ #------------------------------------------------------------ # Evennia Server settings #------------------------------------------------------------ SERVERNAME = settings.SERVERNAME VERSION = get_evennia_version() AMP_ENABLED = True AMP_HOST = settings.AMP_HOST AMP_PORT = settings.AMP_PORT # server-channel mappings IMC2_ENABLED = settings.IMC2_ENABLED IRC_ENABLED = settings.IRC_ENABLED RSS_ENABLED = settings.RSS_ENABLED #------------------------------------------------------------ # Evennia Main Server object #------------------------------------------------------------ class Evennia(object): """ The main Evennia server handler. This object sets up the database and tracks and interlinks all the twisted network services that make up evennia. """ def __init__(self, application): """ Setup the server. application - an instantiated Twisted application """ sys.path.append('.') # create a store of services self.services = service.IServiceCollection(application) self.amp_protocol = None # set by amp factory self.sessions = SESSIONS self.sessions.server = self print '\n' + '-'*50 # Database-specific startup optimizations. self.sqlite3_prep() # Run the initial setup if needed self.run_initial_setup() self.start_time = time.time() # initialize channelhandler channelhandler.CHANNELHANDLER.update() # Make info output to the terminal. self.terminal_output() print '-'*50 # set a callback if the server is killed abruptly, # by Ctrl-C, reboot etc. reactor.addSystemEventTrigger('before', 'shutdown', self.shutdown, _abrupt=True) self.game_running = True self.run_init_hooks() # Server startup methods def sqlite3_prep(self): """ Optimize some SQLite stuff at startup since we can't save it to the database. """ if ((".".join(str(i) for i in django.VERSION) < "1.2" and settings.DATABASE_ENGINE == "sqlite3") or (hasattr(settings, 'DATABASES') and settings.DATABASES.get("default", {}).get('ENGINE', None) == 'django.db.backends.sqlite3')): cursor = connection.cursor() cursor.execute("PRAGMA cache_size=10000") cursor.execute("PRAGMA synchronous=OFF") cursor.execute("PRAGMA count_changes=OFF") cursor.execute("PRAGMA temp_store=2") def run_initial_setup(self): """ This attempts to run the initial_setup script of the server. It returns if this is not the first time the server starts. """ last_initial_setup_step = ServerConfig.objects.conf('last_initial_setup_step') if not last_initial_setup_step: # None is only returned if the config does not exist, # i.e. this is an empty DB that needs populating. print _(' Server started for the first time. Setting defaults.') initial_setup.handle_setup(0) print '-'*50 elif int(last_initial_setup_step) >= 0: # a positive value means the setup crashed on one of its # modules and setup will resume from this step, retrying # the last failed module. When all are finished, the step # is set to -1 to show it does not need to be run again. print _(' Resuming initial setup from step %(last)s.' % \ {'last': last_initial_setup_step}) initial_setup.handle_setup(int(last_initial_setup_step)) print '-'*50 def run_init_hooks(self): """ Called every server start """ from src.objects.models import ObjectDB from src.players.models import PlayerDB #print "run_init_hooks:", ObjectDB.get_all_cached_instances() [(o.typeclass, o.at_init()) for o in ObjectDB.get_all_cached_instances()] [(p.typeclass, p.at_init()) for p in PlayerDB.get_all_cached_instances()] def terminal_output(self): """ Outputs server startup info to the terminal. """ print _(' %(servername)s Server (%(version)s) started.') % {'servername': SERVERNAME, 'version': VERSION} print ' amp (Portal): %s' % AMP_PORT def set_restart_mode(self, mode=None): """ This manages the flag file that tells the runner if the server is reloading, resetting or shutting down. Valid modes are 'reload', 'reset', 'shutdown' and None. If mode is None, no change will be done to the flag file. Either way, the active restart setting (Restart=True/False) is returned so the server knows which more it's in. """ if mode == None: if os.path.exists(SERVER_RESTART) and 'True' == open(SERVER_RESTART, 'r').read(): mode = 'reload' else: mode = 'shutdown' else: restart = mode in ('reload', 'reset') f = open(SERVER_RESTART, 'w') f.write(str(restart)) f.close() return mode def shutdown(self, mode=None, _abrupt=False): """ Shuts down the server from inside it. mode - sets the server restart mode. 'reload' - server restarts, no "persistent" scripts are stopped, at_reload hooks called. 'reset' - server restarts, non-persistent scripts stopped, at_shutdown hooks called. 'shutdown' - like reset, but server will not auto-restart. None - keep currently set flag from flag file. _abrupt - this is set if server is stopped by a kill command, in which case the reactor is dead anyway. """ mode = self.set_restart_mode(mode) # call shutdown hooks on all cached objects from src.objects.models import ObjectDB from src.players.models import PlayerDB from src.server.models import ServerConfig if mode == 'reload': # call restart hooks [(o.typeclass, o.at_server_reload()) for o in ObjectDB.get_all_cached_instances()] [(p.typeclass, p.at_server_reload()) for p in PlayerDB.get_all_cached_instances()] [(s.typeclass, s.pause(), s.at_server_reload()) for s in ScriptDB.get_all_cached_instances()] ServerConfig.objects.conf("server_restart_mode", "reload") else: if mode == 'reset': # don't call disconnect hooks on reset [(o.typeclass, o.at_server_shutdown()) for o in ObjectDB.get_all_cached_instances()] else: # shutdown [(o.typeclass, o.at_disconnect(), o.at_server_shutdown()) for o in ObjectDB.get_all_cached_instances()] [(p.typeclass, p.at_server_shutdown()) for p in PlayerDB.get_all_cached_instances()] [(s.typeclass, s.at_server_shutdown()) for s in ScriptDB.get_all_cached_instances()] ServerConfig.objects.conf("server_restart_mode", "reset") if not _abrupt: reactor.callLater(0, reactor.stop) if os.name == 'nt' and os.path.exists(SERVER_PIDFILE): # for Windows we need to remove pid files manually os.remove(SERVER_PIDFILE) #------------------------------------------------------------ # # Start the Evennia game server and add all active services # #------------------------------------------------------------ # Tell the system the server is starting up; some things are not available yet ServerConfig.objects.conf("server_starting_mode", True) # twistd requires us to define the variable 'application' so it knows # what to execute from. application = service.Application('Evennia') # The main evennia server program. This sets up the database # and is where we store all the other services. EVENNIA = Evennia(application) # The AMP protocol handles the communication between # the portal and the mud server. Only reason to ever deactivate # it would be during testing and debugging. if AMP_ENABLED: from src.server import amp factory = amp.AmpServerFactory(EVENNIA) amp_service = internet.TCPServer(AMP_PORT, factory) amp_service.setName("EvenniaPortal") EVENNIA.services.addService(amp_service) if IRC_ENABLED: # IRC channel connections from src.comms import irc irc.connect_all() if IMC2_ENABLED: # IMC2 channel connections from src.comms import imc2 imc2.connect_all() if RSS_ENABLED: # RSS feed channel connections from src.comms import rss rss.connect_all() # clear server startup mode ServerConfig.objects.conf("server_starting_mode", delete=True) if os.name == 'nt': # Windows only: Set PID file manually f = open(os.path.join(settings.GAME_DIR, 'server.pid'), 'w') f.write(str(os.getpid())) f.close()
Python
# # This sets up how models are displayed # in the web admin interface. # from django import forms from django.db import models from django.conf import settings from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.admin import widgets from django.contrib.auth.forms import UserChangeForm, UserCreationForm from django.contrib.auth.models import User from src.players.models import PlayerDB, PlayerAttribute from src.utils import logger, create # remove User itself from admin site admin.site.unregister(User) # handle the custom User editor class CustomUserChangeForm(UserChangeForm): username = forms.RegexField(label="Username", max_length=30, regex=r'^[\w. @+-]+$', widget=forms.TextInput(attrs={'size':'30'}), error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."}, help_text = "30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.") class CustomUserCreationForm(UserCreationForm): username = forms.RegexField(label="Username", max_length=30, regex=r'^[\w. @+-]+$', widget=forms.TextInput(attrs={'size':'30'}), error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."}, help_text = "30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.") # # The Player editor # class PlayerAttributeForm(forms.ModelForm): # "Defines how to display the atttributes" # class Meta: # model = PlayerAttribute # db_key = forms.CharField(label="Key", # widget=forms.TextInput(attrs={'size':'15'})) # db_value = forms.CharField(label="Value", # widget=forms.Textarea(attrs={'rows':'2'})) # class PlayerAttributeInline(admin.TabularInline): # "Inline creation of player attributes" # model = PlayerAttribute # extra = 0 # form = PlayerAttributeForm # fieldsets = ( # (None, {'fields' : (('db_key', 'db_value'))}),) class PlayerForm(forms.ModelForm): "Defines how to display Players" class Meta: model = PlayerDB db_key = forms.RegexField(label="Username", initial="PlayerDummy", max_length=30, regex=r'^[\w. @+-]+$', required=False, widget=forms.TextInput(attrs={'size':'30'}), error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."}, help_text = "This should be the same as the connected Player's key name. 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.") db_typeclass_path = forms.CharField(label="Typeclass", initial=settings.BASE_PLAYER_TYPECLASS, widget=forms.TextInput(attrs={'size':'78'}), help_text="Required. Defines what 'type' of entity this is. This variable holds a Python path to a module with a valid Evennia Typeclass. Defaults to settings.BASE_PLAYER_TYPECLASS.") db_permissions = forms.CharField(label="Permissions", initial=settings.PERMISSION_PLAYER_DEFAULT, required=False, widget=forms.TextInput(attrs={'size':'78'}), help_text="In-game permissions. A comma-separated list of text strings checked by certain locks. They are often used for hierarchies, such as letting a Player have permission 'Wizards', 'Builders' etc. A Player permission can be overloaded by the permissions of a controlled Character. Normal players use 'Players' by default.") db_lock_storage = forms.CharField(label="Locks", widget=forms.Textarea(attrs={'cols':'100', 'rows':'2'}), required=False, help_text="In-game lock definition string. If not given, defaults will be used. This string should be on the form <i>type:lockfunction(args);type2:lockfunction2(args);...") db_cmdset_storage = forms.CharField(label="cmdset", initial=settings.CMDSET_OOC, widget=forms.TextInput(attrs={'size':'78'}), required=False, help_text="python path to player cmdset class (settings.CMDSET_OOC by default)") class PlayerInline(admin.StackedInline): "Inline creation of Player" model = PlayerDB template = "admin/players/stacked.html" form = PlayerForm fieldsets = ( ("In-game Permissions and Locks", {'fields': ('db_permissions', 'db_lock_storage'), 'description':"<i>These are permissions/locks for in-game use. They are unrelated to website access rights.</i>"}), ("In-game Player data", {'fields':('db_typeclass_path', 'db_cmdset_storage'), 'description':"<i>These fields define in-game-specific properties for the Player object in-game.</i>"}), ("Evennia In-game Character", {'fields':('db_obj',), 'description': "<i>To actually play the game, a Player must control a Character. This could be added in-game instead of from here if some sort of character creation system is in play. If not, you should normally create a new Character here rather than assigning an existing one. Observe that the admin does not check for puppet-access rights when assigning Characters! If not creating a new Character, make sure the one you assign is not puppeted by someone else!</i>"})) extra = 1 max_num = 1 class UserAdmin(BaseUserAdmin): "This is the main creation screen for Users/players" list_display = ('username','email', 'is_staff', 'is_superuser') form = CustomUserChangeForm add_form = CustomUserCreationForm inlines = [PlayerInline] add_form_template = "admin/players/add_form.html" change_form_template = "admin/players/change_form.html" change_list_template = "admin/players/change_list.html" fieldsets = ( (None, {'fields': ('username', 'password', 'email')}), ('Website profile', {'fields': ('first_name', 'last_name'), 'description':"<i>These are not used in the default system.</i>"}), ('Website dates', {'fields': ('last_login', 'date_joined'), 'description':'<i>Relevant only to the website.</i>'}), ('Website Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions','groups'), 'description': "<i>These are permissions/permission groups for accessing the admin site. They are unrelated to in-game access rights.</i>"}),) add_fieldsets = ( (None, {'fields': ('username', 'password1', 'password2', 'email'), 'description':"<i>These account details are shared by the admin system and the game.</i>"},),) def save_formset(self, request, form, formset, change): "Run all hooks on the player object" super(UserAdmin, self).save_formset(request, form, formset, change) playerdb = form.instance.get_profile() if not change: create.create_player("", "", "", typeclass=playerdb.db_typeclass_path, create_character=False, player_dbobj=playerdb) if playerdb.db_obj: playerdb.db_obj.db_player = playerdb playerdb.db_obj.save() #assert False, (form.instance, form.instance.get_profile()) admin.site.register(User, UserAdmin)
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): depends_on = ( ("objects", "0001_initial"), ) def forwards(self, orm): # Adding model 'PlayerAttribute' db.create_table('players_playerattribute', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(max_length=255)), ('db_value', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('db_mode', self.gf('django.db.models.fields.CharField')(max_length=20, null=True, blank=True)), ('db_lock_storage', self.gf('django.db.models.fields.TextField')(blank=True)), ('db_date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('db_obj', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['players.PlayerDB'])), )) db.send_create_signal('players', ['PlayerAttribute']) # Adding model 'PlayerDB' db.create_table('players_playerdb', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(max_length=255)), ('db_typeclass_path', self.gf('django.db.models.fields.CharField')(max_length=255, null=True)), ('db_date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('db_permissions', self.gf('django.db.models.fields.CharField')(max_length=512, blank=True)), ('db_lock_storage', self.gf('django.db.models.fields.TextField')(blank=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], unique=True)), ('db_obj', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['objects.ObjectDB'], null=True)), )) db.send_create_signal('players', ['PlayerDB']) # Hack to get around circular table creation. db.add_column('objects_objectdb', 'db_player', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['players.PlayerDB'], null=True, blank=True)) def backwards(self, orm): # Deleting model 'PlayerAttribute' db.delete_table('players_playerattribute') # Deleting model 'PlayerDB' db.delete_table('players_playerdb') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerattribute': { 'Meta': {'object_name': 'PlayerAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_mode': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['players']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding index on 'PlayerDB', fields ['db_key'] db.create_index('players_playerdb', ['db_key']) # Adding index on 'PlayerAttribute', fields ['db_key'] db.create_index('players_playerattribute', ['db_key']) def backwards(self, orm): # Removing index on 'PlayerAttribute', fields ['db_key'] db.delete_index('players_playerattribute', ['db_key']) # Removing index on 'PlayerDB', fields ['db_key'] db.delete_index('players_playerdb', ['db_key']) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerattribute': { 'Meta': {'object_name': 'PlayerAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'players.playernick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'PlayerNick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['players']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models, utils from django.conf import settings class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." try: for player in orm.PlayerDB.objects.all(): if not player.db_cmdset_storage: player.db_cmdset_storage = settings.CMDSET_OOC player.save() except utils.DatabaseError: # this will happen if we start db from scratch (ignore in that case) pass def backwards(self, orm): "Write your backwards methods here." raise RuntimeError("This migration cannot be reverted.") models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerattribute': { 'Meta': {'object_name': 'PlayerAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'players.playernick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'PlayerNick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['players']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'PlayerNick' db.create_table('players_playernick', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_nick', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)), ('db_real', self.gf('django.db.models.fields.TextField')()), ('db_type', self.gf('django.db.models.fields.CharField')(default='inputline', max_length=16, null=True, blank=True)), ('db_obj', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['players.PlayerDB'])), )) db.send_create_signal('players', ['PlayerNick']) # Adding unique constraint on 'PlayerNick', fields ['db_nick', 'db_type', 'db_obj'] db.create_unique('players_playernick', ['db_nick', 'db_type', 'db_obj_id']) def backwards(self, orm): # Removing unique constraint on 'PlayerNick', fields ['db_nick', 'db_type', 'db_obj'] db.delete_unique('players_playernick', ['db_nick', 'db_type', 'db_obj_id']) # Deleting model 'PlayerNick' db.delete_table('players_playernick') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerattribute': { 'Meta': {'object_name': 'PlayerAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'players.playernick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'PlayerNick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['players']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'PlayerDB.db_cmdset_storage' db.alter_column('players_playerdb', 'db_cmdset_storage', self.gf('django.db.models.fields.CharField')(max_length=255, null=True)) # Changing field 'PlayerDB.db_lock_storage' db.alter_column('players_playerdb', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512)) # Changing field 'PlayerDB.db_permissions' db.alter_column('players_playerdb', 'db_permissions', self.gf('django.db.models.fields.CharField')(max_length=255)) # Changing field 'PlayerAttribute.db_lock_storage' db.alter_column('players_playerattribute', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512)) def backwards(self, orm): # Changing field 'PlayerDB.db_cmdset_storage' db.alter_column('players_playerdb', 'db_cmdset_storage', self.gf('django.db.models.fields.TextField')(null=True)) # Changing field 'PlayerDB.db_lock_storage' db.alter_column('players_playerdb', 'db_lock_storage', self.gf('django.db.models.fields.TextField')()) # Changing field 'PlayerDB.db_permissions' db.alter_column('players_playerdb', 'db_permissions', self.gf('django.db.models.fields.CharField')(max_length=512)) # Changing field 'PlayerAttribute.db_lock_storage' db.alter_column('players_playerattribute', 'db_lock_storage', self.gf('django.db.models.fields.TextField')()) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerattribute': { 'Meta': {'object_name': 'PlayerAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'players.playernick': { 'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'PlayerNick'}, 'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_real': ('django.db.models.fields.TextField', [], {}), 'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['players']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'PlayerAttribute.db_mode' from src.players.models import PlayerAttribute from src.typeclasses.models import PackedDBobject for attr in PlayerAttribute.objects.all(): # resave attributes db_mode = attr.db_mode if db_mode and db_mode != 'pickle': # an object. We need to resave this. if db_mode == 'object': val = PackedDBobject(attr.db_value, "objectdb") elif db_mode == 'player': val = PackedDBobject(attr.db_value, "playerdb") elif db_mode == 'script': val = PackedDBobject(attr.db_value, "scriptdb") elif db_mode == 'help': val = PackedDBobject(attr.db_value, "helpentry") else: val = PackedDBobject(attr.db_value, db_mode) # channel, msg attr.value = val db.delete_column('players_playerattribute', 'db_mode') def backwards(self, orm): # Adding field 'PlayerAttribute.db_mode' db.add_column('players_playerattribute', 'db_mode', self.gf('django.db.models.fields.CharField')(max_length=20, null=True, blank=True), keep_default=False) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerattribute': { 'Meta': {'object_name': 'PlayerAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['players']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'PlayerDB.db_cmdset_storage' db.add_column('players_playerdb', 'db_cmdset_storage', self.gf('django.db.models.fields.TextField')(null=True), keep_default=False) def backwards(self, orm): # Deleting field 'PlayerDB.db_cmdset_storage' db.delete_column('players_playerdb', 'db_cmdset_storage') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerattribute': { 'Meta': {'object_name': 'PlayerAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['players']
Python
""" The managers for the custom Player object and permissions. """ import datetime from django.db import models from django.contrib.auth.models import User from src.typeclasses.managers import returns_typeclass_list, returns_typeclass, TypedObjectManager from src.utils import logger # # Player Manager # def returns_player_list(method): """ decorator that makes sure that a method returns a Player object instead of a User one (if you really want the User object, not the player, use the player's 'user' property) """ def func(self, *args, **kwargs): "This *always* returns a list." match = method(self, *args, **kwargs) if not match: return [] try: match = list(match) except TypeError: match = [match] players = [] for user in match: try: players.append(user.get_profile()) except Exception: # there is something wrong with get_profile. But # there is a 1-1 relation between Users-Players, so we # try to go the other way instead. from src.players.models import PlayerDB match = PlayerDB.objects.filter(user=user) if match: players.append(match[0]) else: logger.log_trace("No connection User<->Player, maybe database was partially reset?") return players return func def returns_player(method): """ Decorator: Always returns a single result or None. """ def func(self, *args, **kwargs): "decorator" rfunc = returns_player_list(method) match = rfunc(self, *args, **kwargs) if match: return match[0] else: return None return func class PlayerManager(TypedObjectManager): """ Custom manager for the player profile model. We use this to wrap users in general in evennia, and supply some useful search/statistics methods. Note how ALL these commands return character objects if possible. """ def num_total_players(self): """ Returns the total number of registered users/players. """ return self.count() @returns_typeclass_list def get_connected_players(self): """ Returns a list of player objects with currently connected users/players. """ return [player for player in self.all() if player.sessions] @returns_typeclass_list @returns_player_list def get_recently_created_players(self, days=7): """ Returns a QuerySet containing the player User accounts that have been connected within the last <days> days. """ end_date = datetime.datetime.now() tdelta = datetime.timedelta(days) start_date = end_date - tdelta return User.objects.filter(date_joined__range=(start_date, end_date)) @returns_typeclass_list @returns_player_list def get_recently_connected_players(self, days=7): """ Returns a QuerySet containing the player User accounts that have been connected within the last <days> days. """ end_date = datetime.datetime.now() tdelta = datetime.timedelta(days) start_date = end_date - tdelta return User.objects.filter(last_login__range=( start_date, end_date)).order_by('-last_login') @returns_typeclass @returns_player def get_player_from_email(self, uemail): """ Returns a player object when given an email address. """ return User.objects.filter(email__iexact=uemail) @returns_typeclass @returns_player def get_player_from_uid(self, uid): """ Returns a player object based on User id. """ return User.objects.get(id=uid) @returns_typeclass def get_player_from_name(self, uname): "Get player object based on name" players = self.filter(user__username=uname) if players: return players[0] return None # @returns_typeclass_list # def get_players_with_perm(self, permstring): # """ # Returns all players having access according to the given # permission string. # """ # return [player for player in self.all() # if player.has_perm(permstring)] # @returns_typeclass_list # def get_players_with_group(self, groupstring): # """ # Returns all players belonging to the given group. # """ # return [player.user for player in self.all() # if player.has_group(groupstring)] @returns_typeclass_list def player_search(self, ostring): """ Searches for a particular player by name or database id. ostring = a string or database id. """ ostring = ostring.lstrip("*") dbref = self.dbref(ostring) if dbref: matches = self.filter(id=dbref) if matches: return matches return self.filter(user__username__iexact=ostring) def swap_character(self, player, new_character, delete_old_character=False): """ This disconnects a player from the current character (if any) and connects to a new character object. """ if new_character.player: # the new character is already linked to a player! return False # do the swap old_character = player.character if old_character: old_character.player = None try: player.character = new_character new_character.player = player except Exception: # recover old setup old_character.player = player player.character = old_character return False if delete_old_character: old_character.delete() return True
Python
""" Player The Player class is a simple extension of the django User model using the 'profile' system of django. A profile is a model that tack new fields to the User model without actually editing the User model (which would mean hacking into django internals which we want to avoid for future compatability reasons). The profile, which we call 'Player', is accessed with user.get_profile() by the property 'player' defined on ObjectDB objects. Since we can customize it, we will try to abstract as many operations as possible to work on Player rather than on User. We use the Player to store a more mud-friendly style of permission system as well as to allow the admin more flexibility by storing attributes on the Player. Within the game we should normally use the Player manager's methods to create users, since that automatically adds the profile extension. The default Django permission system is geared towards web-use, and is defined on a per-application basis permissions. In django terms, 'src/objects' is one application, 'src/scripts' another, indeed all folders in /src with a model.py inside them is an application. Django permissions thus have the form e.g. 'applicationlabel.permissionstring' and django automatically defines a set of these for editing each application from its automatic admin interface. These are still available should you want them. For most in-game mud-use however, like commands and other things, it does not make sense to tie permissions to the applications in src/ - To the user these should all just be considered part of the game engine. So instead we define our own separate permission system here, borrowing heavily from the django original, but allowing the permission string to look however we want, making them unrelated to the applications. To make the Player model more flexible for your own game, it can also persistently store attributes of its own. This is ideal for extra account info and OOC account configuration variables etc. """ from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.utils.encoding import smart_str from django.contrib.contenttypes.models import ContentType from src.server.sessionhandler import SESSIONS from src.players import manager from src.typeclasses.models import Attribute, TypedObject, TypeNick, TypeNickHandler from src.utils import logger, utils from src.commands.cmdsethandler import CmdSetHandler from src.commands import cmdhandler AT_SEARCH_RESULT = utils.mod_import(*settings.SEARCH_AT_RESULT.rsplit('.', 1)) #------------------------------------------------------------ # # PlayerAttribute # #------------------------------------------------------------ class PlayerAttribute(Attribute): """ PlayerAttributes work the same way as Attributes on game objects, but are intended to store OOC information specific to each user and game (example would be configurations etc). """ db_obj = models.ForeignKey("PlayerDB") class Meta: "Define Django meta options" verbose_name = "Player Attribute" #------------------------------------------------------------ # # Player Nicks # #------------------------------------------------------------ class PlayerNick(TypeNick): """ The default nick types used by Evennia are: inputline (default) - match against all input player - match against player searches obj - match against object searches channel - used to store own names for channels """ db_obj = models.ForeignKey("PlayerDB", verbose_name="player") class Meta: "Define Django meta options" verbose_name = "Nickname for Players" verbose_name_plural = "Nicknames Players" unique_together = ("db_nick", "db_type", "db_obj") class PlayerNickHandler(TypeNickHandler): """ Handles nick access and setting. Accessed through ObjectDB.nicks """ NickClass = PlayerNick #------------------------------------------------------------ # # PlayerDB # #------------------------------------------------------------ class PlayerDB(TypedObject): """ This is a special model using Django's 'profile' functionality and extends the default Django User model. It is defined as such by use of the variable AUTH_PROFILE_MODULE in the settings. One accesses the fields/methods. We try use this model as much as possible rather than User, since we can customize this to our liking. The TypedObject supplies the following (inherited) properties: key - main name name - alias for key typeclass_path - the path to the decorating typeclass typeclass - auto-linked typeclass date_created - time stamp of object creation permissions - perm strings dbref - #id of object db - persistent attribute storage ndb - non-persistent attribute storage The PlayerDB adds the following properties: user - Connected User object. django field, needs to be save():d. obj - game object controlled by player character - alias for obj name - alias for user.username sessions - sessions connected to this player is_superuser - bool if this player is a superuser """ # # PlayerDB Database model setup # # inherited fields (from TypedObject): # db_key, db_typeclass_path, db_date_created, db_permissions # this is the one-to-one link between the customized Player object and # this profile model. It is required by django. user = models.ForeignKey(User, unique=True, db_index=True, help_text="The <I>User</I> object holds django-specific authentication for each Player. A unique User should be created and tied to each Player, the two should never be switched or changed around. The User will be deleted automatically when the Player is.") # the in-game object connected to this player (if any). # Use the property 'obj' to access. db_obj = models.ForeignKey("objects.ObjectDB", null=True, blank=True, verbose_name="character", help_text='In-game object.') # database storage of persistant cmdsets. db_cmdset_storage = models.CharField('cmdset', max_length=255, null=True, help_text="optional python path to a cmdset class. If creating a Character, this will default to settings.CMDSET_DEFAULT.") # Database manager objects = manager.PlayerManager() class Meta: app_label = 'players' verbose_name = 'Player' def __init__(self, *args, **kwargs): "Parent must be initiated first" TypedObject.__init__(self, *args, **kwargs) # handlers self.cmdset = CmdSetHandler(self) self.cmdset.update(init_mode=True) self.nicks = PlayerNickHandler(self) # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that allows the user to do self.attr = value, # value = self.attr and del self.attr respectively (where self # is the object in question). # obj property (wraps db_obj) #@property def obj_get(self): "Getter. Allows for value = self.obj" return self.db_obj #@obj.setter def obj_set(self, value): "Setter. Allows for self.obj = value" from src.typeclasses.typeclass import TypeClass if isinstance(value, TypeClass): value = value.dbobj try: self.db_obj = value self.save() except Exception: logger.log_trace() raise Exception("Cannot assign %s as a player object!" % value) #@obj.deleter def obj_del(self): "Deleter. Allows for del self.obj" self.db_obj = None self.save() obj = property(obj_get, obj_set, obj_del) # whereas the name 'obj' is consistent with the rest of the code, # 'character' is a more intuitive property name, so we # define this too, as an alias to player.obj. #@property def character_get(self): "Getter. Allows for value = self.character" return self.db_obj #@character.setter def character_set(self, value): "Setter. Allows for self.character = value" self.obj = value #@character.deleter def character_del(self): "Deleter. Allows for del self.character" self.db_obj = None self.save() character = property(character_get, character_set, character_del) # cmdset_storage property #@property def cmdset_storage_get(self): "Getter. Allows for value = self.name. Returns a list of cmdset_storage." if self.db_cmdset_storage: return [path.strip() for path in self.db_cmdset_storage.split(',')] return [] #@cmdset_storage.setter def cmdset_storage_set(self, value): "Setter. Allows for self.name = value. Stores as a comma-separated string." if utils.is_iter(value): value = ",".join([str(val).strip() for val in value]) self.db_cmdset_storage = value self.save() #@cmdset_storage.deleter def cmdset_storage_del(self): "Deleter. Allows for del self.name" self.db_cmdset_storage = "" self.save() cmdset_storage = property(cmdset_storage_get, cmdset_storage_set, cmdset_storage_del) class Meta: "Define Django meta options" verbose_name = "Player" verbose_name_plural = "Players" # # PlayerDB main class properties and methods # def __str__(self): return smart_str("%s(player %i)" % (self.name, self.id)) def __unicode__(self): return u"%s(player#%i)" % (self.name, self.id) # this is used by all typedobjects as a fallback try: default_typeclass_path = settings.BASE_PLAYER_TYPECLASS except Exception: default_typeclass_path = "src.players.player.Player" # this is required to properly handle attributes and typeclass loading #attribute_model_path = "src.players.models" #attribute_model_name = "PlayerAttribute" typeclass_paths = settings.PLAYER_TYPECLASS_PATHS attribute_class = PlayerAttribute # name property (wraps self.user.username) #@property def name_get(self): "Getter. Allows for value = self.name" return self.user.username #@name.setter def name_set(self, value): "Setter. Allows for player.name = newname" self.user.username = value self.user.save() # this might be stopped by Django? #@name.deleter def name_del(self): "Deleter. Allows for del self.name" raise Exception("Player name cannot be deleted!") name = property(name_get, name_set, name_del) key = property(name_get, name_set, name_del) # sessions property #@property def sessions_get(self): "Getter. Retrieve sessions related to this player/user" return SESSIONS.sessions_from_player(self) #@sessions.setter def sessions_set(self, value): "Setter. Protects the sessions property from adding things" raise Exception("Cannot set sessions manually!") #@sessions.deleter def sessions_del(self): "Deleter. Protects the sessions property from deletion" raise Exception("Cannot delete sessions manually!") sessions = property(sessions_get, sessions_set, sessions_del) #@property def is_superuser_get(self): "Superusers have all permissions." return self.user.is_superuser is_superuser = property(is_superuser_get) # # PlayerDB class access methods # def msg(self, outgoing_string, from_obj=None, data=None): """ Evennia -> User This is the main route for sending data back to the user from the server. """ if from_obj: try: from_obj.at_msg_send(outgoing_string, to_obj=self, data=data) except Exception: pass if (object.__getattribute__(self, "character") and not self.character.at_msg_receive(outgoing_string, from_obj=from_obj, data=data)): # the at_msg_receive() hook may block receiving of certain messages return outgoing_string = utils.to_str(outgoing_string, force_string=True) for session in object.__getattribute__(self, 'sessions'): session.msg(outgoing_string, data) def swap_character(self, new_character, delete_old_character=False): """ Swaps character, if possible """ return self.__class__.objects.swap_character(self, new_character, delete_old_character=delete_old_character) # # Execution/action methods # def execute_cmd(self, raw_string): """ Do something as this playe. This command transparently lets its typeclass execute the command. raw_string - raw command input coming from the command line. """ # nick replacement - we require full-word matching. raw_string = utils.to_unicode(raw_string) raw_list = raw_string.split(None) raw_list = [" ".join(raw_list[:i+1]) for i in range(len(raw_list)) if raw_list[:i+1]] for nick in PlayerNick.objects.filter(db_obj=self, db_type__in=("inputline","channel")): if nick.db_nick in raw_list: raw_string = raw_string.replace(nick.db_nick, nick.db_real, 1) break cmdhandler.cmdhandler(self.typeclass, raw_string) def search(self, ostring, global_search=False, attribute_name=None, use_nicks=False, location=None, ignore_errors=False, player=False): """ A shell method mimicking the ObjectDB equivalent, for easy inclusion from commands regardless of if the command is run by a Player or an Object. """ if self.character: # run the normal search return self.character.search(ostring, global_search=global_search, attribute_name=attribute_name, use_nicks=use_nicks, location=location, ignore_errors=ignore_errors, player=player) if player: # seach for players matches = self.__class__.objects.player_search(ostring) else: # more limited player-only search. Still returns an Object. ObjectDB = ContentType.objects.get(app_label="objects", model="objectdb").model_class() matches = ObjectDB.objects.object_search(ostring, caller=self, global_search=global_search) # deal with results matches = AT_SEARCH_RESULT(self, ostring, matches, global_search=global_search) return matches
Python
""" Typeclass for Player objects Note that this object is primarily intended to store OOC information, not game info! This object represents the actual user (not their character) and has NO actual precence in the game world (this is handled by the associated character object, so you should customize that instead for most things). """ from src.typeclasses.typeclass import TypeClass from settings import CMDSET_OOC class Player(TypeClass): """ Base typeclass for all Players. """ def basetype_setup(self): """ This sets up the basic properties for a player. Overload this with at_player_creation rather than changing this method. """ # the text encoding to use. self.db.encoding = "utf-8" # A basic security setup self.locks.add("examine:perm(Wizards)") self.locks.add("edit:perm(Wizards)") self.locks.add("delete:perm(Wizards)") self.locks.add("boot:perm(Wizards)") self.locks.add("msg:all()") # The ooc player cmdset self.cmdset.add_default(CMDSET_OOC, permanent=True) self.cmdset.outside_access = False def at_player_creation(self): """ This is called once, the very first time the player is created (i.e. first time they register with the game). It's a good place to store attributes all players should have, like configuration values etc. """ pass def at_init(self): """ This is always called whenever this object is initiated -- that is, whenever it its typeclass is cached from memory. This happens on-demand first time the object is used or activated in some way after being created but also after each server restart or reload. In the case of player objects, this usually happens the moment the player logs in or reconnects after a reload. """ pass # Note that the hooks below also exist # in the character object's typeclass. You # can often ignore these and rely on the # character ones instead, unless you # are implementing a multi-character game # and have some things that should be done # regardless of which character is currently # connected to this player. def at_cmdset_get(self): """ Called just before cmdsets on this player are requested by the command handler. If changes need to be done on the fly to the cmdset before passing them on to the cmdhandler, this is the place to do it. This is called also if the player currently have no cmdsets. """ pass def at_first_login(self): """ Only called once, the very first time the user logs in. """ pass def at_pre_login(self): """ Called every time the user logs in, before they are actually logged in. """ pass def at_post_login(self): """ Called at the end of the login process, just before letting them loose. """ pass def at_disconnect(self, reason=None): """ Called just before user is disconnected. """ pass def at_message_receive(self, message, from_obj=None): """ Called when any text is emitted to this object. If it returns False, no text will be sent automatically. """ return True def at_message_send(self, message, to_object): """ Called whenever this object tries to send text to another object. Only called if the object supplied itself as a sender in the msg() call. """ pass def at_server_reload(self): """ This hook is called whenever the server is shutting down for restart/reboot. If you want to, for example, save non-persistent properties across a restart, this is the place to do it. """ pass def at_server_shutdown(self): """ This hook is called whenever the server is shutting down fully (i.e. not for a restart). """ pass
Python
""" This module provides a set of permission lock functions for use with Evennia's permissions system. To call these locks, make sure this module is included in the settings tuple PERMISSION_FUNC_MODULES then define a lock on the form '<access_type>:func(args)' and add it to the object's lockhandler. Run the access() method of the handler to execute the lock check. Note that accessing_obj and accessed_obj can be any object type with a lock variable/field, so be careful to not expect a certain object type. Appendix: MUX locks Below is a list nicked from the MUX help file on the locks available in standard MUX. Most of these are not relevant to core Evennia since locks in Evennia are considerably more flexible and can be implemented on an individual command/typeclass basis rather than as globally available like the MUX ones. So many of these are not available in basic Evennia, but could all be implemented easily if needed for the individual game. MUX Name: Affects: Effect: ------------------------------------------------------------------------------- DefaultLock: Exits: controls who may traverse the exit to its destination. Evennia: "traverse:<lockfunc()>" Rooms: controls whether the player sees the SUCC or FAIL message for the room following the room description when looking at the room. Evennia: Custom typeclass Players/Things: controls who may GET the object. Evennia: "get:<lockfunc()" EnterLock: Players/Things: controls who may ENTER the object Evennia: GetFromLock: All but Exits: controls who may gets things from a given location. Evennia: GiveLock: Players/Things: controls who may give the object. Evennia: LeaveLock: Players/Things: controls who may LEAVE the object. Evennia: LinkLock: All but Exits: controls who may link to the location if the location is LINK_OK (for linking exits or setting drop-tos) or ABODE (for setting homes) Evennia: MailLock: Players: controls who may @mail the player. Evennia: OpenLock: All but Exits: controls who may open an exit. Evennia: PageLock: Players: controls who may page the player. Evennia: "send:<lockfunc()>" ParentLock: All: controls who may make @parent links to the object. Evennia: Typeclasses and "puppet:<lockstring()>" ReceiveLock: Players/Things: controls who may give things to the object. Evennia: SpeechLock: All but Exits: controls who may speak in that location Evennia: TeloutLock: All but Exits: controls who may teleport out of the location. Evennia: TportLock: Rooms/Things: controls who may teleport there Evennia: UseLock: All but Exits: controls who may USE the object, GIVE the object money and have the PAY attributes run, have their messages heard and possibly acted on by LISTEN and AxHEAR, and invoke $-commands stored on the object. Evennia: Commands and Cmdsets. DropLock: All but rooms: controls who may drop that object. Evennia: VisibleLock: All: Controls object visibility when the object is not dark and the looker passes the lock. In DARK locations, the object must also be set LIGHT and the viewer must pass the VisibleLock. Evennia: Room typeclass with Dark/light script """ from django.conf import settings from src.utils import search from src.utils import utils PERMISSION_HIERARCHY = [p.lower() for p in settings.PERMISSION_HIERARCHY] def _to_player(accessing_obj): "Helper function. Makes sure an accessing object is a player object" if utils.inherits_from(accessing_obj, "src.objects.objects.Object"): # an object. Convert to player. accessing_obj = accessing_obj.player return accessing_obj # lock functions def true(*args, **kwargs): "Always returns True." return True def all(*args, **kwargs): return True def false(*args, **kwargs): "Always returns False" return False def none(*args, **kwargs): return False def perm(accessing_obj, accessed_obj, *args, **kwargs): """ The basic permission-checker. Ignores case. Usage: perm(<permission>) where <permission> is the permission accessing_obj must have in order to pass the lock. If the given permission is part of PERMISSION_HIERARCHY, permission is also granted to all ranks higher up in the hierarchy. """ if not args: return False perm = args[0].lower() if hasattr(accessing_obj, 'permissions'): if perm in [p.lower() for p in accessing_obj.permissions]: # simplest case - we have a direct match return True if perm in PERMISSION_HIERARCHY: # check if we have a higher hierarchy position ppos = PERMISSION_HIERARCHY.index(perm) return any(True for hpos, hperm in enumerate(PERMISSION_HIERARCHY) if hperm in [p.lower() for p in accessing_obj.permissions] and hpos > ppos) return False def perm_above(accessing_obj, accessed_obj, *args, **kwargs): """ Only allow objects with a permission *higher* in the permission hierarchy than the one given. If there is no such higher rank, it's assumed we refer to superuser. If no hierarchy is defined, this function has no meaning and returns False. """ if args and args[0].lower() in PERMISSION_HIERARCHY: ppos = PERMISSION_HIERARCHY.index(args[0].lower()) return any(True for hpos, hperm in enumerate(PERMISSION_HIERARCHY) if hperm in [p.lower() for p in accessing_obj.permissions] and hpos > ppos) def pperm(accessing_obj, accessed_obj, *args, **kwargs): """ The basic permission-checker for Player objects. Ignores case. Usage: pperm(<permission>) where <permission> is the permission accessing_obj must have in order to pass the lock. If the given permission is part of PERMISSION_HIERARCHY, permission is also granted to all ranks higher up in the hierarchy. """ return perm(_to_player(accessing_obj), accessed_obj, *args, **kwargs) def pperm_above(accessing_obj, accessed_obj, *args, **kwargs): """ Only allow Player objects with a permission *higher* in the permission hierarchy than the one given. If there is no such higher rank, it's assumed we refer to superuser. If no hierarchy is defined, this function has no meaning and returns False. """ return perm_above(_to_player(accessing_obj), accessed_obj, *args, **kwargs) def dbref(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: dbref(3) This lock type checks if the checking object has a particular dbref. Note that this only works for checking objects that are stored in the database (e.g. not for commands) """ if not args: return False try: dbref = int(args[0].strip().strip('#')) except ValueError: return False if hasattr(accessing_obj, 'id'): return dbref == accessing_obj.id return False def pdbref(accessing_obj, accessed_obj, *args, **kwargs): """ Same as dbref, but making sure accessing_obj is a player. """ return dbref(_to_player(accessing_obj), accessed_obj, *args, **kwargs) def id(accessing_obj, accessed_obj, *args, **kwargs): "Alias to dbref" return dbref(accessing_obj, accessed_obj, *args, **kwargs) def pid(accessing_obj, accessed_obj, *args, **kwargs): "Alias to dbref, for Players" return dbref(_to_player(accessing_obj), accessed_obj, *args, **kwargs) def attr(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr(attrname) attr(attrname, value) attr(attrname, value, compare=type) where compare's type is one of (eq,gt,lt,ge,le,ne) and signifies how the value should be compared with one on accessing_obj (so compare=gt means the accessing_obj must have a value greater than the one given). Searches attributes *and* properties stored on the checking object. The first form works like a flag - if the attribute/property exists on the object, the value is checked for True/False. The second form also requires that the value of the attribute/property matches. Note that all retrieved values will be converted to strings before doing the comparison. """ # deal with arguments if not args: return False attrname = args[0].strip() value = None if len(args) > 1: value = args[1].strip() compare = 'eq' if kwargs: compare = kwargs.get('compare', 'eq') def valcompare(val1, val2, typ='eq'): "compare based on type" try: if typ == 'eq': return val1 == val2 or int(val1) == int(val2) elif typ == 'gt': return int(val1) > int(val2) elif typ == 'lt': return int(val1) < int(val2) elif typ == 'ge': return int(val1) >= int(val2) elif typ == 'le': return int(val1) <= int(val2) elif typ == 'ne': return int(val1) != int(val2) else: return False except Exception, e: #print e # this might happen if we try to compare two things that cannot be compared return False # first, look for normal properties on the object trying to gain access if hasattr(accessing_obj, attrname): if value: return valcompare(str(getattr(accessing_obj, attrname)), value, compare) return bool(getattr(accessing_obj, attrname)) # will return Fail on False value etc # check attributes, if they exist if (hasattr(accessing_obj, 'has_attribute') and accessing_obj.has_attribute(attrname)): if value: return (hasattr(accessing_obj, 'get_attribute') and valcompare(accessing_obj.get_attribute(attrname), value, compare)) return bool(accessing_obj.get_attribute(attrname)) # fails on False/None values return False def objattr(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: objattr(attrname) objattr(attrname, value) objattr(attrname, value, compare=type) Works like attr, except it looks for an attribute on accessing_obj.obj, if such an entity exists. Suitable for commands. """ if hasattr(accessing_obj, "obj"): return attr(accessing_obj.obj, accessed_obj, *args, **kwargs) def locattr(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: locattr(attrname) locattr(attrname, value) locattr(attrname, value, compare=type) Works like attr, except it looks for an attribute on accessing_obj.location, if such an entity exists. """ if hasattr(accessing_obj, "location"): return attr(accessing_obj.location, accessed_obj, *args, **kwargs) def attr_eq(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr_gt(attrname, 54) """ return attr(accessing_obj, accessed_obj, *args, **kwargs) def attr_gt(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr_gt(attrname, 54) Only true if access_obj's attribute > the value given. """ return attr(accessing_obj, accessed_obj, *args, **{'compare':'gt'}) def attr_ge(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr_gt(attrname, 54) Only true if access_obj's attribute >= the value given. """ return attr(accessing_obj, accessed_obj, *args, **{'compare':'ge'}) def attr_lt(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr_gt(attrname, 54) Only true if access_obj's attribute < the value given. """ return attr(accessing_obj, accessed_obj, *args, **{'compare':'lt'}) def attr_le(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr_gt(attrname, 54) Only true if access_obj's attribute <= the value given. """ return attr(accessing_obj, accessed_obj, *args, **{'compare':'le'}) def attr_ne(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr_gt(attrname, 54) Only true if access_obj's attribute != the value given. """ return attr(accessing_obj, accessed_obj, *args, **{'compare':'ne'}) def holds(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: holds() # checks if accessed_obj or accessed_obj.obj is held by accessing_obj holds(key/dbref) # checks if accessing_obj holds an object with given key/dbref This is passed if accessed_obj is carried by accessing_obj (that is, accessed_obj.location == accessing_obj), or if accessing_obj itself holds an object matching the given key. """ try: # commands and scripts don't have contents, so we are usually looking # for the contents of their .obj property instead (i.e. the object the # command/script is attached to). contents = accessing_obj.contents except AttributeError: try: contents = accessing_obj.obj.contents except AttributeError: return False def check_holds(objid): # helper function. Compares both dbrefs and keys/aliases. objid = str(objid) dbref = utils.dbref(objid) if dbref and any((True for obj in contents if obj.id == dbref)): return True objid = objid.lower() return any((True for obj in contents if obj.key.lower() == objid or objid in [al.lower() for al in obj.aliases])) if args and args[0]: return check_holds(args[0]) else: try: if check_holds(accessed_obj.id): #print "holds: accessed_obj.id - True" return True except Exception: pass #print "holds: accessed_obj.obj.id -", hasattr(accessed_obj, "obj") and check_holds(accessed_obj.obj.id) return hasattr(accessed_obj, "obj") and check_holds(accessed_obj.obj.id) def superuser(*args, **kwargs): """ Only accepts an accesing_obj that is superuser (e.g. user #1) Since a superuser would not ever reach this check (superusers bypass the lock entirely), any user who gets this far cannot be a superuser, hence we just return False. :) """ return False def serversetting(accessing_obj, accessed_obj, *args, **kwargs): """ Only returns true if the Evennia settings exists, alternatively has a certain value. Usage: serversetting(IRC_ENABLED) serversetting(BASE_SCRIPT_PATH, [game.gamesrc.scripts]) A given True/False or integers will be converted properly. """ if not args or not args[0]: return False if len(args) < 2: setting = args[0] val = "True" else: setting, val = args[0], args[1] # convert if val == 'True': val = True elif val == 'False': val = False elif val.isdigit(): val = int(val) if setting in settings._wrapped.__dict__: return settings._wrapped.__dict__[setting] == val return False
Python
# -*- coding: utf-8 -*- """ This is part of Evennia's unittest framework, for testing the stability and integrrity of the codebase during updates. This module tests the lock functionality of Evennia. """ try: # this is a special optimized Django version, only available in current Django devel from django.utils.unittest import TestCase except ImportError: from django.test import TestCase from django.conf import settings from src.locks import lockhandler, lockfuncs from src.utils import create #------------------------------------------------------------ # # Lock testing # #------------------------------------------------------------ class LockTest(TestCase): "Defines the lock test base" def setUp(self): "sets up the testing environment" self.obj1 = create.create_object(settings.BASE_OBJECT_TYPECLASS, key="obj1") self.obj2 = create.create_object(settings.BASE_OBJECT_TYPECLASS, key="obj2") class TestLockCheck(LockTest): def testrun(self): dbref = self.obj2.dbref self.obj1.locks.add("owner:dbref(%s);edit:dbref(%s) or perm(Wizards);examine:perm(Builders) and id(%s);delete:perm(Wizards);get:all()" % (dbref, dbref, dbref)) self.obj2.permissions = ['Wizards'] self.assertEquals(True, self.obj1.locks.check(self.obj2, 'owner')) self.assertEquals(True, self.obj1.locks.check(self.obj2, 'edit')) self.assertEquals(True, self.obj1.locks.check(self.obj2, 'examine')) self.assertEquals(True, self.obj1.locks.check(self.obj2, 'delete')) self.assertEquals(True, self.obj1.locks.check(self.obj2, 'get')) self.obj1.locks.add("get:false()") self.assertEquals(False, self.obj1.locks.check(self.obj2, 'get')) self.assertEquals(True, self.obj1.locks.check(self.obj2, 'not_exist', default=True)) class TestLockfuncs(LockTest): def testrun(self): self.obj2.permissions = ['Wizards'] self.assertEquals(True, lockfuncs.true(self.obj2, self.obj1)) self.assertEquals(False, lockfuncs.false(self.obj2, self.obj1)) self.assertEquals(True, lockfuncs.perm(self.obj2, self.obj1, 'Wizards')) self.assertEquals(True, lockfuncs.perm_above(self.obj2, self.obj1, 'Builders')) dbref = self.obj2.dbref self.assertEquals(True, lockfuncs.dbref(self.obj2, self.obj1, '%s' % dbref)) self.obj2.db.testattr = 45 self.assertEquals(True, lockfuncs.attr(self.obj2, self.obj1, 'testattr', '45')) self.assertEquals(False, lockfuncs.attr_gt(self.obj2, self.obj1, 'testattr', '45')) self.assertEquals(True, lockfuncs.attr_ge(self.obj2, self.obj1, 'testattr', '45')) self.assertEquals(False, lockfuncs.attr_lt(self.obj2, self.obj1, 'testattr', '45')) self.assertEquals(True, lockfuncs.attr_le(self.obj2, self.obj1, 'testattr', '45')) self.assertEquals(False, lockfuncs.attr_ne(self.obj2, self.obj1, 'testattr', '45'))
Python
""" Locks A lock defines access to a particular subsystem or property of Evennia. For example, the "owner" property can be impmemented as a lock. Or the disability to lift an object or to ban users. A lock consists of two three parts: - access_type - this defines what kind of access this lock regulates. This just a string. - function call - this is one or many calls to functions that will determine if the lock is passed or not. - lock function(s). These are regular python functions with a special set of allowed arguments. They should always return a boolean depending on if they allow access or not. # Lock function A lock function is defined by existing in one of the modules listed by settings.LOCK_FUNC_MODULES. It should also always take four arguments looking like this: funcname(accessing_obj, accessed_obj, *args, **kwargs): [...] The accessing object is the object wanting to gain access. The accessed object is the object this lock resides on args and kwargs will hold optional arguments and/or keyword arguments to the function as a list and a dictionary respectively. Example: perm(accessing_obj, accessed_obj, *args, **kwargs): "Checking if the object has a particular, desired permission" if args: desired_perm = args[0] return desired_perm in accessing_obj.permissions return False Lock functions should most often be pretty general and ideally possible to re-use and combine in various ways to build clever locks. # Lock definition A lock definition is a string with a special syntax. It is added to each object's lockhandler, making that lock available from then on. The lock definition looks like this: 'access_type:[NOT] func1(args)[ AND|OR][NOT] func2() ...' That is, the access_type, a colon followed by calls to lock functions combined with AND or OR. NOT negates the result of the following call. Example: We want to limit who may edit a particular object (let's call this access_type for 'edit', it depends on what the command is looking for). We want this to only work for those with the Permission 'Builders'. So we use our lock function above and call it like this: 'edit:perm(Builders)' Here, the lock-function perm() will be called (accessing_obj and accessed_obj are added automatically, you only need to add the args/kwargs, if any). If we wanted to make sure the accessing object was BOTH a Builders and a GoodGuy, we could use AND: 'edit:perm(Builders) AND perm(GoodGuy)' To allow EITHER Builders and GoodGuys, we replace AND with OR. perm() is just one example, the lock function can do anything and compare any properties of the calling object to decide if the lock is passed or not. 'lift:attrib(very_strong) AND NOT attrib(bad_back)' To make these work, add the string to the lockhandler of the object you want to apply the lock to: obj.lockhandler.add('edit:perm(Builders)') From then on, a command that wants to check for 'edit' access on this object would do something like this: if not target_obj.lockhandler.has_perm(caller, 'edit'): caller.msg("Sorry you cannot edit that.") # Permissions Permissions are just text strings stored in a comma-separated list on typeclassed objects. The default perm() lock function uses them, taking into account settings.PERMISSION_HIERARCHY. Also, the restricted @perm command sets them, but otherwise they are identical to any other identifier you can use. """ import re, inspect from django.conf import settings from src.utils import logger, utils # # Exception class # class LockException(Exception): pass # # Cached lock functions # LOCKFUNCS = {} def cache_lockfuncs(): "Updates the cache." global LOCKFUNCS LOCKFUNCS = {} for modulepath in settings.LOCK_FUNC_MODULES: modulepath = utils.pypath_to_realpath(modulepath) mod = utils.mod_import(modulepath) if mod: for tup in (tup for tup in inspect.getmembers(mod) if callable(tup[1])): LOCKFUNCS[tup[0]] = tup[1] else: logger.log_errmsg("Couldn't load %s from PERMISSION_FUNC_MODULES." % modulepath) # # pre-compiled regular expressions # RE_FUNCS = re.compile(r"\w+\([^)]*\)") RE_SEPS = re.compile(r"(?<=[ )])AND(?=\s)|(?<=[ )])OR(?=\s)|(?<=[ )])NOT(?=\s)") RE_OK = re.compile(r"%s|and|or|not") # # # Lock handler # # class LockHandler(object): """ This handler should be attached to all objects implementing permission checks, under the property 'lockhandler'. """ def __init__(self, obj): """ Loads and pre-caches all relevant locks and their functions. """ if not LOCKFUNCS: cache_lockfuncs() self.obj = obj self.locks = {} self.log_obj = None self.no_errors = True self.reset_flag = False self._cache_locks(self.obj.lock_storage) def __str__(self): return ";".join(self.locks[key][2] for key in sorted(self.locks)) def _log_error(self, message): "Try to log errors back to object" if self.log_obj and hasattr(self.log_obj, 'msg'): self.log_obj.msg(message) elif hasattr(self.obj, 'msg'): self.obj.msg(message) else: logger.log_errmsg("%s: %s" % (self.obj, message)) def _parse_lockstring(self, storage_lockstring): """ Helper function. locks are stored as a string 'atype:[NOT] lock()[[ AND|OR [NOT] lock() [...]];atype... """ locks = {} if not storage_lockstring: return locks nlocks = storage_lockstring.count(';') + 1 duplicates = 0 elist = [] # errors wlist = [] # warnings for raw_lockstring in storage_lockstring.split(';'): lock_funcs = [] try: access_type, rhs = (part.strip() for part in raw_lockstring.split(':', 1)) except ValueError: logger.log_trace() return locks # parse the lock functions and separators funclist = RE_FUNCS.findall(rhs) evalstring = rhs.replace('AND','and').replace('OR','or').replace('NOT','not') nfuncs = len(funclist) for funcstring in funclist: funcname, rest = [part.strip().strip(')') for part in funcstring.split('(', 1)] func = LOCKFUNCS.get(funcname, None) if not callable(func): elist.append("Lock: function '%s' is not available." % funcstring) continue args = [arg.strip() for arg in rest.split(',') if not '=' in arg] kwargs = dict([arg.split('=', 1) for arg in rest.split(',') if '=' in arg]) lock_funcs.append((func, args, kwargs)) evalstring = evalstring.replace(funcstring, '%s') if len(lock_funcs) < nfuncs: continue try: # purge the eval string of any superfluos items, then test it evalstring = " ".join(RE_OK.findall(evalstring)) eval(evalstring % tuple(True for func in funclist)) except Exception: elist.append("Lock: definition '%s' has syntax errors." % raw_lockstring) continue if access_type in locks: duplicates += 1 wlist.append("Lock: access type '%s' changed from '%s' to '%s' " % \ (access_type, locks[access_type][2], raw_lockstring)) locks[access_type] = (evalstring, tuple(lock_funcs), raw_lockstring) if wlist and self.log_obj: # not an error, so only report if log_obj is available. self._log_error("\n".join(wlist)) if elist: raise LockException("\n".join(elist)) self.no_errors = False return locks def _cache_locks(self, storage_lockstring): """Store data""" self.locks = self._parse_lockstring(storage_lockstring) def _save_locks(self): "Store locks to obj" self.obj.lock_storage = ";".join([tup[2] for tup in self.locks.values()]) def add(self, lockstring, log_obj=None): """ Add a new lockstring on the form '<access_type>:<functions>'. Multiple access types should be separated by semicolon (;). If log_obj is given, it will be fed error information. """ if log_obj: self.log_obj = log_obj self.no_errors = True # sanity checks for lockdef in lockstring.split(';'): if not ':' in lockstring: self._log_error("Lock: '%s' contains no colon (:)." % lockdef) return False access_type, rhs = [part.strip() for part in lockdef.split(':', 1)] if not access_type: self._log_error("Lock: '%s' has no access_type (left-side of colon is empty)." % lockdef) return False if rhs.count('(') != rhs.count(')'): self._log_error("Lock: '%s' has mismatched parentheses." % lockdef) return False if not RE_FUNCS.findall(rhs): self._log_error("Lock: '%s' has no valid lock functions." % lockdef) return False # get the lock string storage_lockstring = self.obj.lock_storage if storage_lockstring: storage_lockstring = storage_lockstring + ";" + lockstring else: storage_lockstring = lockstring # cache the locks will get rid of eventual doublets self._cache_locks(storage_lockstring) self._save_locks() self.log_obj = None return self.no_errors def get(self, access_type): "get the lockstring of a particular type" return self.locks.get(access_type, None) def delete(self, access_type): "Remove a lock from the handler" if access_type in self.locks: del self.locks[access_type] self._save_locks() return True return False def clear(self): "Remove all locks" self.locks = {} self.lock_storage = "" def reset(self): """ Set the reset flag, so the the lock will be re-cached at next checking. This is usually set by @reload. """ self.reset_flag = True def check(self, accessing_obj, access_type, default=False, no_superuser_bypass=False): """ Checks a lock of the correct type by passing execution off to the lock function(s). accessing_obj - the object seeking access access_type - the type of access wanted default - if no suitable lock type is found, use this no_superuser_bypass - don't use this unless you really, really need to """ if self.reset_flag: # rebuild cache self._cache_locks(self.obj.lock_storage) self.reset_flag = False if (not no_superuser_bypass and ((hasattr(accessing_obj, 'is_superuser') and accessing_obj.is_superuser) or (hasattr(accessing_obj, 'player') and hasattr(accessing_obj.player, 'is_superuser') and accessing_obj.player.is_superuser) or (hasattr(accessing_obj, 'get_player') and (accessing_obj.get_player()==None or accessing_obj.get_player().is_superuser)))): # we grant access to superusers and also to protocol instances that not yet has any player assigned to them (the # latter is a safety feature since superuser cannot be authenticated at some point during the connection). return True if access_type in self.locks: # we have a lock, test it. evalstring, func_tup, raw_string = self.locks[access_type] # we have previously stored the function object and all the args/kwargs as list/dict, # now we just execute them all in sequence. The result will be a list of True/False # statements. Note that there is no eval here, these are normal command calls! true_false = (bool(tup[0](accessing_obj, self.obj, *tup[1], **tup[2])) for tup in func_tup) # we now input these True/False list into the evalstring, which combines them with # AND/OR/NOT in order to get the final result #true_false = tuple(true_false) #print accessing_obj, self.obj, access_type, true_false, evalstring, func_tup, raw_string return eval(evalstring % tuple(true_false)) else: return default def check_lockstring(self, accessing_obj, lockstring): """ Do a direct check against a lockstring ('atype:func()..'), without any intermediary storage on the accessed object (this can be left to None if the lock functions called don't access it). atype can also be put to a dummy value since no lock selection is made. """ if ((hasattr(accessing_obj, 'is_superuser') and accessing_obj.is_superuser) or (hasattr(accessing_obj, 'player') and hasattr(accessing_obj.player, 'is_superuser') and accessing_obj.player.is_superuser) or (hasattr(accessing_obj, 'get_player') and (accessing_obj.get_player()==None or accessing_obj.get_player().is_superuser))): return True locks = self. _parse_lockstring(lockstring) for access_type in locks: evalstring, func_tup, raw_string = locks[access_type] true_false = (tup[0](accessing_obj, self.obj, *tup[1], **tup[2]) for tup in func_tup) return eval(evalstring % tuple(true_false)) def test(): # testing class TestObj(object): pass import pdb obj1 = TestObj() obj2 = TestObj() #obj1.lock_storage = "owner:dbref(#4);edit:dbref(#5) or perm(Wizards);examine:perm(Builders);delete:perm(Wizards);get:all()" #obj1.lock_storage = "cmd:all();admin:id(1);listen:all();send:all()" obj1.lock_storage = "listen:perm(Immortals)" pdb.set_trace() obj1.locks = LockHandler(obj1) obj2.permissions = ["Immortals"] obj2.id = 4 #obj1.locks.add("edit:attr(test)") print "comparing obj2.permissions (%s) vs obj1.locks (%s)" % (obj2.permissions, obj1.locks) print obj1.locks.check(obj2, 'owner') print obj1.locks.check(obj2, 'edit') print obj1.locks.check(obj2, 'examine') print obj1.locks.check(obj2, 'delete') print obj1.locks.check(obj2, 'get') print obj1.locks.check(obj2, 'listen')
Python
""" A typeclass is the companion of a TypedObject django model. It 'decorates' the model without actually having to add new fields to the model - transparently storing data onto its associated model without the admin/user just having to deal with a 'normal' Python class. The only restrictions is that the typeclass must inherit from TypeClass and not reimplement the get/setters defined below. There are also a few properties that are protected, so as to not overwrite property names used by the typesystem or django itself. """ from src.utils import logger from django.conf import settings # these are called so many times it's worth to avoid lookup calls GA = object.__getattribute__ SA = object.__setattr__ DA = object.__delattr__ # To ensure the sanity of the model, there are a # few property names we won't allow the admin to # set on the typeclass just like that. Note that these are *not* related # to *in-game* safety (if you can edit typeclasses you have # full access anyway), so no protection against changing # e.g. 'locks' or 'permissions' should go here. PROTECTED = ('id', 'dbobj', 'db', 'ndb', 'objects', 'typeclass', 'attr', 'save', 'delete') # If this is true, all non-protected property assignments # are directly stored to a database attribute class MetaTypeClass(type): """ This metaclass just makes sure the class object gets printed in a nicer way (it might end up having no name at all otherwise due to the magics being done with get/setattribute). """ def __init__(mcs, *args, **kwargs): """ Adds some features to typeclassed objects """ super(MetaTypeClass, mcs).__init__(*args, **kwargs) mcs.typename = mcs.__name__ mcs.path = "%s.%s" % (mcs.__module__, mcs.__name__) def __str__(cls): return "%s" % cls.__name__ class TypeClass(object): """ This class implements a 'typeclass' object. This is connected to a database object inheriting from TypedObject. the TypeClass allows for all customization. Most of the time this means that the admin never has to worry about database access but only deal with extending TypeClasses to create diverse objects in the game. The ObjectType class has all functionality for wrapping a database object transparently. It's up to its child classes to implement eventual custom hooks and other functions called by the engine. """ __metaclass__ = MetaTypeClass def __init__(self, dbobj): """ Initialize the object class. There are two ways to call this class. o = object_class(dbobj) : this is used to initialize dbobj with the class name o = dbobj.object_class(dbobj) : this is used when dbobj.object_class is already set. """ # typecheck of dbobj - we can't allow it to be added here # unless it's really a TypedObject. dbobj_cls = GA(dbobj, '__class__') dbobj_mro = GA(dbobj_cls, '__mro__') if not any('src.typeclasses.models.TypedObject' in str(mro) for mro in dbobj_mro): raise Exception("dbobj is not a TypedObject: %s: %s" % \ (dbobj_cls, dbobj_mro)) # store the needed things on the typeclass SA(self, 'dbobj', dbobj) # # sync the database object to this typeclass. # cls = GA(self, '__class__') # db_typeclass_path = "%s.%s" % (GA(cls, '__module__'), # GA(cls, '__name__')) # if not GA(dbobj, "db_typeclass_path") == db_typeclass_path: # SA(dbobj, "db_typeclass_path", db_typeclass_path) # GA(dbobj, "save")() def __getattribute__(self, propname): """ Change the normal property access to transparently include the properties on self.dbobj. Note that dbobj properties have priority, so if you define a same-named property on the class, it will NOT be accessible through getattr. """ try: dbobj = GA(self, 'dbobj') except AttributeError: dbobj = None logger.log_trace("This is probably due to an unsafe reload.") raise if propname == 'dbobj': return dbobj if propname.startswith('__') and propname.endswith('__'): # python specials are parsed as-is (otherwise things like # isinstance() fail to identify the typeclass) return GA(self, propname) #print "get %s (dbobj:%s)" % (propname, type(dbobj)) try: return GA(self, propname) except AttributeError: try: return GA(dbobj, propname) except AttributeError: try: if propname == 'ndb': # get non-persistent data return getattr(GA(dbobj, 'ndb'), propname) else: return dbobj.get_attribute_raise(propname) except AttributeError: string = "Object: '%s' not found on %s(%s), nor on its typeclass %s." raise AttributeError(string % (propname, dbobj, dbobj.dbref, dbobj.typeclass_path,)) def __setattr__(self, propname, value): """ Transparently save data to the dbobj object in all situations. Note that this does not necessarily mean storing it to the database unless data is stored into a propname corresponding to a field on ObjectDB model. """ #print "set %s -> %s" % (propname, value) if propname in PROTECTED: string = "%s: '%s' is a protected attribute name." string += " (protected: [%s])" % (", ".join(PROTECTED)) logger.log_errmsg(string % (self.name, propname)) return try: dbobj = GA(self, 'dbobj') except AttributeError: dbobj = None logger.log_trace("This is probably due to an unsafe reload.") if dbobj: try: # only set value on propname if propname already exists # on dbobj. __getattribute__ will raise attribute error otherwise. GA(dbobj, propname) SA(dbobj, propname, value) except AttributeError: dbobj.set_attribute(propname, value) else: SA(self, propname, value) def __eq__(self, other): """ dbobj-recognized comparison """ try: return other == self or other == GA(self, dbobj) or other == GA(self, dbobj).user except AttributeError: # if self.dbobj.user fails it means the two previous comparisons failed already return False def __delattr__(self, propname): """ Transparently deletes data from the typeclass or dbobj by first searching on the typeclass, secondly on the dbobj.db. Will not allow deletion of properties stored directly on dbobj. """ if propname in PROTECTED: string = "%s: '%s' is a protected attribute name." string += " (protected: [%s])" % (", ".join(PROTECTED)) logger.log_errmsg(string % (self.name, propname)) return try: DA(self, propname) except AttributeError: # not on typeclass, try to delete on db/ndb try: dbobj = GA(self, 'dbobj') except AttributeError: logger.log_trace("This is probably due to an unsafe reload.") return # ignore delete try: dbobj.del_attribute_raise(propname) except AttributeError: string = "Object: '%s' not found on %s(%s), nor on its typeclass %s." raise AttributeError(string % (propname, dbobj, dbobj.dbref, dbobj.typeclass_path,)) def __str__(self): "represent the object" return self.key
Python
""" This is the *abstract* django models for many of the database objects in Evennia. A django abstract (obs, not the same as a Python metaclass!) is a model which is not actually created in the database, but which only exists for other models to inherit from, to avoid code duplication. Any model can import and inherit from these classes. Attributes are database objects stored on other objects. The implementing class needs to supply a ForeignKey field attr_object pointing to the kind of object being mapped. TypedObjects are objects 'decorated' with a typeclass - that is, the typeclass (which is a normal Python class implementing some special tricks with its get/set attribute methods, allows for the creation of all sorts of different objects all with the same database object underneath. Usually attributes are used to permanently store things not hard-coded as field on the database object. The admin should usually not have to deal directly with the database object layer. This module also contains the Managers for the respective models; inherit from these to create custom managers. """ import sys try: import cPickle as pickle except ImportError: import pickle import traceback from django.db import models from django.conf import settings from django.utils.encoding import smart_str from django.contrib.contenttypes.models import ContentType from src.utils.idmapper.models import SharedMemoryModel from src.server.models import ServerConfig from src.typeclasses import managers from src.locks.lockhandler import LockHandler from src.utils import logger, utils from src.utils.utils import is_iter, has_parent PERMISSION_HIERARCHY = [p.lower() for p in settings.PERMISSION_HIERARCHY] CTYPEGET = ContentType.objects.get GA = object.__getattribute__ SA = object.__setattr__ DA = object.__delattr__ # used by Attribute to efficiently identify stored object types. # Note that these have to be updated if directory structure changes. PARENTS = { "typeclass":"src.typeclasses.typeclass.TypeClass", "objectdb":"src.objects.models.ObjectDB", "playerdb":"src.players.models.PlayerDB", "scriptdb":"src.scripts.models.ScriptDB", "msg":"src.comms.models.Msg", "channel":"src.comms.models.Channel", "helpentry":"src.help.models.HelpEntry"} #------------------------------------------------------------ # # Attributes # #------------------------------------------------------------ class PackedDBobject(object): """ Attribute helper class. A container for storing and easily identifying database objects in the database (which doesn't suppport storing db_objects directly). """ def __init__(self, ID, db_model): self.id = ID self.db_model = db_model class PackedDict(dict): """ Attribute helper class. A variant of dict that stores itself to the database when updating one of its keys. This is called and handled by Attribute.validate_data(). """ def __init__(self, db_obj, *args, **kwargs): """ Sets up the packing dict. The db_store variable is set by Attribute.validate_data() when returned in order to allow custom updates to the dict. db_obj - the Attribute object storing this dict. """ self.db_obj = db_obj self.db_store = False super(PackedDict, self).__init__(*args, **kwargs) def db_save(self): "save data to Attribute, if db_store is active" if self.db_store: self.db_obj.value = self def __setitem__(self, *args, **kwargs): "Custom setitem that stores changed dict to database." super(PackedDict, self).__setitem__(*args, **kwargs) self.db_save() def __getitem__(self, *args, **kwargs): return super(PackedDict, self).__getitem__(*args, **kwargs) def clear(self, *args, **kwargs): "Custom clear" super(PackedDict, self).clear(*args, **kwargs) self.db_save() def pop(self, *args, **kwargs): "Custom pop" super(PackedDict, self).pop(*args, **kwargs) self.db_save() def popitem(self, *args, **kwargs): "Custom popitem" super(PackedDict, self).popitem(*args, **kwargs) self.db_save() def update(self, *args, **kwargs): "Custom update" super(PackedDict, self).update(*args, **kwargs) self.db_save() class PackedList(list): """ Attribute helper class. A variant of list that stores itself to the database when updating one of its keys. This is called and handled by Attribute.validate_data(). """ def __init__(self, db_obj, *args, **kwargs): """ Sets up the packing list. The db_store variable is set by Attribute.validate_data() when returned in order to allow custom updates to the list. db_obj - the Attribute object storing this dict. """ self.db_obj = db_obj self.db_store = False super(PackedList, self).__init__(*args, **kwargs) def db_save(self): "save data to Attribute, if db_store is active" if self.db_store: self.db_obj.value = self def __setitem__(self, *args, **kwargs): "Custom setitem that stores changed dict to database." super(PackedList, self).__setitem__(*args, **kwargs) self.db_save() def append(self, *args, **kwargs): "Custom append" super(PackedList, self).append(*args, **kwargs) self.db_save() def extend(self, *args, **kwargs): "Custom extend" super(PackedList, self).extend(*args, **kwargs) self.db_save() def insert(self, *args, **kwargs): "Custom insert" super(PackedList, self).insert(*args, **kwargs) self.db_save() def remove(self, *args, **kwargs): "Custom remove" super(PackedList, self).remove(*args, **kwargs) self.db_save() def pop(self, *args, **kwargs): "Custom pop" super(PackedList, self).pop(*args, **kwargs) self.db_save() def reverse(self, *args, **kwargs): "Custom reverse" super(PackedList, self).reverse(*args, **kwargs) self.db_save() def sort(self, *args, **kwargs): "Custom sort" super(PackedList, self).sort(*args, **kwargs) self.db_save() class Attribute(SharedMemoryModel): """ Abstract django model. Attributes are things that are specific to different types of objects. For example, a drink container needs to store its fill level, whereas an exit needs to store its open/closed/locked/unlocked state. These are done via attributes, rather than making different classes for each object type and storing them directly. The added benefit is that we can add/remove attributes on the fly as we like. The Attribute class defines the following properties: key - primary identifier mode - which type of data is stored in attribute permissions - perm strings obj - which object the attribute is defined on date_created - when the attribute was created value - the data stored in the attribute """ # # Attribute Database Model setup # # # These databse fields are all set using their corresponding properties, # named same as the field, but withtout the db_* prefix. db_key = models.CharField('key', max_length=255, db_index=True) # access through the value property db_value = models.TextField('value', blank=True, null=True) # Lock storage db_lock_storage = models.CharField('locks', max_length=512, blank=True) # references the object the attribute is linked to (this is set # by each child class to this abstact class) db_obj = None # models.ForeignKey("RefencedObject") # time stamp db_date_created = models.DateTimeField('date_created',editable=False, auto_now_add=True) # Database manager objects = managers.AttributeManager() # Lock handler self.locks def __init__(self, *args, **kwargs): "Initializes the parent first -important!" SharedMemoryModel.__init__(self, *args, **kwargs) self.locks = LockHandler(self) self.value_cache = None class Meta: "Define Django meta options" abstract = True verbose_name = "Evennia Attribute" # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that allows the user to do self.attr = value, # value = self.attr and del self.attr respectively (where self # is the object in question). # key property (wraps db_key) #@property def key_get(self): "Getter. Allows for value = self.key" return self.db_key #@key.setter def key_set(self, value): "Setter. Allows for self.key = value" self.db_key = value self.save() #@key.deleter def key_del(self): "Deleter. Allows for del self.key" raise Exception("Cannot delete attribute key!") key = property(key_get, key_set, key_del) # obj property (wraps db_obj) #@property def obj_get(self): "Getter. Allows for value = self.obj" return self.db_obj #@obj.setter def obj_set(self, value): "Setter. Allows for self.obj = value" self.db_obj = value self.save() #@obj.deleter def obj_del(self): "Deleter. Allows for del self.obj" self.db_obj = None self.save() obj = property(obj_get, obj_set, obj_del) # date_created property (wraps db_date_created) #@property def date_created_get(self): "Getter. Allows for value = self.date_created" return self.db_date_created #@date_created.setter def date_created_set(self, value): "Setter. Allows for self.date_created = value" raise Exception("Cannot edit date_created!") #@date_created.deleter def date_created_del(self): "Deleter. Allows for del self.date_created" raise Exception("Cannot delete date_created!") date_created = property(date_created_get, date_created_set, date_created_del) # value property (wraps db_value) #@property def value_get(self): """ Getter. Allows for value = self.value. """ try: return utils.to_unicode(self.validate_data(pickle.loads(utils.to_str(self.db_value)))) except pickle.UnpicklingError: return self.db_value #@value.setter def value_set(self, new_value): "Setter. Allows for self.value = value" self.db_value = utils.to_unicode(pickle.dumps(utils.to_str(self.validate_data(new_value, setmode=True)))) #self.db_value = utils.to_unicode(pickle.dumps(utils.to_str(self.validate_data(new_value)))) self.save() #@value.deleter def value_del(self): "Deleter. Allows for del attr.value. This removes the entire attribute." self.delete() value = property(value_get, value_set, value_del) # lock_storage property (wraps db_lock_storage) #@property def lock_storage_get(self): "Getter. Allows for value = self.lock_storage" return self.db_lock_storage #@lock_storage.setter def lock_storage_set(self, value): """Saves the lock_storage. This is usually not called directly, but through self.lock()""" self.db_lock_storage = value self.save() #@lock_storage.deleter def lock_storage_del(self): "Deleter is disabled. Use the lockhandler.delete (self.lock.delete) instead""" logger.log_errmsg("Lock_Storage (on %s) cannot be deleted. Use obj.lock.delete() instead." % self) lock_storage = property(lock_storage_get, lock_storage_set, lock_storage_del) # # # Attribute methods # # def __str__(self): return smart_str("%s(%s)" % (self.key, self.id)) def __unicode__(self): return u"%s(%s)" % (self.key, self.id) def validate_data(self, item, niter=0, setmode=False): """ We have to make sure to not store database objects raw, since this will crash the system. Instead we must store their IDs and make sure to convert back when the attribute is read back later. Due to this it's criticial that we check all iterables recursively, converting all found database objects to a form the database can handle. We handle lists, tuples and dicts (and any nested combination of them) this way, all other iterables are stored and returned as lists. setmode - used for iterables; when first assigning, this settings makes sure that it's a normal built-in python object that is stored in the db, not the custom one. This will then just be updated later, assuring the pickling works as it should. niter - iteration counter for recursive iterable search. """ if isinstance(item, basestring): # a string is unmodified ret = item elif type(item) == PackedDBobject: # unpack a previously packed db_object try: #print "unpack:", item.id, item.db_model mclass = CTYPEGET(model=item.db_model).model_class() try: ret = mclass.objects.dbref_search(item.id) except AttributeError: ret = mclass.objects.get(id=item.id) except Exception: logger.log_trace("Attribute error: %s, %s" % (item.db_model, item.id)) #TODO: Remove when stable? ret = None elif type(item) == tuple: # handle tuples ret = [] for it in item: ret.append(self.validate_data(it)) ret = tuple(ret) elif type(item) == dict or type(item) == PackedDict: # handle dictionaries if setmode: ret = {} for key, it in item.items(): ret[key] = self.validate_data(it, niter=niter+1, setmode=True) else: ret = PackedDict(self) for key, it in item.items(): ret[key] = self.validate_data(it, niter=niter+1) if niter == 0: ret.db_store = True elif is_iter(item): # Note: ALL other iterables except dicts and tuples are stored&retrieved as lists! if setmode: ret = [] for it in item: ret.append(self.validate_data(it, niter=niter+1,setmode=True)) else: ret = PackedList(self) for it in item: ret.append(self.validate_data(it, niter=niter+1)) if niter == 0: ret.db_store = True elif has_parent('django.db.models.base.Model', item) or has_parent(PARENTS['typeclass'], item): # db models must be stored as dbrefs db_model = [parent for parent, path in PARENTS.items() if has_parent(path, item)] #print "db_model", db_model if db_model and db_model[0] == 'typeclass': # the typeclass alone can't help us, we have to know the db object. db_model = [parent for parent, path in PARENTS.items() if has_parent(path, item.dbobj)] #print "db_model2", db_model if db_model: # store the object in an easily identifiable container ret = PackedDBobject(str(item.id), db_model[0]) else: # not a valid object - some third-party class or primitive? ret = item else: ret = item return ret def access(self, accessing_obj, access_type='read', default=False): """ Determines if another object has permission to access. accessing_obj - object trying to access this one access_type - type of access sought default - what to return if no lock of access_type was found """ return self.locks.check(accessing_obj, access_type=access_type, default=default) #------------------------------------------------------------ # # Nicks # #------------------------------------------------------------ class TypeNick(SharedMemoryModel): """ This model holds whichever alternate names this object has for OTHER objects, but also for arbitrary strings, channels, players etc. Setting a nick does not affect the nicknamed object at all (as opposed to Aliases above), and only this object will be able to refer to the nicknamed object by the given nick. The default nick types used by Evennia are: inputline (default) - match against all input player - match against player searches obj - match against object searches channel - used to store own names for channels """ db_nick = models.CharField('nickname',max_length=255, db_index=True, help_text='the alias') db_real = models.TextField('realname', help_text='the original string to match and replace.') db_type = models.CharField('nick type',default="inputline", max_length=16, null=True, blank=True, help_text="the nick type describes when the engine tries to do nick-replacement. Common options are 'inputline','player','obj' and 'channel'. Inputline checks everything being inserted, whereas the other cases tries to replace in various searches or when posting to channels.") db_obj = None #models.ForeignKey("ObjectDB") class Meta: "Define Django meta options" abstract = True verbose_name = "Nickname" unique_together = ("db_nick", "db_type", "db_obj") class TypeNickHandler(object): """ Handles nick access and setting. Accessed through ObjectDB.nicks """ NickClass = TypeNick def __init__(self, obj): "Setup" self.obj = obj def add(self, nick, realname, nick_type="inputline"): "We want to assign a new nick" if not nick or not nick.strip(): return nick = nick.strip() real = realname.strip() query = self.NickClass.objects.filter(db_obj=self.obj, db_nick__iexact=nick, db_type__iexact=nick_type) if query.count(): old_nick = query[0] old_nick.db_real = real old_nick.save() else: new_nick = self.NickClass(db_nick=nick, db_real=real, db_type=nick_type, db_obj=self.obj) new_nick.save() def delete(self, nick, nick_type="inputline"): "Removes a nick" nick = nick.strip() query = self.NickClass.objects.filter(db_obj=self.obj, db_nick__iexact=nick, db_type__iexact=nick_type) if query.count(): # remove the found nick(s) query.delete() def get(self, nick=None, nick_type="inputline"): if nick: query = self.NickClass.objects.filter(db_obj=self.obj, db_nick__iexact=nick, db_type__iexact=nick_type) query = query.values_list("db_real", flat=True) if query.count(): return query[0] else: return nick else: return self.NickClass.objects.filter(db_obj=self.obj) def has(self, nick, nick_type="inputline"): "Returns true/false if this nick is defined or not" return self.NickClass.objects.filter(db_obj=self.obj, db_nick__iexact=nick, db_type__iexact=nick_type).count() #------------------------------------------------------------ # # Typed Objects # #------------------------------------------------------------ class TypedObject(SharedMemoryModel): """ Abstract Django model. This is the basis for a typed object. It also contains all the mechanics for managing connected attributes. The TypedObject has the following properties: key - main name name - alias for key typeclass_path - the path to the decorating typeclass typeclass - auto-linked typeclass date_created - time stamp of object creation permissions - perm strings dbref - #id of object db - persistent attribute storage ndb - non-persistent attribute storage """ # # TypedObject Database Model setup # # # These databse fields are all set using their corresponding properties, # named same as the field, but withtou the db_* prefix. # Main identifier of the object, for searching. Can also # be referenced as 'name'. db_key = models.CharField('key', max_length=255, db_index=True) # This is the python path to the type class this object is tied to # (the type class is what defines what kind of Object this is) db_typeclass_path = models.CharField('typeclass', max_length=255, null=True, help_text="this defines what 'type' of entity this is. This variable holds a Python path to a module with a valid Evennia Typeclass.") # Creation date db_date_created = models.DateTimeField('creation date', editable=False, auto_now_add=True) # Permissions (access these through the 'permissions' property) db_permissions = models.CharField('permissions', max_length=255, blank=True, help_text="a comma-separated list of text strings checked by certain locks. They are often used for hierarchies, such as letting a Player have permission 'Wizards', 'Builders' etc. Character objects use 'Players' by default. Most other objects don't have any permissions.") # Lock storage db_lock_storage = models.CharField('locks', max_length=512, blank=True, help_text="locks limit access to an entity. A lock is defined as a 'lock string' on the form 'type:lockfunctions', defining what functionality is locked and how to determine access. Not defining a lock means no access is granted.") # Database manager objects = managers.TypedObjectManager() # object cache and flags cached_typeclass_path = "" cached_typeclass = None # lock handler self.locks def __init__(self, *args, **kwargs): "We must initialize the parent first - important!" SharedMemoryModel.__init__(self, *args, **kwargs) self.locks = LockHandler(self) class Meta: """ Django setup info. """ abstract = True verbose_name = "Evennia Database Object" ordering = ['-db_date_created', 'id', 'db_typeclass_path', 'db_key'] # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that allows the user to do self.attr = value, # value = self.attr and del self.attr respectively (where self # is the object in question). # key property (wraps db_key) #@property def key_get(self): "Getter. Allows for value = self.key" return self.db_key #@key.setter def key_set(self, value): "Setter. Allows for self.key = value" self.db_key = value self.save() #@key.deleter def key_del(self): "Deleter. Allows for del self.key" raise Exception("Cannot delete objectdb key!") key = property(key_get, key_set, key_del) # name property (wraps db_key too - alias to self.key) #@property def name_get(self): "Getter. Allows for value = self.name" return self.db_key #@name.setter def name_set(self, value): "Setter. Allows for self.name = value" self.db_key = value self.save() #@name.deleter def name_del(self): "Deleter. Allows for del self.name" raise Exception("Cannot delete name!") name = property(name_get, name_set, name_del) # typeclass_path property #@property def typeclass_path_get(self): "Getter. Allows for value = self.typeclass_path" typeclass_path = GA(self, 'cached_typeclass_path') if typeclass_path: return typeclass_path return self.db_typeclass_path #@typeclass_path.setter def typeclass_path_set(self, value): "Setter. Allows for self.typeclass_path = value" self.db_typeclass_path = value self.save() SA(self, 'cached_typeclass_path', value) #@typeclass_path.deleter def typeclass_path_del(self): "Deleter. Allows for del self.typeclass_path" self.db_typeclass_path = "" self.save() self.cached_typeclass_path = "" typeclass_path = property(typeclass_path_get, typeclass_path_set, typeclass_path_del) # date_created property #@property def date_created_get(self): "Getter. Allows for value = self.date_created" return self.db_date_created #@date_created.setter def date_created_set(self, value): "Setter. Allows for self.date_created = value" raise Exception("Cannot change date_created!") #@date_created.deleter def date_created_del(self): "Deleter. Allows for del self.date_created" raise Exception("Cannot delete date_created!") date_created = property(date_created_get, date_created_set, date_created_del) # permissions property #@property def permissions_get(self): "Getter. Allows for value = self.name. Returns a list of permissions." if self.db_permissions: return [perm.strip() for perm in self.db_permissions.split(',')] return [] #@permissions.setter def permissions_set(self, value): "Setter. Allows for self.name = value. Stores as a comma-separated string." if is_iter(value): value = ",".join([utils.to_unicode(val).strip() for val in value]) self.db_permissions = value self.save() #@permissions.deleter def permissions_del(self): "Deleter. Allows for del self.name" self.db_permissions = "" self.save() permissions = property(permissions_get, permissions_set, permissions_del) # lock_storage property (wraps db_lock_storage) #@property def lock_storage_get(self): "Getter. Allows for value = self.lock_storage" return self.db_lock_storage #@lock_storage.setter def lock_storage_set(self, value): """Saves the lock_storagetodate. This is usually not called directly, but through self.lock()""" self.db_lock_storage = value self.save() #@lock_storage.deleter def lock_storage_del(self): "Deleter is disabled. Use the lockhandler.delete (self.lock.delete) instead""" logger.log_errmsg("Lock_Storage (on %s) cannot be deleted. Use obj.lock.delete() instead." % self) lock_storage = property(lock_storage_get, lock_storage_set, lock_storage_del) # # # TypedObject main class methods and properties # # # Each subclass should set this property to their respective # attribute model (ObjAttribute, PlayerAttribute etc). #attribute_model_path = "src.typeclasses.models" #attribute_model_name = "Attribute" typeclass_paths = settings.OBJECT_TYPECLASS_PATHS attribute_class = Attribute # replaced by relevant attribute class for child def __eq__(self, other): return other and hasattr(other, 'id') and self.id == other.id def __str__(self): return smart_str("%s" % self.key) def __unicode__(self): return u"%s" % self.key def __getattribute__(self, propname): """ Will predominantly look for an attribute on this object, but if not found we will check if it might exist on the typeclass instead. Since the typeclass refers back to the databaseobject as well, we have to be very careful to avoid loops. """ try: return GA(self, propname) except AttributeError: # check if the attribute exists on the typeclass instead # (we make sure to not incur a loop by not triggering the # typeclass' __getattribute__, since that one would # try to look back to this very database object.) typeclass = GA(self, 'typeclass') if typeclass: return GA(typeclass, propname) else: raise AttributeError #@property def dbref_get(self): """ Returns the object's dbref id on the form #NN. Alternetively, use obj.id directly to get dbref without any #. """ return "#%s" % str(self.id) dbref = property(dbref_get) # typeclass property #@property def typeclass_get(self): """ Getter. Allows for value = self.typeclass. The typeclass is a class object found at self.typeclass_path; it allows for extending the Typed object for all different types of objects that the game needs. This property handles loading and initialization of the typeclass on the fly. Note: The liberal use of GA and __setattr__ (instead of normal dot notation) is due to optimization: it avoids calling the custom self.__getattribute__ more than necessary. """ path = GA(self, "cached_typeclass_path") if not path: path = GA(self, 'db_typeclass_path') typeclass = GA(self, "cached_typeclass") try: if typeclass and GA(typeclass, "path") == path: # don't call at_init() when returning from cache return typeclass except AttributeError: pass errstring = "" if not path: # this means we should get the default obj without giving errors. return GA(self, "get_default_typeclass")(cache=True, silent=True, save=True) else: # handle loading/importing of typeclasses, searching all paths. # (self.typeclass_paths is a shortcut to settings.TYPECLASS_*_PATHS # where '*' is either OBJECT, SCRIPT or PLAYER depending on the typed # entities). typeclass_paths = [path] + ["%s.%s" % (prefix, path) for prefix in GA(self, 'typeclass_paths')] for tpath in typeclass_paths: # try to import and analyze the result typeclass = GA(self, "_path_import")(tpath) if callable(typeclass): # we succeeded to import. Cache and return. SA(self, 'db_typeclass_path', tpath) GA(self, 'save')() SA(self, "cached_typeclass_path", tpath) typeclass = typeclass(self) SA(self, "cached_typeclass", typeclass) try: typeclass.at_init() except Exception: logger.log_trace() return typeclass elif hasattr(typeclass, '__file__'): errstring += "\n%s seems to be just the path to a module. You need" % tpath errstring += " to specify the actual typeclass name inside the module too." else: errstring += "\n%s" % typeclass # this will hold a growing error message. # If we reach this point we couldn't import any typeclasses. Return default. It's up to the calling # method to use e.g. self.is_typeclass() to detect that the result is not the one asked for. GA(self, "_display_errmsg")(errstring) return GA(self, "get_default_typeclass")(cache=False, silent=False, save=False) #@typeclass.deleter def typeclass_del(self): "Deleter. Disallow 'del self.typeclass'" raise Exception("The typeclass property should never be deleted, only changed in-place!") # typeclass property typeclass = property(typeclass_get, fdel=typeclass_del) def _path_import(self, path): """ Import a class from a python path of the form src.objects.object.Object """ errstring = "" if not path: # this needs not be bad, it just means # we should use defaults. return None try: modpath, class_name = path.rsplit('.', 1) module = __import__(modpath, fromlist=[class_name]) return module.__dict__[class_name] except ImportError: trc = sys.exc_traceback if not trc.tb_next: # we separate between not finding the module, and finding a buggy one. errstring += "(Tried path '%s')." % path else: # a bug in the module is reported normally. trc = traceback.format_exc() errstring += "\n%sError importing '%s'." % (trc, path) except KeyError: errstring = "No class '%s' was found in module '%s'." errstring = errstring % (class_name, modpath) except Exception: trc = traceback.format_exc() errstring = "\n%sException importing '%s'." % (trc, path) # return the error. return errstring def _display_errmsg(self, message): """ Helper function to display error. """ infochan = None cmessage = message try: from src.comms.models import Channel infochan = settings.CHANNEL_MUDINFO infochan = Channel.objects.get_channel(infochan[0]) if infochan: cname = infochan.key cmessage = "\n".join(["[%s]: %s" % (cname, line) for line in message.split('\n') if line]) cmessage = cmessage.strip() infochan.msg(cmessage) else: # no mudinfo channel is found. Log instead. cmessage = "\n".join(["[NO MUDINFO CHANNEL]: %s" % line for line in message.split('\n')]) logger.log_errmsg(cmessage) except Exception, e: if ServerConfig.objects.conf("server_starting_mode"): print cmessage else: logger.log_trace(cmessage) def get_default_typeclass(self, cache=False, silent=False, save=False): """ This is called when a typeclass fails to load for whatever reason. Overload this in different entities. Default operation is to load a default typeclass. """ defpath = GA(self, "default_typeclass_path") typeclass = GA(self, "_path_import")(defpath) # if not silent: # #errstring = "\n\nUsing Default class '%s'." % defpath # GA(self, "_display_errmsg")(errstring) if not callable(typeclass): # if typeclass still doesn't exist at this point, we're in trouble. # fall back to hardcoded core class which is wrong for e.g. scripts/players etc. failpath = defpath defpath = "src.objects.objects.Object" typeclass = GA(self, "_path_import")(defpath) if not silent: #errstring = " %s\n%s" % (typeclass, errstring) errstring = " Default class '%s' failed to load." % failpath errstring += "\n Using Evennia's default class '%s'." % defpath GA(self, "_display_errmsg")(errstring) if not callable(typeclass): # if this is still giving an error, Evennia is wrongly configured or buggy raise Exception("CRITICAL ERROR: The final fallback typeclass %s cannot load!!" % defpath) typeclass = typeclass(self) if save: SA(self, 'db_typeclass_path', defpath) GA(self, 'save')() if cache: SA(self, "cached_typeclass_path", defpath) SA(self, "cached_typeclass", typeclass) try: typeclass.at_init() except Exception: logger.log_trace() return typeclass def is_typeclass(self, typeclass, exact=False): """ Returns true if this object has this type OR has a typeclass which is an subclass of the given typeclass. typeclass - can be a class object or the python path to such an object to match against. exact - returns true only if the object's type is exactly this typeclass, ignoring parents. """ try: typeclass = typeclass.path except AttributeError: pass typeclasses = [typeclass] + ["%s.%s" % (path, typeclass) for path in self.typeclass_paths] if exact: current_path = GA(self, "cached_typeclass_path") return typeclass and any([current_path == typec for typec in typeclasses]) else: # check parent chain return any([cls for cls in self.typeclass.__class__.mro() if any(["%s.%s" % (cls.__module__, cls.__name__) == typec for typec in typeclasses])]) # # Object manipulation methods # # def swap_typeclass(self, new_typeclass, clean_attributes=False, no_default=True): """ This performs an in-situ swap of the typeclass. This means that in-game, this object will suddenly be something else. Player will not be affected. To 'move' a player to a different object entirely (while retaining this object's type), use self.player.swap_object(). Note that this might be an error prone operation if the old/new typeclass was heavily customized - your code might expect one and not the other, so be careful to bug test your code if using this feature! Often its easiest to create a new object and just swap the player over to that one instead. new_typeclass (path/classobj) - type to switch to clean_attributes (bool/list) - will delete all attributes stored on this object (but not any of the database fields such as name or location). You can't get attributes back, but this is often the safest bet to make sure nothing in the new typeclass clashes with the old one. If you supply a list, only those named attributes will be cleared. no_default - if this is active, the swapper will not allow for swapping to a default typeclass in case the given one fails for some reason. Instead the old one will be preserved. """ if callable(new_typeclass): # this is an actual class object - build the path cls = new_typeclass.__class__ new_typeclass = "%s.%s" % (cls.__module__, cls.__name__) # Try to set the new path # this will automatically save to database old_typeclass_path = self.typeclass_path self.typeclass_path = new_typeclass.strip() # this will automatically use a default class if # there is an error with the given typeclass. new_typeclass = self.typeclass if self.typeclass_path == new_typeclass.path: # the typeclass loading worked as expected self.cached_typeclass_path = None self.cached_typeclass = None elif no_default: # something went wrong; the default was loaded instead, # and we don't allow that; instead we return to previous. self.typeclass_path = old_typeclass_path self.cached_typeclass = None return False if clean_attributes: # Clean out old attributes if is_iter(clean_attributes): for attr in clean_attributes: self.attr(attr, delete=True) for nattr in clean_attributes: if hasattr(self.ndb, nattr): self.nattr(nattr, delete=True) else: #print "deleting attrs ..." self.get_all_attributes() for attr in self.get_all_attributes(): attr.delete() for nattr in self.ndb.all(): del nattr # run hooks for this new typeclass new_typeclass.basetype_setup() new_typeclass.at_object_creation() return True # # Attribute handler methods # # # Fully persistent attributes. You usually access these # through the obj.db.attrname method. # Helper methods for persistent attributes def has_attribute(self, attribute_name): """ See if we have an attribute set on the object. attribute_name: (str) The attribute's name. """ return self.attribute_class.objects.filter(db_obj=self).filter( db_key__iexact=attribute_name).count() def set_attribute(self, attribute_name, new_value=None): """ Sets an attribute on an object. Creates the attribute if need be. attribute_name: (str) The attribute's name. new_value: (python obj) The value to set the attribute to. If this is not a str, the object will be stored as a pickle. """ attrib_obj = None attrclass = self.attribute_class try: attrib_obj = attrclass.objects.filter( db_obj=self).filter(db_key__iexact=attribute_name)[0] except IndexError: # no match; create new attribute new_attrib = attrclass(db_key=attribute_name, db_obj=self) new_attrib.value = new_value return # re-set an old attribute value attrib_obj.value = new_value def get_attribute(self, attribute_name, default=None): """ Returns the value of an attribute on an object. You may need to type cast the returned value from this function since the attribute can be of any type. Returns default if no match is found. attribute_name: (str) The attribute's name. default: What to return if no attribute is found """ attrib_obj = default try: attrib_obj = self.attribute_class.objects.filter( db_obj=self).filter(db_key__iexact=attribute_name)[0] except IndexError: return default return attrib_obj.value def get_attribute_raise(self, attribute_name): """ Returns value of an attribute. Raises AttributeError if no match is found. attribute_name: (str) The attribute's name. """ try: return self.attribute_class.objects.filter( db_obj=self).filter(db_key__iexact=attribute_name)[0].value except IndexError: raise AttributeError def del_attribute(self, attribute_name): """ Removes an attribute entirely. attribute_name: (str) The attribute's name. """ try: self.attribute_class.objects.filter( db_obj=self).filter(db_key__iexact=attribute_name)[0].delete() except IndexError: pass def del_attribute_raise(self, attribute_name): """ Removes and attribute. Raises AttributeError if attribute is not found. attribute_name: (str) The attribute's name. """ try: self.attribute_class.objects.filter( db_obj=self).filter(db_key__iexact=attribute_name)[0].delete() except IndexError: raise AttributeError def get_all_attributes(self): """ Returns all attributes defined on the object. """ return list(self.attribute_class.objects.filter(db_obj=self)) def attr(self, attribute_name=None, value=None, delete=False): """ This is a convenient wrapper for get_attribute, set_attribute, del_attribute and get_all_attributes. If value is None, attr will act like a getter, otherwise as a setter. set delete=True to delete the named attribute. Note that you cannot set the attribute value to None using this method. Use set_attribute. """ if attribute_name == None: # act as a list method return self.get_all_attributes() elif delete == True: self.del_attribute(attribute_name) elif value == None: # act as a getter. return self.get_attribute(attribute_name) else: # act as a setter self.set_attribute(attribute_name, value) #@property def db_get(self): """ A second convenience wrapper for the the attribute methods. It allows for the syntax obj.db.attrname = value and value = obj.db.attrname and del obj.db.attrname and all_attr = obj.db.all() (if there is no attribute named 'all', in which case that will be returned instead). """ try: return self._db_holder except AttributeError: class DbHolder(object): "Holder for allowing property access of attributes" def __init__(self, obj): SA(self, 'obj', obj) def __getattribute__(self, attrname): if attrname == 'all': # we allow for overwriting the all() method # with an attribute named 'all'. attr = GA(self, 'obj').get_attribute("all") if attr: return attr return GA(self, 'all') return GA(self, 'obj').get_attribute(attrname) def __setattr__(self, attrname, value): GA(self, 'obj').set_attribute(attrname, value) def __delattr__(self, attrname): GA(self, 'obj').del_attribute(attrname) def all(self): return GA(self, 'obj').get_all_attributes() self._db_holder = DbHolder(self) return self._db_holder #@db.setter def db_set(self, value): "Stop accidentally replacing the db object" string = "Cannot assign directly to db object! " string += "Use db.attr=value instead." raise Exception(string) #@db.deleter def db_del(self): "Stop accidental deletion." raise Exception("Cannot delete the db object!") db = property(db_get, db_set, db_del) # # NON-PERSISTENT storage methods # def nattr(self, attribute_name=None, value=None, delete=False): """ This is the equivalence of self.attr but for non-persistent stores. """ if attribute_name == None: # act as a list method if callable(self.ndb.all): return self.ndb.all() else: return [val for val in self.ndb.__dict__.keys() if not val.startswith['_']] elif delete == True: if hasattr(self.ndb, attribute_name): DA(self.db, attribute_name) elif value == None: # act as a getter. if hasattr(self.ndb, attribute_name): GA(self.ndb, attribute_name) else: return None else: # act as a setter SA(self.db, attribute_name, value) #@property def ndb_get(self): """ A non-persistent store (ndb: NonDataBase). Everything stored to this is guaranteed to be cleared when a server is shutdown. Syntax is same as for the _get_db_holder() method and property, e.g. obj.ndb.attr = value etc. """ try: return self._ndb_holder except AttributeError: class NdbHolder(object): "Holder for storing non-persistent attributes." def all(self): return [val for val in self.__dict__.keys() if not val.startswith['_']] def __getattribute__(self, key): # return None if no matching attribute was found. try: return GA(self, key) except AttributeError: return None self._ndb_holder = NdbHolder() return self._ndb_holder #@ndb.setter def ndb_set(self, value): "Stop accidentally replacing the db object" string = "Cannot assign directly to ndb object! " string = "Use ndb.attr=value instead." raise Exception(string) #@ndb.deleter def ndb_del(self): "Stop accidental deletion." raise Exception("Cannot delete the ndb object!") ndb = property(ndb_get, ndb_set, ndb_del) # # Lock / permission methods # def access(self, accessing_obj, access_type='read', default=False): """ Determines if another object has permission to access. accessing_obj - object trying to access this one access_type - type of access sought default - what to return if no lock of access_type was found """ return self.locks.check(accessing_obj, access_type=access_type, default=default) def has_perm(self, accessing_obj, access_type): "Alias to access" logger.log_depmsg("has_perm() is deprecated. Use access() instead.") return self.access(accessing_obj, access_type) def check_permstring(self, permstring): """ This explicitly checks if we hold particular permission without involving any locks. """ if self.player and self.player.is_superuser: return True if not permstring: return False perm = permstring.lower() if perm in [p.lower() for p in self.permissions]: # simplest case - we have a direct match return True if perm in PERMISSION_HIERARCHY: # check if we have a higher hierarchy position ppos = PERMISSION_HIERARCHY.index(perm) return any(True for hpos, hperm in enumerate(PERMISSION_HIERARCHY) if hperm in [p.lower() for p in self.permissions] and hpos > ppos) return False
Python
""" This implements the common managers that are used by the abstract models in dbobjects.py (and which are thus shared by all Attributes and TypedObjects). """ from django.db import models from src.utils import idmapper #from src.typeclasses import idmap # Managers class AttributeManager(models.Manager): "Manager for handling Attributes." def attr_namesearch(self, searchstr, obj, exact_match=True): """ Searches the object's attributes for name matches. searchstr: (str) A string to search for. """ # Retrieve the list of attributes for this object. if exact_match: return self.filter(db_obj=obj).filter( db_key__iexact=searchstr) else: return self.filter(db_obj=obj).filter( db_key__icontains=searchstr) # # helper functions for the TypedObjectManager. # def returns_typeclass_list(method): """ Decorator function that turns the return of the decorated method (which are ObjectDB objects) into object_classes(s) instead. Will always return a list or None. """ def func(self, *args, **kwargs): """ This overloads the relevant method. The return is *always* either None or a list. """ match = method(self, *args, **kwargs) #print "deco: %s" % match, if not match: return [] try: match = list(match) except TypeError: match = [match] obj_classes = [] for dbobj in match: try: obj_classes.append(dbobj.typeclass) except Exception: obj_classes.append(dbobj) #logger.log_trace() #print "-> %s" % obj_classes #if not obj_classes: # return None return obj_classes return func def returns_typeclass(method): """ Decorator: Will always return a single result or None. """ def func(self, *args, **kwargs): "decorator" rfunc = returns_typeclass_list(method) match = rfunc(self, *args, **kwargs) if match: return match[0] return None return func #class TypedObjectManager(idmap.CachingManager): #class TypedObjectManager(models.Manager): class TypedObjectManager(idmapper.manager.SharedMemoryManager): """ Common ObjectManager for all dbobjects. """ def dbref(self, dbref): """ Valid forms of dbref (database reference number) are either a string '#N' or an integer N. Output is the integer part. """ if isinstance(dbref, basestring): dbref = dbref.lstrip('#') try: if int(dbref) < 1: return None except Exception: return None return dbref @returns_typeclass def dbref_search(self, dbref): """ Returns an object when given a dbref. """ dbref = self.dbref(dbref) if dbref : try: return self.get(id=dbref) except self.model.DoesNotExist: return None return None @returns_typeclass_list def get_dbref_range(self, min_dbref=None, max_dbref=None): """ Return all objects inside and including the given boundaries. """ min_dbref, max_dbref = self.dbref(min_dbref), self.dbref(max_dbref) if not min_dbref or not max_dbref: return self.all() if not min_dbref: return self.filter(id__lte=max_dbref) elif not max_dbref: return self.filter(id__gte=min_dbref) return self.filter(id__gte=min_dbref).filter(id__lte=min_dbref) def get_id(self, idnum): """ Alias to dbref_search """ return self.dbref_search(idnum) def object_totals(self): """ Returns a dictionary with all the typeclasses active in-game as well as the number of such objects defined (i.e. the number of database object having that typeclass set on themselves). """ dbtotals = {} typeclass_paths = set(self.values_list('db_typeclass_path', flat=True)) for typeclass_path in typeclass_paths: dbtotals[typeclass_path] = \ self.filter(db_typeclass_path=typeclass_path).count() return dbtotals @returns_typeclass_list def typeclass_search(self, typeclass): """ Searches through all objects returning those which has a certain typeclass. If location is set, limit search to objects in that location. """ if callable(typeclass): cls = typeclass.__class__ typeclass = "%s.%s" % (cls.__module__, cls.__name__) o_query = self.filter(db_typeclass_path__exact=typeclass) return o_query
Python
# # This sets up how models are displayed # in the web admin interface. # from src.scripts.models import ScriptAttribute, ScriptDB from django.contrib import admin class ScriptAttributeInline(admin.TabularInline): model = ScriptAttribute fields = ('db_key', 'db_value') max_num = 1 class ScriptDBAdmin(admin.ModelAdmin): list_display = ('id', 'db_key', 'db_typeclass_path', 'db_obj', 'db_interval', 'db_repeats', 'db_persistent') list_display_links = ('id', 'db_key') ordering = ['db_obj', 'db_typeclass_path'] search_fields = ['^db_key', 'db_typeclass_path'] save_as = True save_on_top = True list_select_related = True fieldsets = ( (None, { 'fields':(('db_key', 'db_typeclass_path'), 'db_interval', 'db_repeats', 'db_start_delay', 'db_persistent', 'db_obj')}), ) #inlines = [ScriptAttributeInline] admin.site.register(ScriptDB, ScriptDBAdmin)
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ScriptAttribute' db.create_table('scripts_scriptattribute', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(max_length=255)), ('db_value', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('db_mode', self.gf('django.db.models.fields.CharField')(max_length=20, null=True, blank=True)), ('db_lock_storage', self.gf('django.db.models.fields.TextField')(blank=True)), ('db_date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('db_obj', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['scripts.ScriptDB'])), )) db.send_create_signal('scripts', ['ScriptAttribute']) # Adding model 'ScriptDB' db.create_table('scripts_scriptdb', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(max_length=255)), ('db_typeclass_path', self.gf('django.db.models.fields.CharField')(max_length=255, null=True)), ('db_date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('db_permissions', self.gf('django.db.models.fields.CharField')(max_length=512, blank=True)), ('db_lock_storage', self.gf('django.db.models.fields.TextField')(blank=True)), ('db_desc', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), ('db_obj', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['objects.ObjectDB'], null=True, blank=True)), ('db_interval', self.gf('django.db.models.fields.IntegerField')(default=-1)), ('db_start_delay', self.gf('django.db.models.fields.BooleanField')(default=False)), ('db_repeats', self.gf('django.db.models.fields.IntegerField')(default=0)), ('db_persistent', self.gf('django.db.models.fields.BooleanField')(default=False)), ('db_is_active', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal('scripts', ['ScriptDB']) def backwards(self, orm): # Deleting model 'ScriptAttribute' db.delete_table('scripts_scriptattribute') # Deleting model 'ScriptDB' db.delete_table('scripts_scriptdb') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'scripts.scriptattribute': { 'Meta': {'object_name': 'ScriptAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_mode': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['scripts.ScriptDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'scripts.scriptdb': { 'Meta': {'object_name': 'ScriptDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_interval': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'db_is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_persistent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_repeats': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'db_start_delay': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['scripts']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'ScriptDB.db_lock_storage' db.alter_column('scripts_scriptdb', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512)) # Changing field 'ScriptDB.db_permissions' db.alter_column('scripts_scriptdb', 'db_permissions', self.gf('django.db.models.fields.CharField')(max_length=255)) # Changing field 'ScriptAttribute.db_lock_storage' db.alter_column('scripts_scriptattribute', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512)) def backwards(self, orm): # Changing field 'ScriptDB.db_lock_storage' db.alter_column('scripts_scriptdb', 'db_lock_storage', self.gf('django.db.models.fields.TextField')()) # Changing field 'ScriptDB.db_permissions' db.alter_column('scripts_scriptdb', 'db_permissions', self.gf('django.db.models.fields.CharField')(max_length=512)) # Changing field 'ScriptAttribute.db_lock_storage' db.alter_column('scripts_scriptattribute', 'db_lock_storage', self.gf('django.db.models.fields.TextField')()) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'scripts.scriptattribute': { 'Meta': {'object_name': 'ScriptAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['scripts.ScriptDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'scripts.scriptdb': { 'Meta': {'object_name': 'ScriptDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_interval': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'db_is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_persistent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_repeats': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'db_start_delay': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['scripts']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'ScriptAttribute.db_mode' from src.scripts.models import ScriptAttribute from src.typeclasses.models import PackedDBobject for attr in ScriptAttribute.objects.all(): # resave attributes db_mode = attr.db_mode if db_mode and db_mode != 'pickle': # an object. We need to resave this. if db_mode == 'object': val = PackedDBobject(attr.db_value, "objectdb") elif db_mode == 'player': val = PackedDBobject(attr.db_value, "playerdb") elif db_mode == 'script': val = PackedDBobject(attr.db_value, "scriptdb") elif db_mode == 'help': val = PackedDBobject(attr.db_value, "helpentry") else: val = PackedDBobject(attr.db_value, db_mode) # channel, msg attr.value = val db.delete_column('scripts_scriptattribute', 'db_mode') def backwards(self, orm): # Adding field 'ScriptAttribute.db_mode' db.add_column('scripts_scriptattribute', 'db_mode', self.gf('django.db.models.fields.CharField')(max_length=20, null=True, blank=True), keep_default=False) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'scripts.scriptattribute': { 'Meta': {'object_name': 'ScriptAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['scripts.ScriptDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'scripts.scriptdb': { 'Meta': {'object_name': 'ScriptDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_interval': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'db_is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_persistent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_repeats': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'db_start_delay': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['scripts']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding index on 'ScriptDB', fields ['db_key'] db.create_index('scripts_scriptdb', ['db_key']) # Adding index on 'ScriptAttribute', fields ['db_key'] db.create_index('scripts_scriptattribute', ['db_key']) def backwards(self, orm): # Removing index on 'ScriptAttribute', fields ['db_key'] db.delete_index('scripts_scriptattribute', ['db_key']) # Removing index on 'ScriptDB', fields ['db_key'] db.delete_index('scripts_scriptdb', ['db_key']) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'scripts.scriptattribute': { 'Meta': {'object_name': 'ScriptAttribute'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['scripts.ScriptDB']"}), 'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'scripts.scriptdb': { 'Meta': {'object_name': 'ScriptDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_interval': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'db_is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_persistent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_repeats': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'db_start_delay': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['scripts']
Python
""" The custom manager for Scripts. """ from src.typeclasses.managers import TypedObjectManager from src.typeclasses.managers import returns_typeclass_list VALIDATE_ITERATION = 0 class ScriptManager(TypedObjectManager): """ ScriptManager get methods """ @returns_typeclass_list def get_all_scripts_on_obj(self, obj, key=None): """ Returns as result all the Scripts related to a particular object """ if not obj: return [] scripts = self.filter(db_obj=obj) if key: return scripts.filter(db_key=key) return scripts @returns_typeclass_list def get_all_scripts(self, key=None): """ Return all scripts, alternative only scripts with a certain key/dbref or path. """ if key: dbref = self.dbref(key) if dbref: # try to see if this is infact a dbref script = self.dbref_search(dbref) if script: return script # not a dbref. Normal key search scripts = self.filter(db_key=key) else: scripts = list(self.all()) return scripts def delete_script(self, dbref): """ This stops and deletes a specific script directly from the script database. This might be needed for global scripts not tied to a specific game object. """ scripts = self.get_id(dbref) for script in scripts: script.stop() def remove_non_persistent(self, obj=None): """ This cleans up the script database of all non-persistent scripts, or only those on obj. It is called every time the server restarts and """ if obj: to_stop = self.filter(db_persistent=False, db_obj=obj) else: to_stop = self.filter(db_persistent=False) nr_deleted = to_stop.count() for script in to_stop.filter(db_is_active=True): script.stop() for script in to_stop.filter(db_is_active=False): script.delete() return nr_deleted def validate(self, scripts=None, obj=None, key=None, dbref=None, init_mode=False): """ This will step through the script database and make sure all objects run scripts that are still valid in the context they are in. This is called by the game engine at regular intervals but can also be initiated by player scripts. If key and/or obj is given, only update the related script/object. Only one of the arguments are supposed to be supplied at a time, since they are exclusive to each other. scripts = a list of scripts objects obtained somewhere. obj = validate only scripts defined on a special object. key = validate only scripts with a particular key dbref = validate only the single script with this particular id. init_mode - This is used during server upstart and can have three values: False (no init mode). Called during run. "reset" - server reboot. Kill non-persistent scripts "reload" - server reload. Keep non-persistent scripts. This method also makes sure start any scripts it validates, this should be harmless, since already-active scripts have the property 'is_running' set and will be skipped. """ # we store a variable that tracks if we are calling a # validation from within another validation (avoids # loops). global VALIDATE_ITERATION if VALIDATE_ITERATION > 0: # we are in a nested validation. Exit. VALIDATE_ITERATION -= 1 return None, None VALIDATE_ITERATION += 1 # not in a validation - loop. Validate as normal. nr_started = 0 nr_stopped = 0 if init_mode: if init_mode == 'reset': # special mode when server starts or object logs in. # This deletes all non-persistent scripts from database nr_stopped += self.remove_non_persistent(obj=obj) # turn off the activity flag for all remaining scripts scripts = self.get_all_scripts() for script in scripts: script.dbobj.is_active = False elif not scripts: # normal operation if dbref and self.dbref(dbref): scripts = self.get_id(dbref) elif obj: scripts = self.get_all_scripts_on_obj(obj, key=key) else: scripts = self.get_all_scripts(key=key) #self.model.get_all_cached_instances() if not scripts: # no scripts available to validate VALIDATE_ITERATION -= 1 return None, None #print "scripts to validate: [%s]" % (", ".join(script.key for script in scripts)) for script in scripts: #print "validating %s (%i) (init_mode=%s)" % (script.key, id(script.dbobj), init_mode) if script.is_valid(): nr_started += script.start(force_restart=init_mode) #print "back from start. nr_started=", nr_started else: script.stop() nr_stopped += 1 VALIDATE_ITERATION -= 1 return nr_started, nr_stopped @returns_typeclass_list def script_search(self, ostring, obj=None, only_timed=False): """ Search for a particular script. ostring - search criterion - a script ID or key obj - limit search to scripts defined on this object only_timed - limit search only to scripts that run on a timer. """ ostring = ostring.strip() dbref = self.dbref(ostring) if dbref: # this is a dbref, try to find the script directly dbref_match = self.dbref_search(dbref) if dbref_match: ok = True if obj and obj != dbref_match.obj: ok = False if only_timed and dbref_match.interval: ok = False if ok: return [dbref_match] # not a dbref; normal search scripts = self.filter(db_key__iexact=ostring) if obj: scripts = scripts.exclude(db_obj=None).filter(db_obj__db_key__iexact=ostring) if only_timed: scripts = scripts.exclude(interval=0) return scripts def copy_script(self, original_script, new_key=None, new_obj=None, new_locks=None): """ Make an identical copy of the original_script """ typeclass = original_script.typeclass_path if not new_key: new_key = original_script.key if not new_obj: new_obj = original_script.obj if not new_locks: new_locks = original_script.db_lock_storage from src.utils import create new_script = create.create_script(typeclass, key=new_key, obj=new_obj, locks=new_locks, autostart=True) return new_script
Python
""" Scripts are entities that perform some sort of action, either only once or repeatedly. They can be directly linked to a particular Evennia Object or be stand-alonw (in the latter case it is considered a 'global' script). Scripts can indicate both actions related to the game world as well as pure behind-the-scenes events and effects. Everything that has a time component in the game (i.e. is not hard-coded at startup or directly created/controlled by players) is handled by Scripts. Scripts have to check for themselves that they should be applied at a particular moment of time; this is handled by the is_valid() hook. Scripts can also implement at_start and at_end hooks for preparing and cleaning whatever effect they have had on the game object. Common examples of uses of Scripts: - load the default cmdset to the player object's cmdhandler when logging in. - switch to a different state, such as entering a text editor, start combat or enter a dark room. - Weather patterns in-game - merge a new cmdset with the default one for changing which commands are available at a particular time - give the player/object a time-limited bonus/effect """ from django.conf import settings from django.db import models from src.typeclasses.models import Attribute, TypedObject from django.contrib.contenttypes.models import ContentType from src.scripts.manager import ScriptManager #------------------------------------------------------------ # # ScriptAttribute # #------------------------------------------------------------ class ScriptAttribute(Attribute): "Attributes for ScriptDB objects." db_obj = models.ForeignKey("ScriptDB", verbose_name='script') class Meta: "Define Django meta options" verbose_name = "Script Attribute" verbose_name_plural = "Script Attributes" #------------------------------------------------------------ # # ScriptDB # #------------------------------------------------------------ class ScriptDB(TypedObject): """ The Script database representation. The TypedObject supplies the following (inherited) properties: key - main name name - alias for key typeclass_path - the path to the decorating typeclass typeclass - auto-linked typeclass date_created - time stamp of object creation permissions - perm strings dbref - #id of object db - persistent attribute storage ndb - non-persistent attribute storage The ScriptDB adds the following properties: desc - optional description of script obj - the object the script is linked to, if any interval - how often script should run start_delay - if the script should start repeating right away repeats - how many times the script should repeat persistent - if script should survive a server reboot is_active - bool if script is currently running """ # # ScriptDB Database Model setup # # These databse fields are all set using their corresponding properties, # named same as the field, but withtou the db_* prefix. # inherited fields (from TypedObject): # db_key, db_typeclass_path, db_date_created, db_permissions # optional description. db_desc = models.CharField('desc', max_length=255, blank=True) # A reference to the database object affected by this Script, if any. db_obj = models.ForeignKey("objects.ObjectDB", null=True, blank=True, verbose_name='scripted object', help_text='the object to store this script on, if not a global script.') # how often to run Script (secs). -1 means there is no timer db_interval = models.IntegerField('interval', default=-1, help_text='how often to repeat script, in seconds. -1 means off.') # start script right away or wait interval seconds first db_start_delay = models.BooleanField('start delay', default=False, help_text='pause interval seconds before starting.') # how many times this script is to be repeated, if interval!=0. db_repeats = models.IntegerField('number of repeats', default=0, help_text='0 means off.') # defines if this script should survive a reboot or not db_persistent = models.BooleanField('survive server reboot', default=False) # defines if this script has already been started in this session db_is_active = models.BooleanField('script active', default=False) # Database manager objects = ScriptManager() class Meta: "Define Django meta options" verbose_name = "Script" # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that allows the user to do self.attr = value, # value = self.attr and del self.attr respectively (where self # is the script in question). # desc property (wraps db_desc) #@property def desc_get(self): "Getter. Allows for value = self.desc" return self.db_desc #@desc.setter def desc_set(self, value): "Setter. Allows for self.desc = value" self.db_desc = value self.save() #@desc.deleter def desc_del(self): "Deleter. Allows for del self.desc" self.db_desc = "" self.save() desc = property(desc_get, desc_set, desc_del) # obj property (wraps db_obj) #@property def obj_get(self): "Getter. Allows for value = self.obj" return self.db_obj #@obj.setter def obj_set(self, value): "Setter. Allows for self.obj = value" self.db_obj = value self.save() #@obj.deleter def obj_del(self): "Deleter. Allows for del self.obj" self.db_obj = None self.save() obj = property(obj_get, obj_set, obj_del) # interval property (wraps db_interval) #@property def interval_get(self): "Getter. Allows for value = self.interval" return self.db_interval #@interval.setter def interval_set(self, value): "Setter. Allows for self.interval = value" self.db_interval = int(value) self.save() #@interval.deleter def interval_del(self): "Deleter. Allows for del self.interval" self.db_interval = 0 self.save() interval = property(interval_get, interval_set, interval_del) # start_delay property (wraps db_start_delay) #@property def start_delay_get(self): "Getter. Allows for value = self.start_delay" return self.db_start_delay #@start_delay.setter def start_delay_set(self, value): "Setter. Allows for self.start_delay = value" self.db_start_delay = value self.save() #@start_delay.deleter def start_delay_del(self): "Deleter. Allows for del self.start_delay" self.db_start_delay = False self.save() start_delay = property(start_delay_get, start_delay_set, start_delay_del) # repeats property (wraps db_repeats) #@property def repeats_get(self): "Getter. Allows for value = self.repeats" return self.db_repeats #@repeats.setter def repeats_set(self, value): "Setter. Allows for self.repeats = value" self.db_repeats = int(value) self.save() #@repeats.deleter def repeats_del(self): "Deleter. Allows for del self.repeats" self.db_repeats = 0 self.save() repeats = property(repeats_get, repeats_set, repeats_del) # persistent property (wraps db_persistent) #@property def persistent_get(self): "Getter. Allows for value = self.persistent" return self.db_persistent #@persistent.setter def persistent_set(self, value): "Setter. Allows for self.persistent = value" self.db_persistent = value self.save() #@persistent.deleter def persistent_del(self): "Deleter. Allows for del self.persistent" self.db_persistent = False self.save() persistent = property(persistent_get, persistent_set, persistent_del) # is_active property (wraps db_is_active) #@property def is_active_get(self): "Getter. Allows for value = self.is_active" return self.db_is_active #@is_active.setter def is_active_set(self, value): "Setter. Allows for self.is_active = value" self.db_is_active = value self.save() #@is_active.deleter def is_active_del(self): "Deleter. Allows for del self.is_active" self.db_is_active = False self.save() is_active = property(is_active_get, is_active_set, is_active_del) # # # ScriptDB class properties # # # this is required to properly handle attributes and typeclass loading #attribute_model_path = "src.scripts.models" #attribute_model_name = "ScriptAttribute" typeclass_paths = settings.SCRIPT_TYPECLASS_PATHS attribute_class = ScriptAttribute # this is used by all typedobjects as a fallback try: default_typeclass_path = settings.BASE_SCRIPT_TYPECLASS except: default_typeclass_path = "src.scripts.scripts.DoNothing" def at_typeclass_error(self): """ If this is called, it means the typeclass has a critical error and cannot even be loaded. We don't allow a script to be created under those circumstances. Already created, permanent scripts are set to already be active so they won't get activated now (next reboot the bug might be fixed) """ # By setting is_active=True, we trick the script not to run "again". self.is_active = True return super(ScriptDB, self).at_typeclass_error() delete_iter = 0 def delete(self): if self.delete_iter > 0: return self.delete_iter += 1 super(ScriptDB, self).delete()
Python
""" This module contains the base Script class that all scripts are inheriting from. It also defines a few common scripts. """ from time import time from twisted.internet.defer import maybeDeferred from twisted.internet.task import LoopingCall from twisted.internet import task from src.server.sessionhandler import SESSIONS from src.typeclasses.typeclass import TypeClass from src.scripts.models import ScriptDB from src.comms import channelhandler from src.utils import logger # # Base script, inherit from Script below instead. # class ScriptClass(TypeClass): """ Base class for scripts """ # private methods def __eq__(self, other): """ This has to be located at this level, having it in the parent doesn't work. """ try: return other.id == self.id except Exception: return False def _start_task(self, start_now=True): "start task runner" self.ndb.twisted_task = LoopingCall(self._step_task) if self.ndb._paused_time: # we had paused the script, restarting #print " start with paused time:", self.key, self.ndb._paused_time self.ndb.twisted_task.start(self.ndb._paused_time, now=False) else: # starting script anew. #print "_start_task: self.interval:", self.key, self.dbobj.interval self.ndb.twisted_task.start(self.dbobj.interval, now=start_now and not self.start_delay) self.ndb.time_last_called = int(time()) def _stop_task(self): "stop task runner" try: #print "stopping twisted task:", id(self.ndb.twisted_task), self.obj if self.ndb.twisted_task and self.ndb.twisted_task.running: self.ndb.twisted_task.stop() except Exception: logger.log_trace() def _step_err_callback(self, e): "callback for runner errors" cname = self.__class__.__name__ estring = "Script %s(#%i) of type '%s': at_repeat() error '%s'." % (self.key, self.id, cname, e.getErrorMessage()) try: self.dbobj.db_obj.msg(estring) except Exception: pass logger.log_errmsg(estring) def _step_succ_callback(self): "step task runner. No try..except needed due to defer wrap." if not self.is_valid(): self.stop() return self.at_repeat() repeats = self.dbobj.db_repeats if repeats <= 0: pass # infinite repeat elif repeats == 1: self.stop() return else: self.dbobj.db_repeats -= 1 self.ndb.time_last_called = int(time()) self.save() if self.ndb._paused_time: # this means we were running an unpaused script, for the time remaining # after the pause. Now we start a normal-running timer again. #print "switching to normal run:", self.key del self.ndb._paused_time self._stop_task() self._start_task(start_now=False) def _step_task(self): "step task" try: d = maybeDeferred(self._step_succ_callback) d.addErrback(self._step_err_callback) return d except Exception: logger.log_trace() def time_until_next_repeat(self): """ Returns the time in seconds until the script will be run again. If this is not a stepping script, returns None. This is not used in any way by the script's stepping system; it's only here for the user to be able to check in on their scripts and when they will next be run. """ try: if self.ndb._paused_time: return max(0, (self.ndb.time_last_called + self.ndb._paused_time) - int(time())) else: return max(0, (self.ndb.time_last_called + self.dbobj.db_interval) - int(time())) except Exception: return None def start(self, force_restart=False): """ Called every time the script is started (for persistent scripts, this is usually once every server start) force_restart - if True, will always restart the script, regardless of if it has started before. returns 0 or 1 to indicated the script has been started or not. Used in counting. """ #print "Script %s (%s) start (active:%s, force:%s) ..." % (self.key, id(self.dbobj), # self.is_active, force_restart) if self.dbobj.is_active and not force_restart: # script already runs and should not be restarted. return 0 obj = self.obj if obj: # check so the scripted object is valid and initalized try: dummy = object.__getattribute__(obj, 'cmdset') except AttributeError: # this means the object is not initialized. self.dbobj.is_active = False return 0 # try to restart a paused script if self.unpause(): return 1 # try to start the script from scratch try: self.dbobj.is_active = True self.at_start() if self.dbobj.db_interval > 0: self._start_task() return 1 except Exception: logger.log_trace() self.dbobj.is_active = False return 0 def stop(self, kill=False): """ Called to stop the script from running. This also deletes the script. kill - don't call finishing hooks. """ #print "stopping script %s" % self.key #import pdb #pdb.set_trace() if not kill: try: self.at_stop() except Exception: logger.log_trace() if self.dbobj.db_interval > 0: try: self._stop_task() except Exception, e: logger.log_trace("Stopping script %s(%s)" % (self.key, self.id)) pass try: self.dbobj.delete() except AssertionError: logger.log_trace() return 0 return 1 def pause(self): """ This stops a running script and stores its active state. """ #print "pausing", self.key, self.time_until_next_repeat() dt = self.time_until_next_repeat() if dt == None: return self.db._paused_time = dt self._stop_task() def unpause(self): """ Restart a paused script. This WILL call at_start(). """ #print "unpausing", self.key, self.db._paused_time dt = self.db._paused_time if dt == None: return False try: self.dbobj.is_active = True self.at_start() self.ndb._paused_time = dt self._start_task(start_now=False) del self.db._paused_time except Exception, e: logger.log_trace() self.dbobj.is_active = False return False return True # hooks def at_script_creation(self): "placeholder" pass def is_valid(self): "placeholder" pass def at_start(self): "placeholder." pass def at_stop(self): "placeholder" pass def at_repeat(self): "placeholder" pass def at_init(self): "called when typeclass re-caches. Usually not used for scripts." pass # # Base Script - inherit from this # class Script(ScriptClass): """ This is the class you should inherit from, it implements the hooks called by the script machinery. """ def at_script_creation(self): """ Only called once, by the create function. """ self.key = "<unnamed>" self.desc = "" self.interval = 0 # infinite self.start_delay = False self.repeats = 0 # infinite self.persistent = False def is_valid(self): """ Is called to check if the script is valid to run at this time. Should return a boolean. The method is assumed to collect all needed information from its related self.obj. """ return True def at_start(self): """ Called whenever the script is started, which for persistent scripts is at least once every server start. It will also be called when starting again after a pause (such as after a server reload) """ pass def at_repeat(self): """ Called repeatedly if this Script is set to repeat regularly. """ pass def at_stop(self): """ Called whenever when it's time for this script to stop (either because is_valid returned False or ) """ pass def at_server_reload(self): """ This hook is called whenever the server is shutting down for restart/reboot. If you want to, for example, save non-persistent properties across a restart, this is the place to do it. """ pass def at_server_shutdown(self): """ This hook is called whenever the server is shutting down fully (i.e. not for a restart). """ pass # Some useful default Script types used by Evennia. class DoNothing(Script): "An script that does nothing. Used as default fallback." def at_script_creation(self): "Setup the script" self.key = "sys_do_nothing" self.desc = "This is a placeholder script." class CheckSessions(Script): "Check sessions regularly." def at_script_creation(self): "Setup the script" self.key = "sys_session_check" self.desc = "Checks sessions so they are live." self.interval = 60 # repeat every 60 seconds self.persistent = True def at_repeat(self): "called every 60 seconds" #print "session check!" #print "ValidateSessions run" SESSIONS.validate_sessions() class ValidateScripts(Script): "Check script validation regularly" def at_script_creation(self): "Setup the script" self.key = "sys_scripts_validate" self.desc = "Validates all scripts regularly." self.interval = 3600 # validate every hour. self.persistent = True def at_repeat(self): "called every hour" #print "ValidateScripts run." ScriptDB.objects.validate() class ValidateChannelHandler(Script): "Update the channelhandler to make sure it's in sync." def at_script_creation(self): "Setup the script" self.key = "sys_channels_validate" self.desc = "Updates the channel handler" self.interval = 3700 # validate a little later than ValidateScripts self.persistent = True def at_repeat(self): "called every hour+" #print "ValidateChannelHandler run." channelhandler.CHANNELHANDLER.update() class AddCmdSet(Script): """ This script permanently assigns a command set to an object whenever it is started. This is not used by the core system anymore, it's here mostly as an example. """ def at_script_creation(self): "Setup the script" if not self.key: self.key = "add_cmdset" if not self.desc: self.desc = "Adds a cmdset to an object." self.persistent = True # this needs to be assigned to upon creation. # It should be a string pointing to the right # cmdset module and cmdset class name, e.g. # 'examples.cmdset_redbutton.RedButtonCmdSet' # self.db.cmdset = <cmdset_path> # self.db.add_default = <bool> def at_start(self): "Get cmdset and assign it." cmdset = self.db.cmdset if cmdset: if self.db.add_default: self.obj.cmdset.add_default(cmdset) else: self.obj.cmdset.add(cmdset) def at_stop(self): """ This removes the cmdset when the script stops """ cmdset = self.db.cmdset if cmdset: if self.db.add_default: self.obj.cmdset.delete_default() else: self.obj.cmdset.delete(cmdset)
Python
""" The script handler makes sure to check through all stored scripts to make sure they are still relevant. An scripthandler is automatically added to all game objects. You access it through the property 'scripts' on the game object. """ from src.scripts.models import ScriptDB from src.utils import create from src.utils import logger class ScriptHandler(object): """ Implements the handler. This sits on each game object. """ def __init__(self, obj): """ Set up internal state. obj - a reference to the object this handler is attached to. We retrieve all scripts attached to this object and check if they are all peristent. If they are not, they are just cruft left over from a server shutdown. """ self.obj = obj def __str__(self): "List the scripts tied to this object" scripts = ScriptDB.objects.get_all_scripts_on_obj(self.obj) string = "" for script in scripts: interval = "inf" next_repeat = "inf" repeats = "inf" if script.interval > 0: interval = script.interval if script.repeats: repeats = script.repeats try: next_repeat = script.time_until_next_repeat() except: next_repeat = "?" string += "\n '%s' (%s/%s, %s repeats): %s" % (script.key, next_repeat, interval, repeats, script.desc) return string.strip() def add(self, scriptclass, key=None, autostart=True): """ Add an script to this object. scriptclass - either a class object inheriting from Script, an instantiated script object or a python path to such a class object. key - optional identifier for the script (often set in script definition) autostart - start the script upon adding it """ script = create.create_script(scriptclass, key=key, obj=self.obj, autostart=autostart) if not script: logger.log_errmsg("Script %s could not be created and/or started." % scriptclass) return False return True def start(self, scriptid): """ Find an already added script and force-start it """ scripts = ScriptDB.objects.get_all_scripts_on_obj(self.obj, key=scriptid) num = 0 for script in scripts: num += script.start() return num def delete(self, scriptid): """ Forcibly delete a script from this object. scriptid can be a script key or the path to a script (in the latter case all scripts with this path will be deleted!) """ delscripts = ScriptDB.objects.get_all_scripts_on_obj(self.obj, key=scriptid) if not delscripts: delscripts = [script for script in ScriptDB.objects.get_all_scripts_on_obj(self.obj) if script.path == scriptid] num = 0 for script in delscripts: num += script.stop() return num def stop(self, scriptid): """ Alias for delete. scriptid can be a script key or a script path string. """ return self.delete(scriptid) def all(self, scriptid=None): """ Get all scripts stored in the handler, alternatively all matching a key. """ return ScriptDB.objects.get_all_scripts_on_obj(self.obj, key=scriptid) def validate(self, init_mode=False): """ Runs a validation on this object's scripts only. This should be called regularly to crank the wheels. """ ScriptDB.objects.validate(obj=self.obj, init_mode=init_mode)
Python
# # This sets up how models are displayed # in the web admin interface. # from django.contrib import admin from src.comms.models import Channel, Msg, PlayerChannelConnection, ExternalChannelConnection class MsgAdmin(admin.ModelAdmin): list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers', 'db_channels', 'db_message', 'db_lock_storage') list_display_links = ("id",) ordering = ["db_date_sent", 'db_sender', 'db_receivers', 'db_channels'] #readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels'] search_fields = ['id', '^db_date_sent', '^db_message'] save_as = True save_on_top = True list_select_related = True #admin.site.register(Msg, MsgAdmin) class PlayerChannelConnectionInline(admin.TabularInline): model = PlayerChannelConnection fieldsets = ( (None, { 'fields':(('db_player', 'db_channel')), 'classes':('collapse',)}),) extra = 1 class ExternalChannelConnectionInline(admin.StackedInline): model = ExternalChannelConnection fieldsets = ( (None, { 'fields':(('db_is_enabled','db_external_key', 'db_channel'), 'db_external_send_code', 'db_external_config'), 'classes':('collapse',) }),) extra = 1 class ChannelAdmin(admin.ModelAdmin): inlines = (PlayerChannelConnectionInline, ExternalChannelConnectionInline) list_display = ('id', 'db_key', 'db_desc', 'db_aliases', 'db_keep_log', 'db_lock_storage') list_display_links = ("id", 'db_key') ordering = ["db_key"] search_fields = ['id', 'db_key', 'db_aliases'] save_as = True save_on_top = True list_select_related = True fieldsets = ( (None, {'fields':(('db_key', 'db_aliases', 'db_desc'),'db_lock_storage', 'db_keep_log')}), ) admin.site.register(Channel, ChannelAdmin) # class PlayerChannelConnectionAdmin(admin.ModelAdmin): # list_display = ('db_channel', 'db_player') # list_display_links = ("db_player", 'db_channel') # ordering = ["db_channel"] # search_fields = ['db_channel', 'db_player'] # save_as = True # save_on_top = True # list_select_related = True # admin.site.register(PlayerChannelConnection, PlayerChannelConnectionAdmin) # class ExternalChannelConnectionAdmin(admin.ModelAdmin): # list_display = ('db_channel', 'db_external_key', 'db_external_config') # list_display_links = ("db_channel", 'db_external_key', 'db_external_config') # ordering = ["db_channel"] # search_fields = ['db_channel', 'db_external_key'] # save_as = True # save_on_top = True # list_select_related = True # admin.site.register(ExternalChannelConnection, ExternalChannelConnectionAdmin)
Python
""" The channel handler handles the stored set of channels and how they are represented against the cmdhandler. If there is a channel named 'newbie', we want to be able to just write > newbie Hello! For this to work, 'newbie', the name of the channel, must be identified by the cmdhandler as a command name. The channelhandler stores all channels as custom 'commands' that the cmdhandler can import and look through. Warning - channel names take precedence over command names, so make sure to not pick clashing channel names. Unless deleting a channel you normally don't need to bother about the channelhandler at all - the create_channel method handles the update. To delete a channel cleanly, delete the channel object, then call update() on the channelhandler. Or use Channel.objects.delete() which does this for you. """ from src.comms.models import Channel, Msg from src.commands import cmdset, command from src.utils import utils class ChannelCommand(command.Command): """ Channel Usage: <channel name or alias> <message> This is a channel. If you have subscribed to it, you can send to it by entering its name or alias, followed by the text you want to send. """ # this flag is what identifies this cmd as a channel cmd # and branches off to the system send-to-channel command # (which is customizable by admin) is_channel = True key = "general" help_category = "Channel Names" locks = "cmd:all()" obj = None def parse(self): """ Simple parser """ channelname, msg = self.args.split(":", 1) # cmdhandler sends channame:msg here. self.args = (channelname.strip(), msg.strip()) def func(self): """ Create a new message and send it to channel, using the already formatted input. """ channelkey, msg = self.args caller = self.caller if not msg: caller.msg("Say what?") return channel = Channel.objects.get_channel(channelkey) if not channel: caller.msg("Channel '%s' not found." % channelkey) return if not channel.has_connection(caller): string = "You are not connected to channel '%s'." caller.msg(string % channelkey) return if not channel.access(caller, 'send'): string = "You are not permitted to send to channel '%s'." caller.msg(string % channelkey) return msg = "[%s] %s: %s" % (channel.key, caller.name, msg) # we can't use the utils.create function to make the Msg, # since that creates an import recursive loop. try: sender = caller.player except AttributeError: # this could happen if a player is calling directly. sender = caller.dbobj msgobj = Msg(db_sender=sender, db_message=msg) msgobj.save() msgobj.channels = channel # send new message object to channel channel.msg(msgobj, from_obj=sender) class ChannelHandler(object): """ Handles the set of commands related to channels. """ def __init__(self): self.cached_channel_cmds = [] def __str__(self): return ", ".join(str(cmd) for cmd in self.cached_channel_cmds) def clear(self): """ Reset the cache storage. """ self.cached_channel_cmds = [] def _format_help(self, channel): "builds a doc string" key = channel.key aliases = channel.aliases if not utils.is_iter(aliases): aliases = [aliases] ustring = "%s <message>" % key.lower() + "".join(["\n %s <message>" % alias.lower() for alias in aliases]) desc = channel.desc string = \ """ Channel '%s' Usage (not including your personal aliases): %s %s """ % (key, ustring, desc) return string def add_channel(self, channel): """ Add an individual channel to the handler. This should be called whenever a new channel is created. To remove a channel, simply delete the channel object and run self.update on the handler. """ # map the channel to a searchable command cmd = ChannelCommand() cmd.key = channel.key.strip().lower() cmd.obj = channel cmd.__doc__= self._format_help(channel) if channel.aliases: cmd.aliases = channel.aliases cmd.lock_storage = "cmd:all();%s" % channel.locks cmd.lockhandler.reset() self.cached_channel_cmds.append(cmd) def update(self): "Updates the handler completely." self.cached_channel_cmds = [] for channel in Channel.objects.all(): self.add_channel(channel) def get_cmdset(self, source_object): """ Retrieve cmdset for channels this source_object has access to send to. """ # create a temporary cmdset holding all channels chan_cmdset = cmdset.CmdSet() chan_cmdset.key = '_channelset' chan_cmdset.priority = 10 chan_cmdset.duplicates = True for cmd in [cmd for cmd in self.cached_channel_cmds if cmd.access(source_object, 'listen')]: chan_cmdset.add(cmd) return chan_cmdset CHANNELHANDLER = ChannelHandler()
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'ExternalChannelConnection.db_external_path' db.delete_column('comms_externalchannelconnection', 'db_external_path') # Adding field 'ExternalChannelConnection.db_external_send_code' db.add_column('comms_externalchannelconnection', 'db_external_send_code', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False) def backwards(self, orm): # User chose to not deal with backwards NULL issues for 'ExternalChannelConnection.db_external_path' raise RuntimeError("Cannot reverse this migration. 'ExternalChannelConnection.db_external_path' and its values cannot be restored.") # Deleting field 'ExternalChannelConnection.db_external_send_code' db.delete_column('comms_externalchannelconnection', 'db_external_send_code') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'comms.channel': { 'Meta': {'object_name': 'Channel'}, 'db_aliases': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'}), 'db_keep_log': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.externalchannelconnection': { 'Meta': {'object_name': 'ExternalChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_external_config': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_external_key': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'db_external_send_code': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_is_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.msg': { 'Meta': {'object_name': 'Msg'}, 'db_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_sent': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_hide_from_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_sender': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_message': ('django.db.models.fields.TextField', [], {}), 'db_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_sender': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sender_set'", 'null': 'True', 'to': "orm['players.PlayerDB']"}), 'db_sender_external': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.playerchannelconnection': { 'Meta': {'object_name': 'PlayerChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['comms']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Channel.db_lock_storage' db.alter_column('comms_channel', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512)) # Changing field 'Msg.db_lock_storage' db.alter_column('comms_msg', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(default='', max_length=512)) def backwards(self, orm): # Changing field 'Channel.db_lock_storage' db.alter_column('comms_channel', 'db_lock_storage', self.gf('django.db.models.fields.TextField')()) # Changing field 'Msg.db_lock_storage' db.alter_column('comms_msg', 'db_lock_storage', self.gf('django.db.models.fields.TextField')(null=True)) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'comms.channel': { 'Meta': {'object_name': 'Channel'}, 'db_aliases': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'}), 'db_keep_log': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.externalchannelconnection': { 'Meta': {'object_name': 'ExternalChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_external_config': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_external_key': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'db_external_send_code': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_is_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.msg': { 'Meta': {'object_name': 'Msg'}, 'db_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_sent': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_hide_from_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_sender': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_message': ('django.db.models.fields.TextField', [], {}), 'db_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_sender': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sender_set'", 'null': 'True', 'to': "orm['players.PlayerDB']"}), 'db_sender_external': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.playerchannelconnection': { 'Meta': {'object_name': 'PlayerChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['comms']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): #depends_on = ( # ("players", "0001_initial"), # ("comms", "0001_initial"), #) def forwards(self, orm): # Adding model 'Msg' db.create_table('comms_msg', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_sender', self.gf('django.db.models.fields.related.ForeignKey')(related_name='sender_set', to=orm['players.PlayerDB'])), ('db_receivers', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('db_channels', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('db_message', self.gf('django.db.models.fields.TextField')()), ('db_date_sent', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('db_hide_from_sender', self.gf('django.db.models.fields.BooleanField')(default=False)), ('db_hide_from_receivers', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('db_hide_from_channels', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('db_lock_storage', self.gf('django.db.models.fields.TextField')(null=True)), )) db.send_create_signal('comms', ['Msg']) # Adding model 'Channel' db.create_table('comms_channel', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_key', self.gf('django.db.models.fields.CharField')(unique=True, max_length=255)), ('db_desc', self.gf('django.db.models.fields.CharField')(max_length=80, null=True, blank=True)), ('db_aliases', self.gf('django.db.models.fields.CharField')(max_length=255)), ('db_keep_log', self.gf('django.db.models.fields.BooleanField')(default=True)), ('db_lock_storage', self.gf('django.db.models.fields.TextField')(blank=True)), )) db.send_create_signal('comms', ['Channel']) # Adding model 'ChannelConnection' db.create_table('comms_channelconnection', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_player', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['players.PlayerDB'])), ('db_channel', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['comms.Channel'])), )) db.send_create_signal('comms', ['ChannelConnection']) def backwards(self, orm): # Deleting model 'Msg' db.delete_table('comms_msg') # Deleting model 'Channel' db.delete_table('comms_channel') # Deleting model 'ChannelConnection' db.delete_table('comms_channelconnection') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'comms.channel': { 'Meta': {'object_name': 'Channel'}, 'db_aliases': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'}), 'db_keep_log': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.channelconnection': { 'Meta': {'object_name': 'ChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.msg': { 'Meta': {'object_name': 'Msg'}, 'db_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_sent': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_hide_from_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_sender': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_message': ('django.db.models.fields.TextField', [], {}), 'db_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_sender': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sender_set'", 'to': "orm['players.PlayerDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['comms']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ExternalChannelConnection' db.create_table('comms_externalchannelconnection', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('db_channel', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['comms.Channel'])), ('db_external_key', self.gf('django.db.models.fields.CharField')(max_length=128)), ('db_external_path', self.gf('django.db.models.fields.CharField')(max_length=128)), ('db_external_config', self.gf('django.db.models.fields.TextField')(blank=True)), ('db_is_enabled', self.gf('django.db.models.fields.BooleanField')(default=True)), )) db.send_create_signal('comms', ['ExternalChannelConnection']) db.rename_table('comms_channelconnection', 'comms_playerchannelconnection') # # Adding model 'PlayerChannelConnection' # db.create_table('comms_playerchannelconnection', ( # ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), # ('db_player', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['players.PlayerDB'])), # ('db_channel', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['comms.Channel'])), # )) # db.send_create_signal('comms', ['PlayerChannelConnection']) # # move channelconnections to playerchannelconnections # for conn in orm.ChannelConnection.objects.all(): # ncon = orm.PlayerChannelConnection(db_player=conn.db_player, db_channel=conn.db_channel) # ncon.save() # db # # Deleting model 'ChannelConnection' # db.delete_table('comms_channelconnection') # Adding field 'Msg.db_sender_external' db.add_column('comms_msg', 'db_sender_external', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True), keep_default=False) # Changing field 'Msg.db_sender' db.alter_column('comms_msg', 'db_sender_id', self.gf('django.db.models.fields.related.ForeignKey')(null=True, to=orm['players.PlayerDB'])) def backwards(self, orm): # # Adding model 'ChannelConnection' # db.create_table('comms_channelconnection', ( # ('db_channel', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['comms.Channel'])), # ('db_player', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['players.PlayerDB'])), # ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), # )) # db.send_create_signal('comms', ['ChannelConnection']) # db.rename_table('comms_playerchannelconnection', 'comms_channelconnection') # Deleting model 'ExternalChannelConnection' db.delete_table('comms_externalchannelconnection') # # Deleting model 'PlayerChannelConnection' # db.delete_table('comms_playerchannelconnection') # Deleting field 'Msg.db_sender_external' db.delete_column('comms_msg', 'db_sender_external') # User chose to not deal with backwards NULL issues for 'Msg.db_sender' raise RuntimeError("Cannot reverse this migration. 'Msg.db_sender' and its values cannot be restored.") models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'comms.channel': { 'Meta': {'object_name': 'Channel'}, 'db_aliases': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'}), 'db_keep_log': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.externalchannelconnection': { 'Meta': {'object_name': 'ExternalChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_external_config': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_external_key': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'db_external_path': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'db_is_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.msg': { 'Meta': {'object_name': 'Msg'}, 'db_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_sent': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_hide_from_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_sender': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_message': ('django.db.models.fields.TextField', [], {}), 'db_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_sender': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sender_set'", 'null': 'True', 'to': "orm['players.PlayerDB']"}), 'db_sender_external': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.playerchannelconnection': { 'Meta': {'object_name': 'PlayerChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['comms']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding index on 'Channel', fields ['db_key'] db.create_index('comms_channel', ['db_key']) def backwards(self, orm): # Removing index on 'Channel', fields ['db_key'] db.delete_index('comms_channel', ['db_key']) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'comms.channel': { 'Meta': {'object_name': 'Channel'}, 'db_aliases': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'}), 'db_keep_log': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.externalchannelconnection': { 'Meta': {'object_name': 'ExternalChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_external_config': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_external_key': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'db_external_send_code': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_is_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.msg': { 'Meta': {'object_name': 'Msg'}, 'db_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_sent': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_hide_from_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_sender': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_message': ('django.db.models.fields.TextField', [], {}), 'db_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_sender': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sender_set'", 'null': 'True', 'to': "orm['players.PlayerDB']"}), 'db_sender_external': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.playerchannelconnection': { 'Meta': {'object_name': 'PlayerChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'db_lock_storage': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['comms']
Python
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): # fixes a changed syntax in the locks. def forwards(self, orm): "Write your forwards methods here." for channel in orm.Channel.objects.all(): lockstring = channel.db_lock_storage lockstring = lockstring.replace("admin:", "control:") channel.db_lock_storage = lockstring channel.save() def backwards(self, orm): "Write your backwards methods here." for channel in orm.Channel.objects.all(): lockstring = channel.db_lock_storage lockstring = lockstring.replace("control:", "admin:") channel.db_lock_storage = lockstring channel.save() models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'comms.channel': { 'Meta': {'object_name': 'Channel'}, 'db_aliases': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'}), 'db_keep_log': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.externalchannelconnection': { 'Meta': {'object_name': 'ExternalChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_external_config': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_external_key': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'db_external_send_code': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_is_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.msg': { 'Meta': {'object_name': 'Msg'}, 'db_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_date_sent': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_hide_from_channels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_hide_from_sender': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_message': ('django.db.models.fields.TextField', [], {}), 'db_receivers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_sender': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sender_set'", 'null': 'True', 'to': "orm['players.PlayerDB']"}), 'db_sender_external': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'comms.playerchannelconnection': { 'Meta': {'object_name': 'PlayerChannelConnection'}, 'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'objects.objectdb': { 'Meta': {'object_name': 'ObjectDB'}, 'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'players.playerdb': { 'Meta': {'object_name': 'PlayerDB'}, 'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}), 'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['comms']
Python
""" Models for the comsystem. The comsystem's main component is the Message, which carries the actual information between two parties. Msgs are stored in the database and usually not deleted. A Msg always have one sender (a user), but can have any number targets, both users and channels. Channels are central objects that act as targets for Msgs. Players can connect to channels by use of a ChannelConnect object (this object is necessary to easily be able to delete connections on the fly). """ from django.db import models from src.utils.idmapper.models import SharedMemoryModel from src.comms import managers from src.locks.lockhandler import LockHandler from src.utils import logger from src.utils.utils import is_iter, to_str from src.utils.utils import dbref as is_dbref #------------------------------------------------------------ # # Utils # #------------------------------------------------------------ def obj_to_id(inp): """ Converts input object to an id string. """ dbref = is_dbref(inp) if dbref: return str(dbref) if hasattr(inp, 'id'): return str(inp.id) if hasattr(inp, 'dbobj') and hasattr(inp.dbobj, 'id'): return str(inp.dbobj.id) return str(inp) def id_to_obj(dbref, db_model='PlayerDB'): """ loads from dbref to object. Uses the db_model to search for the id. """ if db_model == 'PlayerDB': from src.players.models import PlayerDB as db_model else: db_model = Channel try: dbref = int(dbref.strip()) return db_model.objects.get(id=dbref) except Exception: return None #------------------------------------------------------------ # # Msg # #------------------------------------------------------------ class Msg(SharedMemoryModel): """ A single message. This model describes all ooc messages sent in-game, both to channels and between players. The Msg class defines the following properties: sender - sender of message receivers - list of target objects for message channels - list of channels message was sent to message - the text being sent date_sent - time message was sent hide_from_sender - bool if message should be hidden from sender hide_from_receivers - list of receiver objects to hide message from hide_from_channels - list of channels objects to hide message from permissions - perm strings """ # # Msg database model setup # # # These databse fields are all set using their corresponding properties, # named same as the field, but withtout the db_* prefix. # There must always be one sender of the message. db_sender = models.ForeignKey("players.PlayerDB", related_name='sender_set', null=True, verbose_name='sender') # in the case of external senders, no Player object might be available db_sender_external = models.CharField('external sender', max_length=255, null=True, blank=True, help_text="identifier for external sender, for example a sender over an IRC connection (i.e. someone who doesn't have an exixtence in-game).") # The destination objects of this message. Stored as a # comma-separated string of object dbrefs. Can be defined along # with channels below. db_receivers = models.CharField('receivers', max_length=255, null=True, blank=True, help_text='comma-separated list of object dbrefs this message is aimed at.') # The channels this message was sent to. Stored as a # comma-separated string of channel dbrefs. A message can both # have channel targets and destination objects. db_channels = models.CharField('channels', max_length=255, null=True, blank=True, help_text='comma-separated list of channel dbrefs this message is aimed at.') # The actual message and a timestamp. The message field # should itself handle eventual headers etc. db_message = models.TextField('messsage') db_date_sent = models.DateTimeField('date sent', editable=False, auto_now_add=True) # lock storage db_lock_storage = models.CharField('locks', max_length=512, blank=True, help_text='access locks on this message.') # These are settable by senders/receivers/channels respectively. # Stored as a comma-separated string of dbrefs. Can be used by the # game to mask out messages from being visible in the archive (no # messages are actually deleted) db_hide_from_sender = models.BooleanField(default=False) db_hide_from_receivers = models.CharField(max_length=255, null=True, blank=True) db_hide_from_channels = models.CharField(max_length=255, null=True, blank=True) # Storage of lock strings #db_lock_storage = models.TextField(null=True) # Database manager objects = managers.MsgManager() def __init__(self, *args, **kwargs): SharedMemoryModel.__init__(self, *args, **kwargs) self.locks = LockHandler(self) class Meta: "Define Django meta options" verbose_name = "Message" # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that allows the user to do self.attr = value, # value = self.attr and del self.attr respectively (where self # is the object in question). # sender property (wraps db_sender) #@property def sender_get(self): "Getter. Allows for value = self.sender" return self.db_sender #@sender.setter def sender_set(self, value): "Setter. Allows for self.sender = value" self.db_sender = value self.save() #@sender.deleter def sender_del(self): "Deleter. Allows for del self.sender" raise Exception("You cannot delete the sender of a message!") sender = property(sender_get, sender_set, sender_del) # sender_external property (wraps db_sender_external) #@property def sender_external_get(self): "Getter. Allows for value = self.sender_external" return self.db_sender_external #@sender_external.setter def sender_external_set(self, value): "Setter. Allows for self.sender_external = value" self.db_sender_external = value self.save() #@sender_external.deleter def sender_external_del(self): "Deleter. Allows for del self.sender_external" raise Exception("You cannot delete the sender_external of a message!") sender_external = property(sender_external_get, sender_external_set, sender_external_del) # receivers property #@property def receivers_get(self): "Getter. Allows for value = self.receivers. Returns a list of receivers." if self.db_receivers: return [id_to_obj(dbref) for dbref in self.db_receivers.split(',')] return [] #@receivers.setter def receivers_set(self, value): "Setter. Allows for self.receivers = value. Stores as a comma-separated string." if is_iter(value): value = ",".join([obj_to_id(val) for val in value]) self.db_receivers = obj_to_id(value) self.save() #@receivers.deleter def receivers_del(self): "Deleter. Allows for del self.receivers" self.db_receivers = "" self.save() receivers = property(receivers_get, receivers_set, receivers_del) # channels property #@property def channels_get(self): "Getter. Allows for value = self.channels. Returns a list of channels." if self.db_channels: return [id_to_obj(dbref, 'Channel') for dbref in self.db_channels.split(',')] return [] #@channels.setter def channels_set(self, value): "Setter. Allows for self.channels = value. Stores as a comma-separated string." if is_iter(value): value = ",".join([obj_to_id(val) for val in value]) self.db_channels = obj_to_id(value) self.save() #@channels.deleter def channels_del(self): "Deleter. Allows for del self.channels" self.db_channels = "" self.save() channels = property(channels_get, channels_set, channels_del) # message property (wraps db_message) #@property def message_get(self): "Getter. Allows for value = self.message" return self.db_message #@message.setter def message_set(self, value): "Setter. Allows for self.message = value" self.db_message = value self.save() #@message.deleter def message_del(self): "Deleter. Allows for del self.message" self.db_message = "" self.save() message = property(message_get, message_set, message_del) # date_sent property (wraps db_date_sent) #@property def date_sent_get(self): "Getter. Allows for value = self.date_sent" return self.db_date_sent #@date_sent.setter def date_sent_set(self, value): "Setter. Allows for self.date_sent = value" raise Exception("You cannot edit date_sent!") #@date_sent.deleter def date_sent_del(self): "Deleter. Allows for del self.date_sent" raise Exception("You cannot delete the date_sent property!") date_sent = property(date_sent_get, date_sent_set, date_sent_del) # hide_from_sender property #@property def hide_from_sender_get(self): "Getter. Allows for value = self.hide_from_sender." return self.db_hide_from_sender #@hide_from_sender.setter def hide_from_sender_set(self, value): "Setter. Allows for self.hide_from_senders = value." self.db_hide_from_sender = value self.save() #@hide_from_sender.deleter def hide_from_sender_del(self): "Deleter. Allows for del self.hide_from_senders" self.db_hide_from_sender = False self.save() hide_from_sender = property(hide_from_sender_get, hide_from_sender_set, hide_from_sender_del) # hide_from_receivers property #@property def hide_from_receivers_get(self): "Getter. Allows for value = self.hide_from_receivers. Returns a list of hide_from_receivers." if self.db_hide_from_receivers: return [id_to_obj(dbref) for dbref in self.db_hide_from_receivers.split(',')] return [] #@hide_from_receivers.setter def hide_from_receivers_set(self, value): "Setter. Allows for self.hide_from_receivers = value. Stores as a comma-separated string." if is_iter(value): value = ",".join([obj_to_id(val) for val in value]) self.db_hide_from_receivers = obj_to_id(value) self.save() #@hide_from_receivers.deleter def hide_from_receivers_del(self): "Deleter. Allows for del self.hide_from_receivers" self.db_hide_from_receivers = "" self.save() hide_from_receivers = property(hide_from_receivers_get, hide_from_receivers_set, hide_from_receivers_del) # hide_from_channels property #@property def hide_from_channels_get(self): "Getter. Allows for value = self.hide_from_channels. Returns a list of hide_from_channels." if self.db_hide_from_channels: return [id_to_obj(dbref) for dbref in self.db_hide_from_channels.split(',')] return [] #@hide_from_channels.setter def hide_from_channels_set(self, value): "Setter. Allows for self.hide_from_channels = value. Stores as a comma-separated string." if is_iter(value): value = ",".join([obj_to_id(val) for val in value]) self.db_hide_from_channels = obj_to_id(value) self.save() #@hide_from_channels.deleter def hide_from_channels_del(self): "Deleter. Allows for del self.hide_from_channels" self.db_hide_from_channels = "" self.save() hide_from_channels = property(hide_from_channels_get, hide_from_channels_set, hide_from_channels_del) # lock_storage property (wraps db_lock_storage) #@property def lock_storage_get(self): "Getter. Allows for value = self.lock_storage" return self.db_lock_storage #@nick.setter def lock_storage_set(self, value): """Saves the lock_storagetodate. This is usually not called directly, but through self.lock()""" self.db_lock_storage = value self.save() #@nick.deleter def lock_storage_del(self): "Deleter is disabled. Use the lockhandler.delete (self.lock.delete) instead""" logger.log_errmsg("Lock_Storage (on %s) cannot be deleted. Use obj.lock.delete() instead." % self) lock_storage = property(lock_storage_get, lock_storage_set, lock_storage_del) # # Msg class methods # def __str__(self): "Print text" if self.channels: return "%s -> %s: %s" % (self.sender.key, ", ".join([chan.key for chan in self.channels]), self.message) else: return "%s -> %s: %s" % (self.sender.key, ", ".join([rec.key for rec in self.receivers]), self.message) def access(self, accessing_obj, access_type='read', default=False): """ Determines if another object has permission to access. accessing_obj - object trying to access this one access_type - type of access sought default - what to return if no lock of access_type was found """ return self.locks.check(accessing_obj, access_type=access_type, default=default) #------------------------------------------------------------ # # TempMsg # #------------------------------------------------------------ class TempMsg(object): """ This is a non-persistent object for sending temporary messages that will not be stored. It mimics the "real" Msg object, but don't require sender to be given. """ def __init__(self, sender=None, receivers=[], channels=[], message="", permissions=[]): self.sender = sender self.receivers = receivers self.message = message self.permissions = permissions self.hide_from_sender = False self.hide_from_sender = receivers = False self.hide_from_channels = False #------------------------------------------------------------ # # Channel # #------------------------------------------------------------ class Channel(SharedMemoryModel): """ This is the basis of a comm channel, only implementing the very basics of distributing messages. The Channel class defines the following properties: key - main name for channel desc - optional description of channel aliases - alternative names for the channel keep_log - bool if the channel should remember messages permissions - perm strings """ # # Channel database model setup # # # These databse fields are all set using their corresponding properties, # named same as the field, but withtout the db_* prefix. # unique identifier for this channel db_key = models.CharField('key', max_length=255, unique=True, db_index=True) # optional description of channel db_desc = models.CharField('description', max_length=80, blank=True, null=True) # aliases for the channel. These are searched by cmdhandler # as well to determine if a command is the name of a channel. # Several aliases are separated by commas. db_aliases = models.CharField('aliases', max_length=255) # Whether this channel should remember its past messages db_keep_log = models.BooleanField(default=True) # Storage of lock definitions db_lock_storage = models.CharField('locks', max_length=512, blank=True) # Database manager objects = managers.ChannelManager() class Meta: "Define Django meta options" verbose_name = "Channel" def __init__(self, *args, **kwargs): SharedMemoryModel.__init__(self, *args, **kwargs) self.locks = LockHandler(self) # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that allows the user to do self.attr = value, # value = self.attr and del self.attr respectively (where self # is the object in question). # key property (wraps db_key) #@property def key_get(self): "Getter. Allows for value = self.key" return self.db_key #@key.setter def key_set(self, value): "Setter. Allows for self.key = value" self.db_key = value self.save() #@key.deleter def key_del(self): "Deleter. Allows for del self.key" raise Exception("You cannot delete the channel key!") key = property(key_get, key_set, key_del) # desc property (wraps db_desc) #@property def desc_get(self): "Getter. Allows for value = self.desc" return self.db_desc #@desc.setter def desc_set(self, value): "Setter. Allows for self.desc = value" self.db_desc = value self.save() #@desc.deleter def desc_del(self): "Deleter. Allows for del self.desc" self.db_desc = "" self.save() desc = property(desc_get, desc_set, desc_del) # aliases property #@property def aliases_get(self): "Getter. Allows for value = self.aliases. Returns a list of aliases." if self.db_aliases: return [perm.strip() for perm in self.db_aliases.split(',')] return [] #@aliases.setter def aliases_set(self, value): "Setter. Allows for self.aliases = value. Stores as a comma-separated string." if is_iter(value): value = ",".join([str(val).strip().lower() for val in value]) self.db_aliases = value self.save() #@aliases_del.deleter def aliases_del(self): "Deleter. Allows for del self.aliases" self.db_aliases = "" self.save() aliases = property(aliases_get, aliases_set, aliases_del) # keep_log property (wraps db_keep_log) #@property def keep_log_get(self): "Getter. Allows for value = self.keep_log" return self.db_keep_log #@keep_log.setter def keep_log_set(self, value): "Setter. Allows for self.keep_log = value" self.db_keep_log = value self.save() #@keep_log.deleter def keep_log_del(self): "Deleter. Allows for del self.keep_log" self.db_keep_log = False self.save() keep_log = property(keep_log_get, keep_log_set, keep_log_del) # lock_storage property (wraps db_lock_storage) #@property def lock_storage_get(self): "Getter. Allows for value = self.lock_storage" return self.db_lock_storage #@nick.setter def lock_storage_set(self, value): """Saves the lock_storagetodate. This is usually not called directly, but through self.lock()""" self.db_lock_storage = value self.save() #@nick.deleter def lock_storage_del(self): "Deleter is disabled. Use the lockhandler.delete (self.lock.delete) instead""" logger.log_errmsg("Lock_Storage (on %s) cannot be deleted. Use obj.lock.delete() instead." % self) lock_storage = property(lock_storage_get, lock_storage_set, lock_storage_del) class Meta: "Define Django meta options" verbose_name = "Channel" verbose_name_plural = "Channels" # # Channel class methods # def __str__(self): return "Channel '%s' (%s)" % (self.key, self.desc) def has_connection(self, player): """ Checks so this player is actually listening to this channel. """ return PlayerChannelConnection.objects.has_connection(player, self) def msg(self, msgobj, from_obj=None): """ Send the given message to all players connected to channel. Note that no permission-checking is done here; it is assumed to have been done before calling this method. msgobj - a Msg instance or a message string. In the latter case a Msg will be created. from_obj - if msgobj is not an Msg-instance, this is used to create a message on the fly. If from_obj is None, no Msg object will be created and the message will be sent without being logged. """ if isinstance(msgobj, basestring): # given msgobj is a string if from_obj: if isinstance(from_obj, basestring): msgobj = Msg(db_sender_external=from_obj, db_message=msgobj) else: msgobj = Msg(db_sender=from_obj, db_message=msgobj) # try to use msgobj.save() msgobj.channels = [self] msg = msgobj.message else: # this just sends a message, without any sender # (and without storing it in a persistent Msg object) msg = to_str(msgobj) else: msg = msgobj.message # get all players connected to this channel and send to them for conn in Channel.objects.get_all_connections(self): try: conn.player.msg(msg, from_obj) except AttributeError: try: conn.to_external(msg, from_obj, from_channel=self) except Exception: logger.log_trace("Cannot send msg to connection '%s'" % conn) return True def tempmsg(self, message): """ A wrapper for sending non-persistent messages. Nothing will be stored in the database. message - a Msg object or a text string. """ if type(msgobj) == Msg: # extract only the string message = message.message return self.msg(message) def connect_to(self, player): "Connect the user to this channel" if not self.access(player, 'listen'): return False conn = PlayerChannelConnection.objects.create_connection(player, self) if conn: return True return False def disconnect_from(self, player): "Disconnect user from this channel." PlayerChannelConnection.objects.break_connection(player, self) def delete(self): "Clean out all connections to this channel and delete it." for connection in Channel.objects.get_all_connections(self): connection.delete() super(Channel, self).delete() def access(self, accessing_obj, access_type='listen', default=False): """ Determines if another object has permission to access. accessing_obj - object trying to access this one access_type - type of access sought default - what to return if no lock of access_type was found """ return self.locks.check(accessing_obj, access_type=access_type, default=default) class PlayerChannelConnection(SharedMemoryModel): """ This connects a player object to a particular comm channel. The advantage of making it like this is that one can easily break the connection just by deleting this object. """ # Player connected to a channel db_player = models.ForeignKey("players.PlayerDB", verbose_name='player') # Channel the player is connected to db_channel = models.ForeignKey(Channel, verbose_name='channel') # Database manager objects = managers.PlayerChannelConnectionManager() # player property (wraps db_player) #@property def player_get(self): "Getter. Allows for value = self.player" return self.db_player #@player.setter def player_set(self, value): "Setter. Allows for self.player = value" self.db_player = value self.save() #@player.deleter def player_del(self): "Deleter. Allows for del self.player. Deletes connection." self.delete() player = property(player_get, player_set, player_del) # channel property (wraps db_channel) #@property def channel_get(self): "Getter. Allows for value = self.channel" return self.db_channel #@channel.setter def channel_set(self, value): "Setter. Allows for self.channel = value" self.db_channel = value self.save() #@channel.deleter def channel_del(self): "Deleter. Allows for del self.channel. Deletes connection." self.delete() channel = property(channel_get, channel_set, channel_del) def __str__(self): return "Connection Player '%s' <-> %s" % (self.player, self.channel) class Meta: "Define Django meta options" verbose_name = "Channel<->Player link" verbose_name_plural = "Channel<->Player links" class ExternalChannelConnection(SharedMemoryModel): """ This defines an external protocol connecting to a channel, while storing some critical info about that connection. """ # evennia channel connecting to db_channel = models.ForeignKey(Channel, verbose_name='channel', help_text='which channel this connection is tied to.') # external connection identifier db_external_key = models.CharField('external key', max_length=128, help_text='external connection identifier, used by calling protocol.') # eval-code to use when the channel tries to send a message # to the external protocol. db_external_send_code = models.TextField('executable code', blank=True, help_text='this is a custom snippet of Python code to connect the external protocol to the in-game channel.') # custom config for the connection db_external_config = models.TextField('external config', blank=True, help_text='configuration options on form understood by connection.') # activate the connection db_is_enabled = models.BooleanField('is enabled', default=True, help_text='turn on/off the connection.') objects = managers.ExternalChannelConnectionManager() class Meta: verbose_name = "External Channel Connection" def __str__(self): return "%s <-> external %s" % (self.channel.key, self.db_external_key) # channel property (wraps db_channel) #@property def channel_get(self): "Getter. Allows for value = self.channel" return self.db_channel #@channel.setter def channel_set(self, value): "Setter. Allows for self.channel = value" self.db_channel = value self.save() #@channel.deleter def channel_del(self): "Deleter. Allows for del self.channel. Deletes connection." self.delete() channel = property(channel_get, channel_set, channel_del) # external_key property (wraps db_external_key) #@property def external_key_get(self): "Getter. Allows for value = self.external_key" return self.db_external_key #@external_key.setter def external_key_set(self, value): "Setter. Allows for self.external_key = value" self.db_external_key = value self.save() #@external_key.deleter def external_key_del(self): "Deleter. Allows for del self.external_key. Deletes connection." self.delete() external_key = property(external_key_get, external_key_set, external_key_del) # external_send_code property (wraps db_external_send_code) #@property def external_send_code_get(self): "Getter. Allows for value = self.external_send_code" return self.db_external_send_code #@external_send_code.setter def external_send_code_set(self, value): "Setter. Allows for self.external_send_code = value" self.db_external_send_code = value self.save() #@external_send_code.deleter def external_send_code_del(self): "Deleter. Allows for del self.external_send_code. Deletes connection." self.db_external_send_code = "" self.save() external_send_code = property(external_send_code_get, external_send_code_set, external_send_code_del) # external_config property (wraps db_external_config) #@property def external_config_get(self): "Getter. Allows for value = self.external_config" return self.db_external_config #@external_config.setter def external_config_set(self, value): "Setter. Allows for self.external_config = value" self.db_external_config = value self.save() #@external_config.deleter def external_config_del(self): "Deleter. Allows for del self.external_config. Deletes connection." self.db_external_config = "" self.save() external_config = property(external_config_get, external_config_set, external_config_del) # is_enabled property (wraps db_is_enabled) #@property def is_enabled_get(self): "Getter. Allows for value = self.is_enabled" return self.db_is_enabled #@is_enabled.setter def is_enabled_set(self, value): "Setter. Allows for self.is_enabled = value" self.db_is_enabled = value self.save() #@is_enabled.deleter def is_enabled_del(self): "Deleter. Allows for del self.is_enabled. Deletes connection." self.delete() is_enabled = property(is_enabled_get, is_enabled_set, is_enabled_del) # # methods # def to_channel(self, message, from_obj=None): "Send external -> channel" if not from_obj: from_obj = self.external_key self.channel.msg(message, from_obj=from_obj) def to_external(self, message, from_obj=None, from_channel=None): "Send channel -> external" # make sure we are not echoing back our own message to ourselves # (this would result in a nasty infinite loop) if from_obj == self.external_key: return try: # we execute the code snippet that should make it possible for the # connection to contact the protocol correctly (as set by the protocol). # Note that the code block has access to the variables here, such # as message, from_obj and from_channel. exec(to_str(self.external_send_code)) except Exception: logger.log_trace("Channel %s could not send to External %s" % (self.channel, self.external_key))
Python
""" IMC2 client module. Handles connecting to and communicating with an IMC2 server. """ from time import time from twisted.application import internet from twisted.internet import protocol from twisted.conch import telnet from django.conf import settings from src.utils import logger, create, search, utils from src.server.sessionhandler import SESSIONS from src.scripts.scripts import Script from src.comms.models import Channel, ExternalChannelConnection from src.comms.imc2lib import imc2_packets as pck from src.comms.imc2lib.imc2_trackers import IMC2MudList, IMC2ChanList from src.comms.imc2lib.imc2_listeners import handle_whois_reply # IMC2 network setup IMC2_MUDNAME = settings.SERVERNAME IMC2_NETWORK = settings.IMC2_NETWORK IMC2_PORT = settings.IMC2_PORT IMC2_CLIENT_PWD = settings.IMC2_CLIENT_PWD IMC2_SERVER_PWD = settings.IMC2_SERVER_PWD # channel to send info to INFOCHANNEL = Channel.objects.channel_search(settings.CHANNEL_MUDINFO[0]) # all linked channel connections IMC2_CLIENT = None # IMC2 debug mode IMC2_DEBUG = False # Use this instance to keep track of the other games on the network. IMC2_MUDLIST = IMC2MudList() # Tracks the list of available channels on the network. IMC2_CHANLIST = IMC2ChanList() # # Helper method # def msg_info(message): """ Send info to default info channel """ try: INFOCHANNEL[0].msg(message) message = '[%s][IMC2]: %s' % (INFOCHANNEL[0].key, message) except Exception: logger.log_infomsg("MUDinfo (imc2): %s" % message) # # Regular scripts # class Send_IsAlive(Script): """ Sends periodic keepalives to network neighbors. This lets the other games know that our game is still up and connected to the network. Also provides some useful information about the client game. """ def at_script_creation(self): self.key = 'IMC2_Send_IsAlive' self.interval = 900 self.desc = "Send an IMC2 is-alive packet" self.persistent = True def at_repeat(self): IMC2_CLIENT.send_packet(pck.IMC2PacketIsAlive()) def is_valid(self): "Is only valid as long as there are channels to update" return any(service for service in SESSIONS.server.services if service.name.startswith("imc2_")) class Send_Keepalive_Request(Script): """ Event: Sends a keepalive-request to connected games in order to see who is connected. """ def at_script_creation(self): self.key = "IMC2_Send_Keepalive_Request" self.interval = 3500 self.desc = "Send an IMC2 keepalive-request packet" self.persistent = True def at_repeat(self): IMC2_CLIENT.channel.send_packet(pck.IMC2PacketKeepAliveRequest()) def is_valid(self): "Is only valid as long as there are channels to update" return any(service for service in SESSIONS.server.services if service.name.startswith("imc2_")) class Prune_Inactive_Muds(Script): """ Prunes games that have not sent is-alive packets for a while. If we haven't heard from them, they're probably not connected or don't implement the protocol correctly. In either case, good riddance to them. """ def at_script_creation(self): self.key = "IMC2_Prune_Inactive_Muds" self.interval = 1800 self.desc = "Check IMC2 list for inactive games" self.persistent = True self.inactive_threshold = 3599 def at_repeat(self): for name, mudinfo in IMC2_MUDLIST.mud_list.items(): if time() - mudinfo.last_updated > self.inactive_threshold: del IMC2_MUDLIST.mud_list[name] def is_valid(self): "Is only valid as long as there are channels to update" return any(service for service in SESSIONS.server.services if service.name.startswith("imc2_")) class Sync_Server_Channel_List(Script): """ Re-syncs the network's channel list. This will cause a cascade of reply packets of a certain type from the network. These are handled by the protocol, gradually updating the channel cache. """ def at_script_creation(self): self.key = "IMC2_Sync_Server_Channel_List" self.interval = 24 * 3600 # once every day self.desc = "Re-sync IMC2 network channel list" self.persistent = True def at_repeat(self): checked_networks = [] network = IMC2_CLIENT.factory.network if not network in checked_networks: channel.send_packet(pkg.IMC2PacketIceRefresh()) checked_networks.append(network) def is_valid(self): return any(service for service in SESSIONS.server.services if service.name.startswith("imc2_")) # # IMC2 protocol # class IMC2Protocol(telnet.StatefulTelnetProtocol): """ Provides the abstraction for the IMC2 protocol. Handles connection, authentication, and all necessary packets. """ def __init__(self): global IMC2_CLIENT IMC2_CLIENT = self self.is_authenticated = False self.auth_type = None self.server_name = None self.network_name = None self.sequence = None def connectionMade(self): """ Triggered after connecting to the IMC2 network. """ self.auth_type = "plaintext" if IMC2_DEBUG: logger.log_infomsg("IMC2: Connected to network server.") logger.log_infomsg("IMC2: Sending authentication packet.") self.send_packet(pck.IMC2PacketAuthPlaintext()) def connectionLost(self, reason=None): """ This is executed when the connection is lost for whatever reason. """ try: service = SESSIONS.server.services.getServiceNamed("imc2_%s:%s(%s)" % (IMC2_NETWORK, IMC2_PORT, IMC2_MUDNAME)) except Exception: return if service.running: service.stopService() def send_packet(self, packet): """ Given a sub-class of IMC2Packet, assemble the packet and send it on its way to the IMC2 server. Evennia -> IMC2 """ if self.sequence: # This gets incremented with every command. self.sequence += 1 packet.imc2_protocol = self packet_str = utils.to_str(packet.assemble(self.factory.mudname, self.factory.client_pwd, self.factory.server_pwd)) if IMC2_DEBUG and not (hasattr(packet, 'packet_type') and packet.packet_type == "is-alive"): logger.log_infomsg("IMC2: SENT> %s" % packet_str) logger.log_infomsg(str(packet)) self.sendLine(packet_str) def _parse_auth_response(self, line): """ Parses the IMC2 network authentication packet. """ if self.auth_type == "plaintext": # Plain text passwords. # SERVER Sends: PW <servername> <serverpw> version=<version#> <networkname> if IMC2_DEBUG: logger.log_infomsg("IMC2: AUTH< %s" % line) line_split = line.split(' ') pw_present = line_split[0] == 'PW' autosetup_present = line_split[0] == 'autosetup' if "reject" in line_split: auth_message = "IMC2 server rejected connection." logger.log_infomsg(auth_message) msg_info(auth_message) return if pw_present: self.server_name = line_split[1] self.network_name = line_split[4] elif autosetup_present: logger.log_infomsg("IMC2: Autosetup response found.") self.server_name = line_split[1] self.network_name = line_split[3] self.is_authenticated = True self.sequence = int(time()) # Log to stdout and notify over MUDInfo. auth_message = "Successfully authenticated to the '%s' network." % self.factory.network logger.log_infomsg('IMC2: %s' % auth_message) msg_info(auth_message) # Ask to see what other MUDs are connected. self.send_packet(pck.IMC2PacketKeepAliveRequest()) # IMC2 protocol states that KeepAliveRequests should be followed # up by the requester sending an IsAlive packet. self.send_packet(pck.IMC2PacketIsAlive()) # Get a listing of channels. self.send_packet(pck.IMC2PacketIceRefresh()) def _msg_evennia(self, packet): """ Handle the sending of packet data to Evennia channel (Message from IMC2 -> Evennia) """ conn_name = packet.optional_data.get('channel', None) # If the packet lacks the 'echo' key, don't bother with it. if not conn_name or not packet.optional_data.get('echo', None): return imc2_channel = conn_name.split(':', 1)[1] # Look for matching IMC2 channel maps mapping to this imc2 channel. conns = ExternalChannelConnection.objects.filter(db_external_key__startswith="imc2_") conns = [conn for conn in conns if imc2_channel in conn.db_external_config.split(",")] if not conns: # we are not listening to this imc2 channel. return # Format the message to send to local channel(s). for conn in conns: message = '[%s] %s@%s: %s' % (conn.channel.key, packet.sender, packet.origin, packet.optional_data.get('text')) conn.to_channel(message) def _format_tell(self, packet): """ Handle tells over IMC2 by formatting the text properly """ return "{c%s@%s{n {wpages (over IMC):{n %s" % (packet.sender, packet.origin, packet.optional_data.get('text', 'ERROR: No text provided.')) def lineReceived(self, line): """ Triggered when text is received from the IMC2 network. Figures out what to do with the packet. IMC2 -> Evennia """ line = line.strip() if not self.is_authenticated: self._parse_auth_response(line) else: if IMC2_DEBUG and not 'is-alive' in line: # if IMC2_DEBUG mode is on, print the contents of the packet # to stdout. logger.log_infomsg("IMC2: RECV> %s" % line) # Parse the packet and encapsulate it for easy access packet = pck.IMC2Packet(self.factory.mudname, packet_str=line) if IMC2_DEBUG and packet.packet_type not in ('is-alive', 'keepalive-request'): # Print the parsed packet's __str__ representation. # is-alive and keepalive-requests happen pretty frequently. # Don't bore us with them in stdout. logger.log_infomsg(str(packet)) # Figure out what kind of packet we're dealing with and hand it # off to the correct handler. if packet.packet_type == 'is-alive': IMC2_MUDLIST.update_mud_from_packet(packet) elif packet.packet_type == 'keepalive-request': # Don't need to check the destination, we only receive these # packets when they are intended for us. self.send_packet(pck.IMC2PacketIsAlive()) elif packet.packet_type == 'ice-msg-b': self._msg_evennia(packet) elif packet.packet_type == 'whois-reply': handle_whois_reply(packet) elif packet.packet_type == 'close-notify': IMC2_MUDLIST.remove_mud_from_packet(packet) elif packet.packet_type == 'ice-update': IMC2_CHANLIST.update_channel_from_packet(packet) elif packet.packet_type == 'ice-destroy': IMC2_CHANLIST.remove_channel_from_packet(packet) elif packet.packet_type == 'tell': player = search.players(packet.target) if not player: return player[0].msg(self._format_tell(packet)) def msg_imc2(self, message, from_obj=None, packet_type="imcbroadcast", data=None): """ Called by Evennia to send a message through the imc2 connection """ if from_obj: if hasattr(from_obj, 'key'): from_name = from_obj.key else: from_name = from_obj else: from_name = self.factory.mudname if packet_type == "imcbroadcast": if type(data) == dict: conns = ExternalChannelConnection.objects.filter(db_external_key__startswith="imc2_", db_channel=data.get("channel", "Unknown")) if not conns: return # we remove the extra channel info since imc2 supplies this anyway if ":" in message: header, message = [part.strip() for part in message.split(":", 1)] # send the packet imc2_channel = conns[0].db_external_config.split(',')[0] # only send to the first channel self.send_packet(pck.IMC2PacketIceMsgBroadcasted(self.factory.servername, imc2_channel, from_name, message)) elif packet_type == "imctell": # send a tell if type(data) == dict: target = data.get("target", "Unknown") destination = data.get("destination", "Unknown") self.send_packet(pck.IMC2PacketTell(from_name, target, destination, message)) elif packet_type == "imcwhois": # send a whois request if type(data) == dict: target = data.get("target", "Unknown") self.send_packet(pck.IMC2PacketWhois(from_obj.id, target)) class IMC2Factory(protocol.ClientFactory): """ Creates instances of the IMC2Protocol. Should really only ever need to create one connection. Tied in via src/server.py. """ protocol = IMC2Protocol def __init__(self, network, port, mudname, client_pwd, server_pwd): self.pretty_key = "%s:%s(%s)" % (network, port, mudname) self.network = network sname, host = network.split(".", 1) self.servername = sname.strip() self.port = port self.mudname = mudname self.protocol_version = '2' self.client_pwd = client_pwd self.server_pwd = server_pwd def clientConnectionFailed(self, connector, reason): message = 'Connection failed: %s' % reason.getErrorMessage() msg_info(message) logger.log_errmsg('IMC2: %s' % message) def clientConnectionLost(self, connector, reason): message = 'Connection lost: %s' % reason.getErrorMessage() msg_info(message) logger.log_errmsg('IMC2: %s' % message) def build_connection_key(channel, imc2_channel): "Build an id hash for the connection" if hasattr(channel, "key"): channel = channel.key return "imc2_%s:%s(%s)%s<>%s" % (IMC2_NETWORK, IMC2_PORT, IMC2_MUDNAME, imc2_channel, channel) def start_scripts(validate=False): """ Start all the needed scripts """ if validate: from src.scripts.models import ScriptDB ScriptDB.objects.validate() return if not search.scripts("IMC2_Send_IsAlive"): create.create_script(Send_IsAlive) if not search.scripts("IMC2_Send_Keepalive_Request"): create.create_script(Send_Keepalive_Request) if not search.scripts("IMC2_Prune_Inactive_Muds"): create.create_script(Prune_Inactive_Muds) if not search.scripts("IMC2_Sync_Server_Channel_List"): create.create_script(Sync_Server_Channel_List) def create_connection(channel, imc2_channel): """ This will create a new IMC2<->channel connection. """ if not type(channel) == Channel: new_channel = Channel.objects.filter(db_key=channel) if not new_channel: logger.log_errmsg("Cannot attach IMC2<->Evennia: Evennia Channel '%s' not found" % channel) return False channel = new_channel[0] key = build_connection_key(channel, imc2_channel) old_conns = ExternalChannelConnection.objects.filter(db_external_key=key) if old_conns: # this evennia channel is already connected to imc. Check if imc2_channel is different. # connection already exists. We try to only connect a new channel old_config = old_conns[0].db_external_config.split(",") if imc2_channel in old_config: return False # we already listen to this channel else: # We add a new imc2_channel to listen to old_config.append(imc2_channel) old_conns[0].db_external_config = ",".join(old_config) old_conns[0].save() return True else: # no old connection found; create a new one. config = imc2_channel # how the evennia channel will be able to contact this protocol in reverse send_code = "from src.comms.imc2 import IMC2_CLIENT\n" send_code += "data={'channel':from_channel}\n" send_code += "IMC2_CLIENT.msg_imc2(message, from_obj=from_obj, data=data)\n" conn = ExternalChannelConnection(db_channel=channel, db_external_key=key, db_external_send_code=send_code, db_external_config=config) conn.save() return True def delete_connection(channel, imc2_channel): "Destroy a connection" if hasattr(channel, "key"): channel = channel.key key = build_connection_key(channel, imc2_channel) try: conn = ExternalChannelConnection.objects.get(db_external_key=key) except ExternalChannelConnection.DoesNotExist: return False conn.delete() return True def connect_to_imc2(): "Create the imc instance and connect to the IMC2 network." # connect imc = internet.TCPClient(IMC2_NETWORK, int(IMC2_PORT), IMC2Factory(IMC2_NETWORK, IMC2_PORT, IMC2_MUDNAME, IMC2_CLIENT_PWD, IMC2_SERVER_PWD)) imc.setName("imc2_%s:%s(%s)" % (IMC2_NETWORK, IMC2_PORT, IMC2_MUDNAME)) SESSIONS.server.services.addService(imc) def connect_all(): """ Activates the imc2 system. Called by the server if IMC2_ENABLED=True. """ connect_to_imc2() start_scripts()
Python
""" This connects to an IRC network/channel and launches an 'bot' onto it. The bot then pipes what is being said between the IRC channel and one or more Evennia channels. """ from twisted.application import internet from twisted.words.protocols import irc from twisted.internet import protocol from django.conf import settings from src.comms.models import ExternalChannelConnection, Channel from src.utils import logger, utils from src.server.sessionhandler import SESSIONS INFOCHANNEL = Channel.objects.channel_search(settings.CHANNEL_MUDINFO[0]) IRC_CHANNELS = [] def msg_info(message): """ Send info to default info channel """ message = '[%s][IRC]: %s' % (INFOCHANNEL[0].key, message) try: INFOCHANNEL[0].msg(message) except AttributeError: logger.log_infomsg("MUDinfo (irc): %s" % message) class IRC_Bot(irc.IRCClient): """ This defines an IRC bot that connects to an IRC channel and relays data to and from an evennia game. """ def _get_nickname(self): "required for correct nickname setting" return self.factory.nickname nickname = property(_get_nickname) def signedOn(self): # This is the first point the protocol is instantiated. # add this protocol instance to the global list so we # can access it later to send data. global IRC_CHANNELS self.join(self.factory.channel) IRC_CHANNELS.append(self) #msg_info("Client connecting to %s.'" % (self.factory.channel)) def joined(self, channel): msg = "joined %s." % self.factory.pretty_key msg_info(msg) logger.log_infomsg(msg) def privmsg(self, user, irc_channel, msg): "Someone has written something in irc channel. Echo it to the evennia channel" #find irc->evennia channel mappings conns = ExternalChannelConnection.objects.filter(db_external_key=self.factory.key) if not conns: return #format message: user = user.split("!")[0] if user: user.strip() else: user = "Unknown" msg = "[%s] %s@%s: %s" % (self.factory.evennia_channel, user, irc_channel, msg.strip()) #logger.log_infomsg("<IRC: " + msg) for conn in conns: if conn.channel: conn.to_channel(msg) def msg_irc(self, msg, from_obj=None): """ Called by evennia when sending something to mapped IRC channel. Note that this cannot simply be called msg() since that's the name of of the twisted irc hook as well, this leads to some initialization messages to be sent without checks, causing loops. """ self.msg(utils.to_str(self.factory.channel), utils.to_str(msg)) class IRCbotFactory(protocol.ClientFactory): protocol = IRC_Bot def __init__(self, key, channel, network, port, nickname, evennia_channel): self.key = key self.pretty_key = "%s:%s%s ('%s')" % (network, port, channel, nickname) self.network = network self.port = port self.channel = channel self.nickname = nickname self.evennia_channel = evennia_channel def clientConnectionLost(self, connector, reason): from twisted.internet.error import ConnectionDone if type(reason.type) == type(ConnectionDone): msg_info("Connection closed.") else: msg_info("Lost connection %s. Reason: '%s'. Reconnecting." % (self.pretty_key, reason)) connector.connect() def clientConnectionFailed(self, connector, reason): msg = "Could not connect %s Reason: '%s'" % (self.pretty_key, reason) msg_info(msg) logger.log_errmsg(msg) def build_connection_key(channel, irc_network, irc_port, irc_channel, irc_bot_nick): "Build an id hash for the connection" if hasattr(channel, 'key'): channel = channel.key return "irc_%s:%s%s(%s)<>%s" % (irc_network, irc_port, irc_channel, irc_bot_nick, channel) def build_service_key(key): return "IRCbot:%s" % key def create_connection(channel, irc_network, irc_port, irc_channel, irc_bot_nick): """ This will create a new IRC<->channel connection. """ if not type(channel) == Channel: new_channel = Channel.objects.filter(db_key=channel) if not new_channel: logger.log_errmsg("Cannot attach IRC<->Evennia: Evennia Channel '%s' not found" % channel) return False channel = new_channel[0] key = build_connection_key(channel, irc_network, irc_port, irc_channel, irc_bot_nick) old_conns = ExternalChannelConnection.objects.filter(db_external_key=key) if old_conns: return False config = "%s|%s|%s|%s" % (irc_network, irc_port, irc_channel, irc_bot_nick) # how the channel will be able to contact this protocol send_code = "from src.comms.irc import IRC_CHANNELS\n" send_code += "matched_ircs = [irc for irc in IRC_CHANNELS if irc.factory.key == '%s']\n" % key send_code += "[irc.msg_irc(message, from_obj=from_obj) for irc in matched_ircs]\n" conn = ExternalChannelConnection(db_channel=channel, db_external_key=key, db_external_send_code=send_code, db_external_config=config) conn.save() # connect connect_to_irc(conn) return True def delete_connection(channel, irc_network, irc_port, irc_channel, irc_bot_nick): "Destroy a connection" if hasattr(channel, 'key'): channel = channel.key key = build_connection_key(channel, irc_network, irc_port, irc_channel, irc_bot_nick) service_key = build_service_key(key) try: conn = ExternalChannelConnection.objects.get(db_external_key=key) except Exception: return False conn.delete() try: service = SESSIONS.server.services.getServiceNamed(service_key) except Exception: return True if service.running: SESSIONS.server.services.removeService(service) return True def connect_to_irc(connection): "Create the bot instance and connect to the IRC network and channel." # get config key = utils.to_str(connection.external_key) service_key = build_service_key(key) irc_network, irc_port, irc_channel, irc_bot_nick = [utils.to_str(conf) for conf in connection.external_config.split('|')] # connect bot = internet.TCPClient(irc_network, int(irc_port), IRCbotFactory(key, irc_channel, irc_network, irc_port, irc_bot_nick, connection.channel.key)) bot.setName(service_key) SESSIONS.server.services.addService(bot) def connect_all(): """ Activate all irc bots. """ for connection in ExternalChannelConnection.objects.filter(db_external_key__startswith='irc_'): connect_to_irc(connection)
Python
""" Certain periodic packets are sent by connected MUDs (is-alive, user-cache, etc). The IMC2 protocol assumes that each connected MUD will capture these and populate/maintain their own lists of other servers connected. This module contains stuff like this. """ from time import time class IMC2Mud(object): """ Stores information about other games connected to our current IMC2 network. """ def __init__(self, packet): self.name = packet.origin self.versionid = packet.optional_data.get('versionid', None) self.networkname = packet.optional_data.get('networkname', None) self.url = packet.optional_data.get('url', None) self.host = packet.optional_data.get('host', None) self.port = packet.optional_data.get('port', None) self.sha256 = packet.optional_data.get('sha256', None) # This is used to determine when a Mud has fallen into inactive status. self.last_updated = time() class IMC2MudList(object): """ Keeps track of other MUDs connected to the IMC network. """ def __init__(self): # Mud list is stored in a dict, key being the IMC Mud name. self.mud_list = {} def get_mud_list(self): """ Returns a sorted list of connected Muds. """ muds = self.mud_list.items() muds.sort() return [value for key, value in muds] def update_mud_from_packet(self, packet): """ This grabs relevant info from the packet and stuffs it in the Mud list for later retrieval. """ mud = IMC2Mud(packet) self.mud_list[mud.name] = mud def remove_mud_from_packet(self, packet): """ Removes a mud from the Mud list when given a packet. """ mud = IMC2Mud(packet) try: del self.mud_list[mud.name] except KeyError: # No matching entry, no big deal. pass class IMC2Channel(object): """ Stores information about channels available on the network. """ def __init__(self, packet): self.localname = packet.optional_data.get('localname', None) self.name = packet.optional_data.get('channel', None) self.level = packet.optional_data.get('level', None) self.owner = packet.optional_data.get('owner', None) self.policy = packet.optional_data.get('policy', None) self.last_updated = time() class IMC2ChanList(object): """ Keeps track of other MUDs connected to the IMC network. """ def __init__(self): # Chan list is stored in a dict, key being the IMC Mud name. self.chan_list = {} def get_channel_list(self): """ Returns a sorted list of cached channels. """ channels = self.chan_list.items() channels.sort() return [value for key, value in channels] def update_channel_from_packet(self, packet): """ This grabs relevant info from the packet and stuffs it in the channel list for later retrieval. """ channel = IMC2Channel(packet) self.chan_list[channel.name] = channel def remove_channel_from_packet(self, packet): """ Removes a channel from the Channel list when given a packet. """ channel = IMC2Channel(packet) try: del self.chan_list[channel.name] except KeyError: # No matching entry, no big deal. pass
Python
""" This module handles some of the -reply packets like whois-reply. """ from src.objects.models import ObjectDB from src.comms.imc2lib import imc2_ansi def handle_whois_reply(packet): """ When the player sends an imcwhois <playername> request, the outgoing packet contains the id of the one asking. This handler catches the (possible) reply from the server, parses the id back to the original asker and tells them the result. """ try: pobject = ObjectDB.objects.get(id=packet.target) response_text = imc2_ansi.parse_ansi(packet.optional_data.get('text', 'Unknown')) string = 'Whois reply from %s: %s' % (packet.origin, response_text) pobject.msg(string.strip()) except ObjectDB.DoesNotExist: # No match found for whois sender. Ignore it. pass
Python
""" ANSI parser - this adds colour to text according to special markup strings. This is a IMC2 complacent version. """ import re from src.utils import ansi class IMCANSIParser(ansi.ANSIParser): """ This parser is per the IMC2 specification. """ def __init__(self): normal = ansi.ANSI_NORMAL hilite = ansi.ANSI_HILITE self.ansi_map = [ (r'~Z', normal), # Random (r'~x', normal + ansi.ANSI_BLACK), # Black (r'~D', hilite + ansi.ANSI_BLACK), # Dark Grey (r'~z', hilite + ansi.ANSI_BLACK), (r'~w', normal + ansi.ANSI_WHITE), # Grey (r'~W', hilite + ansi.ANSI_WHITE), # White (r'~g', normal + ansi.ANSI_GREEN), # Dark Green (r'~G', hilite + ansi.ANSI_GREEN), # Green (r'~p', normal + ansi.ANSI_MAGENTA), # Dark magenta (r'~m', normal + ansi.ANSI_MAGENTA), (r'~M', hilite + ansi.ANSI_MAGENTA), # Magenta (r'~P', hilite + ansi.ANSI_MAGENTA), (r'~c', normal + ansi.ANSI_CYAN), # Cyan (r'~y', normal + ansi.ANSI_YELLOW), # Dark Yellow (brown) (r'~Y', hilite + ansi.ANSI_YELLOW), # Yellow (r'~b', normal + ansi.ANSI_BLUE), # Dark Blue (r'~B', hilite + ansi.ANSI_BLUE), # Blue (r'~C', hilite + ansi.ANSI_BLUE), (r'~r', normal + ansi.ANSI_RED), # Dark Red (r'~R', hilite + ansi.ANSI_RED), # Red ## Formatting (r'~L', hilite), # Bold/hilite (r'~!', normal), # reset (r'\\r', normal), (r'\\n', ansi.ANSI_RETURN), ] # prepare regex matching self.ansi_sub = [(re.compile(sub[0], re.DOTALL), sub[1]) for sub in self.ansi_map] # prepare matching ansi codes overall self.ansi_regex = re.compile("\033\[[0-9;]+m") ANSI_PARSER = IMCANSIParser() def parse_ansi(string, strip_ansi=False, parser=ANSI_PARSER): """ Shortcut to use the IMC2 ANSI parser. """ return parser.parse_ansi(string, strip_ansi=strip_ansi)
Python
""" IMC2 packets. These are pretty well documented at: http://www.mudbytes.net/index.php?a=articles&s=imc2_protocol """ import shlex from django.conf import settings class Lexxer(shlex.shlex): """ A lexical parser for interpreting IMC2 packets. """ def __init__(self, packet_str, posix=True): shlex.shlex.__init__(self, packet_str, posix=True) # Single-quotes are notably not present. This is important! self.quotes = '"' self.commenters = '' # This helps denote what constitutes a continuous token. self.wordchars += "~`!@#$%^&*()-_+=[{]}|\\;:',<.>/?" class IMC2Packet(object): """ Base IMC2 packet class. This is generally sub-classed, aside from using it to parse incoming packets from the IMC2 network server. """ def __init__(self, mudname=None, packet_str=None): """ Optionally, parse a packet and load it up. """ # The following fields are all according to the basic packet format of: # <sender>@<origin> <sequence> <route> <packet-type> <target>@<destination> <data...> self.sender = None if not mudname: mudname = settings.SERVERNAME self.origin = mudname self.sequence = None self.route = mudname self.packet_type = None self.target = None self.destination = None # Optional data. self.optional_data = {} # Reference to the IMC2Protocol object doing the sending. self.imc2_protocol = None if packet_str: # The lexxer handles the double quotes correctly, unlike just # splitting. Spaces throw things off, so shlex handles it # gracefully, ala POSIX shell-style parsing. lex = Lexxer(packet_str) # Token counter. counter = 0 for token in lex: if counter == 0: # This is the sender@origin token. sender_origin = token split_sender_origin = sender_origin.split('@') self.sender = split_sender_origin[0].strip() self.origin = split_sender_origin[1] elif counter == 1: # Numeric time-based sequence. self.sequence = token elif counter == 2: # Packet routing info. self.route = token elif counter == 3: # Packet type string. self.packet_type = token elif counter == 4: # Get values for the target and destination attributes. target_destination = token split_target_destination = target_destination.split('@') self.target = split_target_destination[0] try: self.destination = split_target_destination[1] except IndexError: # There is only one element to the target@dest segment # of the packet. Wipe the target and move the captured # value to the destination attrib. self.target = '*' self.destination = split_target_destination[0] elif counter > 4: # Populate optional data. try: key, value = token.split('=', 1) self.optional_data[key] = value except ValueError: # Failed to split on equal sign, disregard. pass # Increment and continue to the next token (if applicable) counter += 1 def __str__(self): retval = """ --IMC2 package (%s) Sender: %s Origin: %s Sequence: %s Route: %s Type: %s Target: %s Dest.: %s Data: %s ------------------------""" % (self.packet_type, self.sender, self.origin, self.sequence, self.route, self.packet_type, self.target, self.destination, "\n ".join(["%s: %s" % items for items in self.optional_data.items()])) return retval.strip() def _get_optional_data_string(self): """ Generates the optional data string to tack on to the end of the packet. """ if self.optional_data: data_string = '' for key, value in self.optional_data.items(): # Determine the number of words in this value. words = len(str(value).split(' ')) # Anything over 1 word needs double quotes. if words > 1: value = '"%s"' % (value,) data_string += '%s=%s ' % (key, value) return data_string.strip() else: return '' def _get_sender_name(self): """ Calculates the sender name to be sent with the packet. """ if self.sender == '*': # Some packets have no sender. return '*' elif str(self.sender).isdigit(): return self.sender elif type(self.sender) in [type(u""),type(str())]: #this is used by e.g. IRC where no user object is present. return self.sender.strip().replace(' ', '_') elif self.sender: # Player object. name = self.sender.get_name(fullname=False, show_dbref=False, show_flags=False, no_ansi=True) # IMC2 does not allow for spaces. return name.strip().replace(' ', '_') else: # None value. Do something or other. return 'Unknown' def assemble(self, mudname=None, client_pwd=None, server_pwd=None): """ Assembles the packet and returns the ready-to-send string. Note that the arguments are not used, they are there for consistency across all packets. """ self.sequence = self.imc2_protocol.sequence packet = "%s@%s %s %s %s %s@%s %s\n" % ( self._get_sender_name(), self.origin, self.sequence, self.route, self.packet_type, self.target, self.destination, self._get_optional_data_string()) return packet.strip() class IMC2PacketAuthPlaintext(object): """ IMC2 plain-text authentication packet. Auth packets are strangely formatted, so this does not sub-class IMC2Packet. The SHA and plain text auth packets are the two only non-conformers. CLIENT Sends: PW <mudname> <clientpw> version=<version#> autosetup <serverpw> (SHA256) Optional Arguments( required if using the specified authentication method: (SHA256) The literal string: SHA256. This is sent to notify the server that the MUD is SHA256-Enabled. All future logins from this client will be expected in SHA256-AUTH format if the server supports it. """ def assemble(self, mudname=None, client_pwd=None, server_pwd=None): """ This is one of two strange packets, just assemble the packet manually and go. """ return 'PW %s %s version=2 autosetup %s\n' %(mudname, client_pwd, server_pwd) class IMC2PacketKeepAliveRequest(IMC2Packet): """ Description: This packet is sent by a MUD to trigger is-alive packets from other MUDs. This packet is usually followed by the sending MUD's own is-alive packet. It is used in the filling of a client's MUD list, thus any MUD that doesn't respond with an is-alive isn't marked as online on the sending MUD's mudlist. Data: (none) Example of a received keepalive-request: *@YourMUD 1234567890 YourMUD!Hub1 keepalive-request *@* Example of a sent keepalive-request: *@YourMUD 1234567890 YourMUD keepalive-request *@* """ def __init__(self): super(IMC2PacketKeepAliveRequest, self).__init__() self.sender = '*' self.packet_type = 'keepalive-request' self.target = '*' self.destination = '*' class IMC2PacketIsAlive(IMC2Packet): """ Description: This packet is the reply to a keepalive-request packet. It is responsible for filling a client's mudlist with the information about other MUDs on the network. Data: versionid=<string> Where <string> is the text version ID of the client. ("IMC2 4.5 MUD-Net") url=<string> Where <string> is the proper URL of the client. (http://www.domain.com) host=<string> Where <string> is the telnet address of the MUD. (telnet://domain.com) port=<int> Where <int> is the telnet port of the MUD. (These data fields are not sent by the MUD, they are added by the server.) networkname=<string> Where <string> is the network name that the MUD/server is on. ("MyNetwork") sha256=<int> This is an optional tag that denotes the SHA-256 capabilities of a MUD or server. Example of a received is-alive: *@SomeMUD 1234567890 SomeMUD!Hub2 is-alive *@YourMUD versionid="IMC2 4.5 MUD-Net" url="http://www.domain.com" networkname="MyNetwork" sha256=1 host=domain.com port=5500 Example of a sent is-alive: *@YourMUD 1234567890 YourMUD is-alive *@* versionid="IMC2 4.5 MUD-Net" url="http://www.domain.com" host=domain.com port=5500 """ def __init__(self): super(IMC2PacketIsAlive, self).__init__() self.sender = '*' self.packet_type = 'is-alive' self.target = '*' self.destination = '*' self.optional_data = {'versionid': 'Evennia IMC2', 'url': '"http://www.evennia.com"', 'host': 'test.com', 'port': '5555'} class IMC2PacketIceRefresh(IMC2Packet): """ Description: This packet is sent by the MUD to request data about the channels on the network. Servers with channels reply with an ice-update packet for each channel they control. The usual target for this packet is IMC@$. Data: (none) Example: *@YourMUD 1234567890 YourMUD!Hub1 ice-refresh IMC@$ """ def __init__(self): super(IMC2PacketIceRefresh, self).__init__() self.sender = '*' self.packet_type = 'ice-refresh' self.target = 'IMC' self.destination = '$' class IMC2PacketIceUpdate(IMC2Packet): """ Description: A server returns this packet with the data of a channel when prompted with an ice-refresh request. Data: channel=<string> The channel's network name in the format of ServerName:ChannelName owner=<string> The Name@MUD of the channel's owner operators=<string> A space-seperated list of the Channel's operators, in the format of Person@MUD policy=<string> The policy is either "open" or "private" with no quotes. invited=<string> The space-seperated list of invited User@MUDs, only valid for a "private" channel. excluded=<string> The space-seperated list of banned User@MUDs, only valid for "open" channels. level=<string> The default level of the channel: Admin, Imp, Imm, Mort, or None localname=<string> The suggested local name of the channel. Examples: Open Policy: ICE@Hub1 1234567890 Hub1!Hub2 ice-update *@YourMUD channel=Hub1:ichat owner=Imm@SomeMUD operators=Other@SomeMUD policy=open excluded="Flamer@badMUD Jerk@dirtyMUD" level=Imm localname=ichat Private Policy: ICE@Hub1 1234567890 Hub1!Hub2 ice-update *@YourMUD channel=Hub1:secretchat owner=Imm@SomeMUD operators=Other@SomeMUD policy=private invited="SpecialDude@OtherMUD CoolDude@WeirdMUD" level=Mort localname=schat """ pass class IMC2PacketIceMsgRelayed(IMC2Packet): """ Description: The -r in this ice-msg packet means it was relayed. This, along with the ice-msg-p packet, are used with private policy channels. The 'r' stands for 'relay'. All incoming channel messages are from ICE@<server>, where <server> is the server hosting the channel. Data: realfrom=<string> The User@MUD the message came from. channel=<string> The Server:Channel the message is intended to be displayed on. text=<string> The message text. emote=<int> An integer value designating emotes. 0 for no emote, 1 for an emote, and 2 for a social. Examples: ICE@Hub1 1234567890 Hub1!Hub2 ice-msg-r *@YourMUD realfrom=You@YourMUD channel=hub1:secret text="Aha! I got it!" emote=0 ICE@Hub1 1234567890 Hub1!Hub2 ice-msg-r *@YourMUD realfrom=You@YourMUD channel=hub1:secret text=Ahh emote=0 ICE@Hub1 1234567890 Hub1!Hub2 ice-msg-r *@YourMUD realfrom=You@YourMUD channel=hub1:secret text="grins evilly." emote=1 ICE@Hub1 1234567890 Hub1!Hub2 ice-msg-r *@YourMUD realfrom=You@YourMUD channel=hub1:secret text="You@YourMUD grins evilly!" emote=2 """ pass class IMC2PacketIceMsgPrivate(IMC2Packet): """ Description: This packet is sent when a player sends a message to a private channel. This packet should never be seen as incoming to a client. The target of this packet should be IMC@<server> of the server hosting the channel. Data: channel=<string> The Server:Channel the message is intended to be displayed on. text=<string> The message text. emote=<int> An integer value designating emotes. 0 for no emote, 1 for an emote, and 2 for a social. echo=<int> Tells the server to echo the message back to the sending MUD. This is only seen on out-going messages. Examples: You@YourMUD 1234567890 YourMUD ice-msg-p IMC@Hub1 channel=Hub1:secret text="Ahh! I got it!" emote=0 echo=1 You@YourMUD 1234567890 YourMUD ice-msg-p IMC@Hub1 channel=Hub1:secret text=Ahh! emote=0 echo=1 You@YourMUD 1234567890 YourMUD ice-msg-p IMC@Hub1 channel=Hub1:secret text="grins evilly." emote=1 echo=1 You@YourMUD 1234567890 YourMUD ice-msg-p IMC@Hub1 channel=Hub1:secret text="You@YourMUD grins evilly." emote=2 echo=1 """ pass class IMC2PacketIceMsgBroadcasted(IMC2Packet): """ Description: This is the packet used to chat on open policy channels. When sent from a MUD, it is broadcasted across the network. Other MUDs receive it in-tact as it was sent by the originating MUD. The server that hosts the channel sends the packet back to the originating MUD as an 'echo' by removing the "echo=1" and attaching the "sender=Person@MUD" data field. Data: channel=<string> The Server:Channel the message is intended to be displayed on. text=<string> The message text. emote=<int> An integer value designating emotes. 0 for no emote, 1 for an emote, and 2 for a social. *echo=<int> This stays on broadcasted messages. It tells the channel's server to relay an echo back. *sender=<string> The hosting server replaces "echo=1" with this when sending the echo back to the originating MUD. Examples: (See above for emote/social examples as they are pretty much the same) Return Echo Packet: You-YourMUD@Hub1 1234567890 Hub1 ice-msg-b *@YourMUD text=Hi! channel=Hub1:ichat sender=You@YourMUD emote=0 Broadcasted Packet: You@YourMUD 1234567890 YourMUD!Hub1 ice-msg-b *@* channel=Hub1:ichat text=Hi! emote=0 echo=1 """ def __init__(self, server, channel, pobject, message): """ Args: server: (String) Server name the channel resides on (obs - this is e.g. Server01, not the full network name!) channel: (String) Name of the IMC2 channel. pobject: (Object) Object sending the message. message: (String) Message to send. """ super(IMC2PacketIceMsgBroadcasted, self).__init__() self.sender = pobject self.packet_type = 'ice-msg-b' self.target = '*' self.destination = '*' self.optional_data = {'channel': '%s:%s' % (server, channel), 'text': message, 'emote': 0, 'echo': 1} class IMC2PacketUserCache(IMC2Packet): """ Description: Sent by a MUD with a new IMC2-able player or when a player's gender changes, this packet contains only the gender for data. The packet's origination should be the Player@MUD. Data: gender=<int> 0 is male, 1 is female, 2 is anything else such as neuter. Will be referred to as "it". Example: Dude@someMUD 1234567890 SomeMUD!Hub2!Hub1 user-cache *@* gender=0 """ pass class IMC2PacketUserCacheRequest(IMC2Packet): """ Description: The MUD sends this packet out when making a request for the user-cache information of the user included in the data part of the packet. Data: user=<string> The Person@MUD whose data the MUD is seeking. Example: *@YourMUD 1234567890 YourMUD user-cache-request *@SomeMUD user=Dude@SomeMUD """ pass class IMC2PacketUserCacheReply(IMC2Packet): """ Description: A reply to the user-cache-request packet. It contains the user and gender for the user. Data: user=<string> The Person@MUD whose data the MUD requested. gender=<int> The gender of the Person@MUD in the 'user' field. Example: *@someMUD 1234567890 SomeMUD!Hub2!Hub1 user-cache-reply *@YourMUD user=Dude@SomeMUD gender=0 """ pass class IMC2PacketTell(IMC2Packet): """ Description: This packet is used to communicate private messages between users on MUDs across the network. Data: text=<string> Message text isreply=<int> Two settings: 1 denotes a reply, 2 denotes a tell social. Example: Originating: You@YourMUD 1234567890 YourMUD tell Dude@SomeMUD text="Having fun?" Reply from Dude: Dude@SomeMUD 1234567890 SomeMUD!Hub1 tell You@YourMUD text="Yeah, this is cool!" isreply=1 """ def __init__(self, pobject, target, destination, message): super(IMC2PacketTell, self).__init__() self.sender = pobject self.packet_type = "tell" self.target = target self.destination = destination self.optional_data = {"text": message, "isreply":None} def assemble(self, mudname=None, client_pwd=None, server_pwd=None): self.sequence = self.imc2_protocol.sequence #self.route = "%s!%s" % (self.origin, self.imc2_protocol.factory.servername.capitalize()) return '''"%s@%s %s %s tell %s@%s text="%s"''' % (self.sender, self.origin, self.sequence, self.route, self.target, self.destination, self.optional_data.get("text","NO TEXT GIVEN")) class IMC2PacketEmote(IMC2Packet): """ Description: This packet seems to be sent by servers when notifying the network of a new channel or the destruction of a channel. Data: channel=<int> Unsure of what this means. The channel seen in both creation and destruction packets is 15. level=<int> I am assuming this is the permission level of the sender. In both creation and destruction messages, this is -1. text=<string> This is the message to be sent to the users. Examples: ICE@Hub1 1234567890 Hub1 emote *@* channel=15 level=-1 text="the channel called hub1:test has been destroyed by You@YourMUD." """ pass class IMC2PacketRemoteAdmin(IMC2Packet): """ Description: This packet is used in remote server administration. Please note that SHA-256 Support is *required* for a client to use this feature. The command can vary, in fact this very packet is highly dependant on the server it's being directed to. In most cases, sending the 'list' command will have a remote-admin enabled server send you the list of commands it will accept. Data: command=<string> The command being sent to the server for processing. data=<string> Data associated with the command. This is not always required. hash=<string> The SHA-256 hash that is verified by the server. This hash is generated in the same manner as an authentication packet. Example: You@YourMUD 1234567890 YourMUD remote-admin IMC@Hub1 command=list hash=<hash goes here> """ pass class IMC2PacketIceCmd(IMC2Packet): """ Description: Used for remote channel administration. In most cases, one must be listed as a channel creator on the target server in order to do much with this packet. Other cases include channel operators. Data: channel=<string> The target server:channel for the command. command=<string> The command to be processed. data=<string> Data associated with the command. This is not always required. Example: You@YourMUD 1234567890 YourMUD ice-cmd IMC@hub1 channel=hub1:ichat command=list """ pass class IMC2PacketDestroy(IMC2Packet): """ Description: Sent by a server to indicate the destruction of a channel it hosted. The mud should remove this channel from its local configuration. Data: channel=<string> The server:channel being destroyed. """ pass class IMC2PacketWho(IMC2Packet): """ Description: A seemingly mutli-purpose information-requesting packet. The istats packet currently only works on servers, or at least that's the case on MUD-Net servers. The 'finger' type takes a player name in addition to the type name. Example: "finger Dude". The 'who' and 'info' types take no argument. The MUD is responsible for building the reply text sent in the who-reply packet. Data: type=<string> Types: who, info, "finger <name>", istats (server only) Example: Dude@SomeMUD 1234567890 SomeMUD!Hub1 who *@YourMUD type=who """ pass class IMC2PacketWhoReply(IMC2Packet): """ Description: The multi-purpose reply to the multi-purpose information-requesting 'who' packet. The MUD is responsible for building the return data, including the format of it. The mud can use the permission level sent in the original who packet to filter the output. The example below is the MUD-Net format. Data: text=<string> The formatted reply to a 'who' packet. Additional Notes: The example below is for the who list packet. The same construction would go into formatting the other types of who packets. Example: *@YourMUD 1234567890 YourMUD who-reply Dude@SomeMUD text="\n\r~R-=< ~WPlayers on YourMUD ~R>=-\n\r ~Y-=< ~Wtelnet://yourmud.domain.com:1234 ~Y>=-\n\r\n\r~B--------------------------------=< ~WPlayers ~B>=---------------------------------\n\r\n\r ~BPlayer ~z<--->~G Mortal the Toy\n\r\n\r~R-------------------------------=< ~WImmortals ~R>=--------------------------------\n\r\n\r ~YStaff ~z<--->~G You the Immortal\n\r\n\r~Y<~W2 Players~Y> ~Y<~WHomepage: http://www.yourmud.com~Y> <~W 2 Max Since Reboot~Y>\n\r~Y<~W3 logins since last reboot on Tue Feb 24, 2004 6:55:59 PM EST~Y>" """ pass class IMC2PacketWhois(IMC2Packet): """ Description: Sends a request to the network for the location of the specified player. Data: level=<int> The permission level of the person making the request. Example: You@YourMUD 1234567890 YourMUD whois dude@* level=5 """ def __init__(self, pobject_id, whois_target): super(IMC2PacketWhois, self).__init__() self.sender = pobject_id # Use the dbref, it's easier to trace back for the whois-reply. self.packet_type = 'whois' self.target = whois_target self.destination = '*' self.optional_data = {'level': '5'} class IMC2PacketWhoisReply(IMC2Packet): """ Description: The reply to a whois packet. The MUD is responsible for building and formatting the text sent back to the requesting player, and can use the permission level sent in the original whois packet to filter or block the response. Data: text=<string> The whois text. Example: *@SomeMUD 1234567890 SomeMUD!Hub1 whois-reply You@YourMUD text="~RIMC Locate: ~YDude@SomeMUD: ~cOnline.\n\r" """ pass class IMC2PacketBeep(IMC2Packet): """ Description: Sends out a beep packet to the Player@MUD. The client receiving this should then send a bell-character to the target player to 'beep' them. Example: You@YourMUD 1234567890 YourMUD beep dude@somemud """ pass class IMC2PacketIceChanWho(IMC2Packet): """ Description: Sends a request to the specified MUD or * to list all the users listening to the specified channel. Data: level=<int> Sender's permission level. channel=<string> The server:chan name of the channel. lname=<string> The localname of the channel. Example: You@YourMUD 1234567890 YourMUD ice-chan-who somemud level=5 channel=Hub1:ichat lname=ichat """ pass class IMC2PacketIceChanWhoReply(IMC2Packet): """ Description: This is the reply packet for an ice-chan-who. The MUD is responsible for creating and formatting the list sent back in the 'list' field. The permission level sent in the original ice-chan-who packet can be used to filter or block the response. Data: channel=<string> The server:chan of the requested channel. list=<string> The formatted list of local listeners for that MUD. Example: *@SomeMUD 1234567890 SomeMUD!Hub1 ice-chan-whoreply You@YourMUD channel=Hub1:ichat list="The following people are listening to ichat on SomeMUD:\n\r\n\rDude\n\r" """ pass class IMC2PacketLaston(IMC2Packet): """ Description: This packet queries the server the mud is connected to to find out when a specified user was last seen by the network on a public channel. Data: username=<string> The user, user@mud, or "all" being queried. Responses to this packet will be sent by the server in the form of a series of tells. Example: User@MUD 1234567890 MUD imc-laston SERVER username=somenamehere """ pass class IMC2PacketCloseNotify(IMC2Packet): """ Description: This packet alerts the network when a server or MUD has disconnected. The server hosting the server or MUD is responsible for sending this packet out across the network. Clients need only process the packet to remove the disconnected MUD from their MUD list (or mark it as Disconnected). Data: host=<string> The MUD or server that has disconnected from the network. Example: *@Hub2 1234567890 Hub2!Hub1 close-notify *@* host=DisconnMUD """ pass if __name__ == "__main__": packstr = "Kayle@MW 1234567 MW!Server02!Server01 ice-msg-b *@* channel=Server01:ichat text=\"*they're going woot\" emote=0 echo=1" packstr = "*@Lythelian 1234567 Lythelian!Server01 is-alive *@* versionid=\"Tim's LPC IMC2 client 30-Jan-05 / Dead Souls integrated\" networkname=Mudbytes url=http://dead-souls.net host=70.32.76.142 port=6666 sha256=0" print IMC2Packet(packstr)
Python
""" RSS parser for Evennia This connects an RSS feed to an in-game Evennia channel, sending messages to the channel whenever the feed updates. """ import re from twisted.internet import task from django.conf import settings from src.comms.models import ExternalChannelConnection, Channel from src.utils import logger, utils from src.scripts.models import ScriptDB RSS_ENABLED = settings.RSS_ENABLED RSS_UPDATE_INTERVAL = settings.RSS_UPDATE_INTERVAL INFOCHANNEL = Channel.objects.channel_search(settings.CHANNEL_MUDINFO[0]) RETAG = re.compile(r'<[^>]*?>') # holds rss readers they can be shut down at will. RSS_READERS = {} def msg_info(message): """ Send info to default info channel """ message = '[%s][RSS]: %s' % (INFOCHANNEL[0].key, message) try: INFOCHANNEL[0].msg(message) except AttributeError: logger.log_infomsg("MUDinfo (rss): %s" % message) if RSS_ENABLED: try: import feedparser except ImportError: raise ImportError("RSS requirs python-feedparser to be installed. Install or set RSS_ENABLED=False.") class RSSReader(object): """ Reader script used to connect to each individual RSS feed """ def __init__(self, key, url, interval): """ The reader needs an rss url and It also needs an interval for how often it is to check for new updates (defaults to 10 minutes) """ self.key = key self.url = url self.interval = interval self.entries = {} # stored feeds self.task = None # first we do is to load the feed so we don't resend # old entries whenever the reader starts. self.update_feed() # start runner self.start() def update_feed(self): "Read the url for new updated data and determine what's new." feed = feedparser.parse(self.url) new = [] for entry in (e for e in feed['entries'] if e['id'] not in self.entries): txt = "[RSS] %s: %s" % (RETAG.sub("", entry['title']), entry['link'].replace('\n','').encode('utf-8')) self.entries[entry['id']] = txt new.append(txt) return new def update(self): """ Called every self.interval seconds - tries to get new feed entries, and if so, uses the appropriate ExternalChannelConnection to send the data to subscribing channels. """ new = self.update_feed() if not new: return conns = ExternalChannelConnection.objects.filter(db_external_key=self.key) for conn in (conn for conn in conns if conn.channel): for txt in new: conn.to_channel("%s:%s" % (conn.channel.key, txt)) def start(self): """ Starting the update task and store a reference in the global variable so it can be found and shut down later. """ global RSS_READERS self.task = task.LoopingCall(self.update) self.task.start(self.interval, now=False) RSS_READERS[self.key] = self def build_connection_key(channel, url): "This is used to id the connection" if hasattr(channel, 'key'): channel = channel.key return "rss_%s>%s" % (url, channel) def create_connection(channel, url, interval): """ This will create a new RSS->channel connection """ if not type(channel) == Channel: new_channel = Channel.objects.filter(db_key=channel) if not new_channel: logger.log_errmsg("Cannot attach RSS->Evennia: Evennia Channel '%s' not found." % channel) return False channel = new_channel[0] key = build_connection_key(channel, url) old_conns = ExternalChannelConnection.objects.filter(db_external_key=key) if old_conns: return False config = "%s|%i" % (url, interval) # There is no sendback from evennia to the rss, so we need not define any sendback code. conn = ExternalChannelConnection(db_channel=channel, db_external_key=key, db_external_config=config) conn.save() connect_to_rss(conn) return True def delete_connection(channel, url): """ Delete rss connection between channel and url """ key = build_connection_key(channel, url) try: conn = ExternalChannelConnection.objects.get(db_external_key=key) except Exception: return False conn.delete() reader = RSS_READERS.get(key, None) if reader and reader.task: reader.task.stop() return True def connect_to_rss(connection): """ Create the parser instance and connect to RSS feed and channel """ global RSS_READERS key = utils.to_str(connection.external_key) url, interval = [utils.to_str(conf) for conf in connection.external_config.split('|')] # Create reader (this starts the running task and stores a reference in RSS_TASKS) RSSReader(key, url, int(interval)) def connect_all(): """ Activate all rss feed parsers """ if not RSS_ENABLED: return for connection in ExternalChannelConnection.objects.filter(db_external_key__startswith="rss_"): print "connecting RSS: %s" % connection connect_to_rss(connection)
Python
""" These managers handles the """ import itertools from django.db import models from django.contrib.contenttypes.models import ContentType from src.utils.utils import is_iter class CommError(Exception): "Raise by comm system, to allow feedback to player when caught." pass # helper function def to_object(inp, objtype='player'): """ Locates the object related to the given playername or channel key. If input was already the correct object, return it. inp - the input object/string objtype - 'player' or 'channel' """ from src.players.models import PlayerDB if objtype == 'player': if type(inp) == PlayerDB: return inp if hasattr(inp, 'player'): return inp.player else: umatch = PlayerDB.objects.filter(user__username__iexact=inp) if umatch: return umatch[0] elif objtype == 'external': from src.comms.models import ExternalChannelConnection if type (inp) == ExternalChannelConnection: return inp umatch = ExternalChannelConnection.objects.filter(db_key=inp) if umatch: return umatch[0] else: # have to import this way to avoid circular imports from src.comms.models import Channel #= ContentType.objects.get(app_label="comms", # model="channel").model_class() if type(inp) == Channel: return inp cmatch = Channel.objects.filter(db_key__iexact=inp) if cmatch: return cmatch[0] return None # # Msg manager # class MsgManager(models.Manager): """ Handle msg database """ def get_message_by_id(self, idnum): "Retrieve message by its id." try: idnum = int(idnum) return self.get(id=id) except Exception: return None def get_messages_by_sender(self, player): """ Get all messages sent by one player """ player = to_object(player, objtype='player') if not player: return None return self.filter(db_sender=player).exclude(db_hide_from_sender=True) def get_messages_by_receiver(self, receiver): """ Get all messages sent to one player """ receiver = to_object(receiver) if not receiver: return None return [msg for msg in self.all() if receiver in msg.receivers and receiver not in msg.hide_from_receivers] def get_messages_by_channel(self, channel): """ Get all messages sent to one channel """ channel = to_object(channel, objtype='channel') if not channel: return None return [msg for msg in self.all() if channel in msg.channels and channel not in msg.hide_from_channels] #TODO add search limited by send_times def text_search(self, searchstring, filterdict=None): """ Returns all messages that contain the matching search string. To avoid too many results, and also since this can be a very computing- heavy operation, it's recommended to be filtered by at least channel or sender/receiver. searchstring - string to search for filterdict - {'channels':[list], 'senders':[list], 'receivers':[list]} lists can contain either the name/keys of the objects or the actual objects to filter by. """ if filterdict: # obtain valid objects for all filters channels = [chan for chan in [to_object(chan, objtype='channel') for chan in filterdict.get('channels',[])] if chan] senders = [sender for sender in [to_object(sender) for sender in filterdict.get('senders',[])] if sender] receivers = [receiver for receiver in [to_object(receiver) for receiver in filterdict.get('receivers',[])] if receiver] # filter the messages lazily using the filter objects msgs = [] for sender in senders: msgs = list(sender.message_set.filter( db_message__icontains=searchstring)) for receiver in receivers: rec_msgs = receiver.message_set.filter( db_message__icontains=searchstring) if msgs: msgs = [msg for msg in rec_msgs if msg in msgs] else: msgs = rec_msgs for channel in channels: chan_msgs = list(channel.message_set.filter( db_message__icontains=searchstring)) if msgs: msgs = [msg for msg in chan_msgs if msg in msgs] else: msgs = chan_msgs return list(set(msgs)) return list(self.all().filter(db_message__icontains=searchstring)) def message_search(self, sender=None, receiver=None, channel=None, freetext=None, dbref=None): """ Search the message database for particular messages. At least one of the arguments must be given to do a search. sender - get messages sent by a particular player receiver - get messages received by a certain player or players channel - get messages sent to a particular channel or channels freetext - Search for a text string in a message. NOTE: This can potentially be slow, so make sure to supply one of the other arguments to limit the search. dbref - (int) the exact database id of the message. This will override all other search crieteria since it's unique and always gives a list with only one match. """ if dbref: return self.filter(id=dbref) if freetext: if sender: sender = [sender] if receiver and not is_iter(receiver): receiver = [receiver] if channel and not is_iter(channel): channel = [channel] filterdict = {"senders":sender, "receivers":receiver, "channels":channel} return self.textsearch(freetext, filterdict) msgs = [] if sender: msgs = self.get_messages_by_sender(sender) if receiver: rec_msgs = self.get_messages_by_receiver(receiver) if msgs: msgs = [msg for msg in rec_msgs if msg in msgs] else: msgs = rec_msgs if channel: chan_msgs = self.get_messaqge_by_channel(channel) if msgs: msgs = [msg for msg in chan_msgs if msg in msgs] else: msgs = chan_msgs return msgs # # Channel manager # class ChannelManager(models.Manager): """ Handle channel database """ def get_all_channels(self): """ Returns all channels in game. """ return self.all() def get_channel(self, channelkey): """ Return the channel object if given its key. Also searches its aliases. """ # first check the channel key channels = self.filter(db_key__iexact=channelkey) if not channels: # also check aliases channels = [channel for channel in self.all() if channelkey in channel.aliases] if channels: return channels[0] return None def del_channel(self, channelkey): """ Delete channel matching channelkey. Also cleans up channelhandler. """ channels = self.filter(db_key__iexact=channelkey) if not channels: # no aliases allowed for deletion. return False for channel in channels: channel.delete() from src.comms.channelhandler import CHANNELHANDLER CHANNELHANDLER.update() return None def get_all_connections(self, channel): """ Return the connections of all players listening to this channel """ # import here to avoid circular imports #from src.comms.models import PlayerChannelConnection PlayerChannelConnection = ContentType.objects.get(app_label="comms", model="playerchannelconnection").model_class() ExternalChannelConnection = ContentType.objects.get(app_label="comms", model="externalchannelconnection").model_class() return itertools.chain(PlayerChannelConnection.objects.get_all_connections(channel), ExternalChannelConnection.objects.get_all_connections(channel)) def channel_search(self, ostring): """ Search the channel database for a particular channel. ostring - the key or database id of the channel. """ channels = [] try: # try an id match first dbref = int(ostring.strip('#')) channels = self.filter(id=dbref) except Exception: pass if not channels: # no id match. Search on the key. channels = self.filter(db_key__iexact=ostring) if not channels: # still no match. Search by alias. channels = [channel for channel in self.all() if ostring.lower in [a.lower for a in channel.aliases]] return channels # # PlayerChannelConnection manager # class PlayerChannelConnectionManager(models.Manager): """ This handles all connections between a player and a channel. """ def get_all_player_connections(self, player): "Get all connections that the given player has." player = to_object(player) return self.filter(db_player=player) def has_connection(self, player, channel): "Checks so a connection exists player<->channel" player = to_object(player) channel = to_object(channel, objtype="channel") if player and channel: return self.filter(db_player=player).filter(db_channel=channel).count() > 0 return False def get_all_connections(self, channel): """ Get all connections for a channel """ channel = to_object(channel, objtype='channel') return self.filter(db_channel=channel) def create_connection(self, player, channel): """ Connect a player to a channel. player and channel can be actual objects or keystrings. """ player = to_object(player) channel = to_object(channel, objtype='channel') if not player or not channel: raise CommError("NOTFOUND") new_connection = self.model(db_player=player, db_channel=channel) new_connection.save() return new_connection def break_connection(self, player, channel): "Remove link between player and channel" player = to_object(player) channel = to_object(channel, objtype='channel') if not player or not channel: raise CommError("NOTFOUND") conns = self.filter(db_player=player).filter(db_channel=channel) for conn in conns: conn.delete() class ExternalChannelConnectionManager(models.Manager): """ This handles all connections between a external and a channel. """ def get_all_external_connections(self, external): "Get all connections that the given external." external = to_object(external, objtype='external') return self.filter(db_external_key=external) def has_connection(self, external, channel): "Checks so a connection exists external<->channel" external = to_object(external, objtype='external') channel = to_object(channel, objtype="channel") if external and channel: return self.filter(db_external_key=external).filter(db_channel=channel).count() > 0 return False def get_all_connections(self, channel): """ Get all connections for a channel """ channel = to_object(channel, objtype='channel') return self.filter(db_channel=channel) def create_connection(self, external, channel, config=""): """ Connect a external to a channel. external and channel can be actual objects or keystrings. """ channel = to_object(channel, objtype='channel') if not channel: raise CommError("NOTFOUND") new_connection = self.model(db_external_key=external, db_channel=channel, db_external_config=config) new_connection.save() return new_connection def break_connection(self, external, channel): "Remove link between external and channel" external = to_object(external) channel = to_object(channel, objtype='channel') if not external or not channel: raise CommError("NOTFOUND") conns = self.filter(db_external_key=external).filter(db_channel=channel) for conn in conns: conn.delete()
Python
""" Evennia Line Editor Contribution - Griatch 2011 This implements an advanced line editor for editing longer texts in-game. The editor mimics the command mechanisms of the VI editor as far as possible. Features of the editor: undo/redo edit/replace on any line of the buffer search&replace text anywhere in buffer formatting of buffer, or selection, to certain width + indentations allow to echo the input or not depending on your client. """ import re from src.commands.command import Command from src.commands.cmdset import CmdSet from src.commands.cmdhandler import CMD_NOMATCH, CMD_NOINPUT from src.utils import utils from contrib.menusystem import prompt_yesno RE_GROUP = re.compile(r"\".*?\"|\'.*?\'|\S*") class CmdEditorBase(Command): """ Base parent for editor commands """ locks = "cmd:all()" help_entry = "LineEditor" code = None editor = None def parse(self): """ Handles pre-parsing Editor commands are on the form :cmd [li] [w] [txt] Where all arguments are optional. li - line number (int), starting from 1. This could also be a range given as <l>:<l> w - word(s) (string), could be encased in quotes. txt - extra text (string), could be encased in quotes """ linebuffer = [] if self.editor: linebuffer = self.editor.buffer.split("\n") nlines = len(linebuffer) # The regular expression will split the line by whitespaces, # stripping extra whitespaces, except if the text is # surrounded by single- or double quotes, in which case they # will be kept together and extra whitespace preserved. You # can input quotes on the line by alternating single and # double quotes. arglist = [part for part in RE_GROUP.findall(self.args) if part] temp = [] for arg in arglist: # we want to clean the quotes, but only one type, in case we are nesting. if arg.startswith('"'): arg.strip('"') elif arg.startswith("'"): arg.strip("'") temp.append(arg) arglist = temp # A dumb split, without grouping quotes words = self.args.split() # current line number cline = nlines - 1 # the first argument could also be a range of line numbers, on the # form <lstart>:<lend>. Either of the ends could be missing, to # mean start/end of buffer respectively. lstart, lend = cline, cline + 1 linerange = False if arglist and ':' in arglist[0]: part1, part2 = arglist[0].split(':') if part1 and part1.isdigit(): lstart = min(max(0, int(part1)) - 1, nlines) linerange = True if part2 and part2.isdigit(): lend = min(lstart + 1, int(part2)) + 1 linerange = True elif arglist and arglist[0].isdigit(): lstart = min(max(0, int(arglist[0]) - 1), nlines) lend = lstart + 1 linerange = True if linerange: arglist = arglist[1:] # nicer output formatting of the line range. lstr = "" if not linerange or lstart + 1 == lend: lstr = "line %i" % (lstart + 1) else: lstr = "lines %i-%i" % (lstart + 1, lend) # arg1 and arg2 is whatever arguments. Line numbers or -ranges are never included here. args = " ".join(arglist) arg1, arg2 = "", "" if len(arglist) > 1: arg1, arg2 = arglist[0], " ".join(arglist[1:]) else: arg1 = " ".join(arglist) # store for use in func() self.linebuffer = linebuffer self.nlines = nlines self.arglist = arglist self.cline = cline self.lstart = lstart self.lend = lend self.linerange = linerange self.lstr = lstr self.words = words self.args = args self.arg1 = arg1 self.arg2 = arg2 def func(self): "Implements the Editor commands" pass class CmdLineInput(CmdEditorBase): """ No command match - Inputs line of text into buffer. """ key = CMD_NOMATCH aliases = [CMD_NOINPUT] def func(self): "Adds the line without any formatting changes." # add a line of text if not self.editor.buffer: buf = self.args else: buf = self.editor.buffer + "\n%s" % self.args self.editor.update_buffer(buf) if self.editor.echo_mode: self.caller.msg("%02i| %s" % (self.cline + 1, self.args)) class CmdEditorGroup(CmdEditorBase): """ Commands for the editor """ key = ":editor_command_group" aliases = [":","::", ":::", ":h", ":w", ":wq", ":q", ":q!", ":u", ":uu", ":UU", ":dd", ":dw", ":DD", ":y", ":x", ":p", ":i", ":r", ":I", ":A", ":s", ":S", ":f", ":fi", ":fd", ":echo"] def func(self): """ This command handles all the in-editor :-style commands. Since each command is small and very limited, this makes for a more efficient presentation. """ caller = self.caller editor = self.editor linebuffer = self.linebuffer lstart, lend = self.lstart, self.lend cmd = self.cmdstring echo_mode = self.editor.echo_mode string = "" if cmd == ":": # Echo buffer if self.linerange: buf = linebuffer[lstart:lend] string = editor.display_buffer(buf=buf, offset=lstart) else: string = editor.display_buffer() elif cmd == "::": # Echo buffer without the line numbers and syntax parsing if self.linerange: buf = linebuffer[lstart:lend] string = editor.display_buffer(buf=buf, offset=lstart, linenums=False) else: string = editor.display_buffer(linenums=False) self.caller.msg(string, data={"raw":True}) return elif cmd == ":::": # Insert single colon alone on a line editor.update_buffer(editor.buffer + "\n:") if echo_mode: string = "Single ':' added to buffer." elif cmd == ":h": # help entry string = editor.display_help() elif cmd == ":w": # save without quitting string = editor.save_buffer() elif cmd == ":wq": # save and quit string = editor.save_buffer() string += " " + editor.quit() elif cmd == ":q": # quit. If not saved, will ask if self.editor.unsaved: prompt_yesno(caller, "Save before quitting?", yescode = "self.caller.ndb._lineeditor.save_buffer()\nself.caller.ndb._lineeditor.quit()", nocode = "self.caller.msg(self.caller.ndb._lineeditor.quit())", default="Y") else: string = editor.quit() elif cmd == ":q!": # force quit, not checking saving string = editor.quit() elif cmd == ":u": # undo string = editor.update_undo(-1) elif cmd == ":uu": # redo string = editor.update_undo(1) elif cmd == ":UU": # reset buffer editor.update_buffer(editor.pristine_buffer) string = "Reverted all changes to the buffer back to original state." elif cmd == ":dd": # :dd <l> - delete line <l> buf = linebuffer[:lstart] + linebuffer[lend:] editor.update_buffer(buf) string = "Deleted %s." % (self.lstr) elif cmd == ":dw": # :dw <w> - delete word in entire buffer # :dw <l> <w> delete word only on line(s) <l> if not self.arg1: string = "You must give a search word to delete." else: if not self.linerange: lstart = 0 lend = self.cline + 1 string = "Removed %s for lines %i-%i." % (self.arg1, lstart + 1 , lend + 1) else: string = "Removed %s for %s." % (self.arg1, self.lstr) sarea = "\n".join(linebuffer[lstart:lend]) sarea = re.sub(r"%s" % self.arg1.strip("\'").strip('\"'), "", sarea, re.MULTILINE) buf = linebuffer[:lstart] + sarea.split("\n") + linebuffer[lend:] editor.update_buffer(buf) elif cmd == ":DD": # clear buffer editor.update_buffer("") string = "Cleared %i lines from buffer." % self.nlines elif cmd == ":y": # :y <l> - yank line(s) to copy buffer cbuf = linebuffer[lstart:lend] editor.copy_buffer = cbuf string = "%s, %s yanked." % (self.lstr.capitalize(), cbuf) elif cmd == ":x": # :x <l> - cut line to copy buffer cbuf = linebuffer[lstart:lend] editor.copy_buffer = cbuf buf = linebuffer[:lstart] + linebuffer[lend:] editor.update_buffer(buf) string = "%s, %s cut." % (self.lstr.capitalize(), cbuf) elif cmd == ":p": # :p <l> paste line(s) from copy buffer if not editor.copy_buffer: string = "Copy buffer is empty." else: buf = linebuffer[:lstart] + editor.copy_buffer + linebuffer[lstart:] editor.update_buffer(buf) string = "Copied buffer %s to %s." % (editor.copy_buffer, self.lstr) elif cmd == ":i": # :i <l> <txt> - insert new line new_lines = self.args.split('\n') if not new_lines: string = "You need to enter a new line and where to insert it." else: buf = linebuffer[:lstart] + new_lines + linebuffer[lstart:] editor.update_buffer(buf) string = "Inserted %i new line(s) at %s." % (len(new_lines), self.lstr) elif cmd == ":r": # :r <l> <txt> - replace lines new_lines = self.args.split('\n') if not new_lines: string = "You need to enter a replacement string." else: buf = linebuffer[:lstart] + new_lines + linebuffer[lend:] editor.update_buffer(buf) string = "Replaced %i line(s) at %s." % (len(new_lines), self.lstr) elif cmd == ":I": # :I <l> <txt> - insert text at beginning of line(s) <l> if not self.args: string = "You need to enter text to insert." else: buf = linebuffer[:lstart] + ["%s%s" % (self.args, line) for line in linebuffer[lstart:lend]] + linebuffer[lend:] editor.update_buffer(buf) string = "Inserted text at beginning of %s." % self.lstr elif cmd == ":A": # :A <l> <txt> - append text after end of line(s) if not self.args: string = "You need to enter text to append." else: buf = linebuffer[:lstart] + ["%s%s" % (line, self.args) for line in linebuffer[lstart:lend]] + linebuffer[lend:] editor.update_buffer(buf) string = "Appended text to end of %s." % self.lstr elif cmd == ":s": # :s <li> <w> <txt> - search and replace words in entire buffer or on certain lines if not self.arg1 or not self.arg2: string = "You must give a search word and something to replace it with." else: if not self.linerange: lstart = 0 lend = self.cline + 1 string = "Search-replaced %s -> %s for lines %i-%i." % (self.arg1, self.arg2, lstart + 1 , lend) else: string = "Search-replaced %s -> %s for %s." % (self.arg1, self.arg2, self.lstr) sarea = "\n".join(linebuffer[lstart:lend]) regex = r"%s|^%s(?=\s)|(?<=\s)%s(?=\s)|^%s$|(?<=\s)%s$" regarg = self.arg1.strip("\'").strip('\"') if " " in regarg: regarg = regarg.replace(" ", " +") sarea = re.sub(regex % (regarg, regarg, regarg, regarg, regarg), self.arg2.strip("\'").strip('\"'), sarea, re.MULTILINE) buf = linebuffer[:lstart] + sarea.split("\n") + linebuffer[lend:] editor.update_buffer(buf) elif cmd == ":f": # :f <l> flood-fill buffer or <l> lines of buffer. width = 78 if not self.linerange: lstart = 0 lend = self.cline + 1 string = "Flood filled lines %i-%i." % (lstart + 1 , lend) else: string = "Flood filled %s." % self.lstr fbuf = "\n".join(linebuffer[lstart:lend]) fbuf = utils.fill(fbuf, width=width) buf = linebuffer[:lstart] + fbuf.split("\n") + linebuffer[lend:] editor.update_buffer(buf) elif cmd == ":fi": # :fi <l> indent buffer or lines <l> of buffer. indent = " " * 4 if not self.linerange: lstart = 0 lend = self.cline + 1 string = "Indented lines %i-%i." % (lstart + 1 , lend) else: string = "Indented %s." % self.lstr fbuf = [indent + line for line in linebuffer[lstart:lend]] buf = linebuffer[:lstart] + fbuf + linebuffer[lend:] editor.update_buffer(buf) elif cmd == ":fd": # :fi <l> indent buffer or lines <l> of buffer. if not self.linerange: lstart = 0 lend = self.cline + 1 string = "Removed left margin (dedented) lines %i-%i." % (lstart + 1 , lend) else: string = "Removed left margin (dedented) %s." % self.lstr fbuf = "\n".join(linebuffer[lstart:lend]) fbuf = utils.dedent(fbuf) buf = linebuffer[:lstart] + fbuf.split("\n") + linebuffer[lend:] editor.update_buffer(buf) elif cmd == ":echo": # set echoing on/off editor.echo_mode = not editor.echo_mode string = "Echo mode set to %s" % editor.echo_mode caller.msg(string) class EditorCmdSet(CmdSet): "CmdSet for the editor commands" key = "editorcmdset" mergetype = "Replace" class LineEditor(object): """ This defines a line editor object. It creates all relevant commands and tracks the current state of the buffer. It also cleans up after itself. """ def __init__(self, caller, loadcode="", savecode="", key=""): """ caller - who is using the editor loadcode - code to execute in order to load already existing text into the buffer savecode - code to execute in order to save the result key = an optional key for naming this session (such as which attribute is being edited) """ self.key = key self.caller = caller self.caller.ndb._lineeditor = self self.buffer = "" self.unsaved = False if loadcode: try: exec(loadcode) except Exception, e: caller.msg("%s\n{rBuffer loadcode failed. Could not load initial data.{n" % e) # Create the commands we need cmd1 = CmdLineInput() cmd1.editor = self cmd1.obj = self cmd2 = CmdEditorGroup() cmd2.obj = self cmd2.editor = self # Populate cmdset and add it to caller editor_cmdset = EditorCmdSet() editor_cmdset.add(cmd1) editor_cmdset.add(cmd2) self.caller.cmdset.add(editor_cmdset) # store the original version self.pristine_buffer = self.buffer self.savecode = savecode self.sep = "-" # undo operation buffer self.undo_buffer = [self.buffer] self.undo_pos = 0 self.undo_max = 20 # copy buffer self.copy_buffer = [] # echo inserted text back to caller self.echo_mode = False # show the buffer ui self.caller.msg(self.display_buffer()) def update_buffer(self, buf): """ This should be called when the buffer has been changed somehow. It will handle unsaved flag and undo updating. """ if utils.is_iter(buf): buf = "\n".join(buf) if buf != self.buffer: self.buffer = buf self.update_undo() self.unsaved = True def quit(self): "Cleanly exit the editor." del self.caller.ndb._lineeditor self.caller.cmdset.delete(EditorCmdSet) return "Exited editor." def save_buffer(self): "Saves the content of the buffer" if self.unsaved: try: exec(self.savecode) self.unsaved = False return "Buffer saved." except Exception, e: return "%s\n{rSave code gave an error. Buffer not saved." % e else: return "No changes need saving." def update_undo(self, step=None): """ This updates the undo position. """ if step and step < 0: if self.undo_pos <= 0: return "Nothing to undo." self.undo_pos = max(0, self.undo_pos + step) self.buffer = self.undo_buffer[self.undo_pos] return "Undo." elif step and step > 0: if self.undo_pos >= len(self.undo_buffer) - 1 or self.undo_pos + 1 >= self.undo_max: return "Nothing to redo." self.undo_pos = min(self.undo_pos + step, min(len(self.undo_buffer), self.undo_max) - 1) self.buffer = self.undo_buffer[self.undo_pos] return "Redo." if not self.undo_buffer or (self.undo_buffer and self.buffer != self.undo_buffer[self.undo_pos]): self.undo_buffer = self.undo_buffer[:self.undo_pos + 1] + [self.buffer] self.undo_pos = len(self.undo_buffer) - 1 def display_buffer(self, buf=None, offset=0, linenums=True): """ This displays the line editor buffer, or selected parts of it. If buf is set and is not the full buffer, offset should define the starting line number, to get the linenum display right. """ if buf == None: buf = self.buffer if utils.is_iter(buf): buf = "\n".join(buf) lines = buf.split('\n') nlines = len(lines) nwords = len(buf.split()) nchars = len(buf) sep = self.sep header = "{n" + sep * 10 + "Line Editor [%s]" % self.key + sep * (78-25-len(self.key)) footer = "{n" + sep * 10 + "[l:%02i w:%03i c:%04i]" % (nlines, nwords, nchars) + sep * 12 + "(:h for help)" + sep * 23 if linenums: main = "\n".join("{b%02i|{n %s" % (iline + 1 + offset, line) for iline, line in enumerate(lines)) else: main = "\n".join(lines) string = "%s\n%s\n%s" % (header, main, footer) return string def display_help(self): """ Shows the help entry for the editor. """ string = self.sep*78 + """ <txt> - any non-command is appended to the end of the buffer. : <l> - view buffer or only line <l> :: <l> - view buffer without line numbers or other parsing ::: - print a ':' as the only character on the line... :h - this help. :w - saves the buffer (don't quit) :wq - save buffer and quit :q - quits (will be asked to save if buffer was changed) :q! - quit without saving, no questions asked :u - (undo) step backwards in undo history :uu - (redo) step forward in undo history :UU - reset all changes back to initial :dd <l> - delete line <n> :dw <l> <w> - delete word or regex <w> in entire buffer or on line <l> :DD - clear buffer :y <l> - yank (copy) line <l> to the copy buffer :x <l> - cut line <l> and store it in the copy buffer :p <l> - put (paste) previously copied line directly after <l> :i <l> <txt> - insert new text <txt> at line <l>. Old line will be shifted down :r <l> <txt> - replace line <l> with text <txt> :I <l> <txt> - insert text at the beginning of line <l> :A <l> <txt> - append text after the end of line <l> :s <l> <w> <txt> - search/replace word or regex <w> in buffer or on line <l> :f <l> - flood-fill entire buffer or line <l> :fi <l> - indent entire buffer or line <l> :fd <l> - de-indent entire buffer or line <l> :echo - turn echoing of the input on/off (helpful for some clients) Legend: <l> - line numbers, or range lstart:lend, e.g. '3:7'. <w> - one word or several enclosed in quotes. <txt> - longer string, usually not needed to be enclosed in quotes. """ + self.sep * 78 return string # # Editor access command for editing a given attribute on an object. # class CmdEditor(Command): """ start editor Usage: @editor <obj>/<attr> This will start Evennia's powerful line editor, which has a host of commands on its own. Use :h for a list of commands. """ key = "@editor" aliases = ["@edit"] locks = "cmd:perm(editor) or perm(Builders)" help_category = "Building" def func(self): "setup and start the editor" if not self.args or not '/' in self.args: self.caller.msg("Usage: @editor <obj>/<attrname>") return objname, attrname = [part.strip() for part in self.args.split("/")] obj = self.caller.search(objname) if not obj: return # the load/save codes define what the editor shall do when wanting to # save the result of the editing. The editor makes self.buffer and # self.caller available for this code - self.buffer holds the editable text. loadcode = "obj = self.caller.search('%s')\n" % obj.id loadcode += "if obj.db.%s: self.buffer = obj.db.%s" % (attrname, attrname) savecode = "obj = self.caller.search('%s')\n" % obj.id savecode += "obj.db.%s = self.buffer" % attrname editor_key = "%s/%s" % (objname, attrname) # start editor, it will handle things from here. LineEditor(self.caller, loadcode=loadcode, savecode=savecode, key=editor_key)
Python
""" Evennia menu system. Contribution - Griatch 2011 This module offers the ability for admins to let their game be fully or partly menu-driven. Menu choices can be numbered or use arbitrary keys. There are also some formatting options, such a putting options in one or more collumns. The menu system consists of a MenuTree object populated by MenuNode objects. Nodes are linked together with automatically created commands so the player may select and traverse the menu. Each node can display text and show options, but also execute arbitrary code to act on the system and the calling object when they are selected. There is also a simple Yes/No function supplied. This will create a one-off Yes/No question and executes a given code depending on which choice was made. To test, import and add the CmdTestMenu command to the end of the default cmdset in game.gamesrc.commands.basecmdset. The test command is also a good example of how to use this module in code. """ from src.commands.cmdhandler import CMD_NOMATCH, CMD_NOINPUT from src.commands.command import Command from src.commands.cmdset import CmdSet from src.commands.default.general import CmdLook from src.commands.default.help import CmdHelp from src.utils import utils # imported only to make them available during execution of code blocks from src.objects.models import ObjectDB from src.players.models import PlayerDB # # Commands used by the Menu system # class CmdMenuNode(Command): """ Parent for menu selection commands. """ key = "selection" aliases = [] locks = "cmd:all()" help_category = "Menu" menutree = None code = None def func(self): "Execute a selection" if self.code: try: exec(self.code) except Exception, e: self.caller.msg("%s\n{rThere was an error with this selection.{n" % e) else: self.caller.msg("{rThis option is not available.{n") class CmdMenuLook(CmdLook): """ ooc look Usage: look This is a Menu version of the look command. It will normally show the options available, otherwise works like the normal look command.. """ key = "look" aliases = ["l", "ls"] locks = "cmd:all()" help_cateogory = "General" def func(self): "implement the menu look command" if self.caller.db._menu_data: # if we have menu data, try to use that. lookstring = self.caller.db._menu_data.get("look", None) if lookstring: self.caller.msg(lookstring) return # otherwise we use normal look super(CmdMenuLook, self).func() class CmdMenuHelp(CmdHelp): """ help Usage: help Get help specific to the menu, if available. If not, works like the normal help command. """ key = "help" aliases = "h" locks = "cmd:all()" help_category = "Menu" def func(self): "implement the menu help command" if self.caller.db._menu_data: # if we have menu data, try to use that. lookstring = self.caller.db._menu_data.get("help", None) if lookstring: self.caller.msg(lookstring) return # otherwise we use normal help super(CmdMenuHelp, self).func() class MenuCmdSet(CmdSet): """ Cmdset for the menu. Will replace all other commands. This always has a few basic commands available. Note that you must always supply a way to exit the cmdset manually! """ key = "menucmdset" priority = 1 mergetype = "Replace" def at_cmdset_creation(self): "populate cmdset" pass # # Menu Node system # class MenuTree(object): """ The menu tree object holds the full menu structure consisting of MenuNodes. Each node is identified by a unique key. The tree allows for traversal of nodes as well as entering and exiting the tree as needed. For safety, being in a menu will not survive a server reboot. A menutree have two special node keys given by 'startnode' and 'endnode' arguments. The startnode is where the user will start upon first entering the menu. The endnode need not actually exist, the moment it is linked to and that link is used, the menu will be exited and cleanups run. The default keys for these are 'START' and 'END' respectively. """ def __init__(self, caller, nodes=None, startnode="START", endnode="END", exec_end="look"): """ We specify startnode/endnode so that the system knows where to enter and where to exit the menu tree. If nodes is given, it shuld be a list of valid node objects to add to the tree. exec_end - if not None, will execute the given command string directly after the menu system has been exited. """ self.tree = {} self.startnode = startnode self.endnode = endnode self.exec_end = exec_end self.caller = caller if nodes and utils.is_iter(nodes): for node in nodes: self.add(node) def start(self): """ Initialize the menu """ self.goto(self.startnode) def add(self, menunode): """ Add a menu node object to the tree. Each node itself keeps track of which nodes it is connected to. """ menunode.init(self) self.tree[menunode.key] = menunode def goto(self, key): """ Go to a key in the tree. This sets up the cmdsets on the caller so that they match the choices in that node. """ if key == self.endnode: # if we was given the END node key, we clean up immediately. self.caller.cmdset.delete("menucmdset") del self.caller.db._menu_data if self.exec_end != None: self.caller.execute_cmd(self.exec_end) return # not exiting, look for a valid code. node = self.tree.get(key, None) if node: if node.code: # Execute eventual code active on this # node. self.caller is available at this point. try: exec(node.code) except Exception, e: self.caller.msg("{rCode could not be executed for node %s. Continuing anyway.{n" % key) # clean old menu cmdset and replace with the new one self.caller.cmdset.delete("menucmdset") self.caller.cmdset.add(node.cmdset) # set the menu flag data for the default commands self.caller.db._menu_data = {"help":node.helptext, "look":str(node.text)} # display the node self.caller.msg(node.text) else: self.caller.msg("{rMenu node '%s' does not exist - maybe it's not created yet..{n" % key) class MenuNode(object): """ This represents a node in a menu tree. The node will display its textual content and offer menu links to other nodes (the relevant commands are created automatically) """ def __init__(self, key, text="", links=None, linktexts=None, keywords=None, cols=1, helptext=None, selectcmds=None, code="", nodefaultcmds=False, separator=""): """ key - the unique identifier of this node. text - is the text that will be displayed at top when viewing this node. links - a list of keys for unique menunodes this is connected to. The actual keys will not be printed - keywords will be used (or a number) linktexts - an optional list of texts to describe the links. Must match link list if defined. Entries can be None to not generate any extra text for a particular link. keywords - an optional list of unique keys for choosing links. Must match links list. If not given, index numbers will be used. Also individual list entries can be None and will be replaed by indices. If CMD_NOMATCH or CMD_NOENTRY, no text will be generated to indicate the option exists. cols - how many columns to use for displaying options. helptext - if defined, this is shown when using the help command instead of the normal help index. selectcmds- a list of custom cmdclasses for handling each option. Must match links list, but some entries may be set to None to use default menu cmds. The given command's key will be used for the menu list entry unless it's CMD_NOMATCH or CMD_NOENTRY, in which case no text will be generated. These commands have access to self.menutree and so can be used to select nodes. code - functional code. This will be executed just before this node is loaded (i.e. as soon after it's been selected from another node). self.caller is available to call from this code block, as well as ObjectDB and PlayerDB. nodefaultcmds - if true, don't offer the default help and look commands in the node separator - this string will be put on the line between menu nodes5B. """ self.key = key self.cmdset = None self.links = links self.linktexts = linktexts self.keywords = keywords self.cols = cols self.selectcmds = selectcmds self.code = code self.nodefaultcmds = nodefaultcmds self.separator = separator Nlinks = len(self.links) # validate the input if not self.links: self.links = [] if not self.linktexts or (len(self.linktexts) != Nlinks): self.linktexts = [None for i in range(Nlinks)] if not self.keywords or (len(self.keywords) != Nlinks): self.keywords = [None for i in range(Nlinks)] if not selectcmds or (len(self.selectcmds) != Nlinks): self.selectcmds = [None for i in range(Nlinks)] # Format default text for the menu-help command if not helptext: helptext = "Select one of the valid options (" for i in range(Nlinks): if self.keywords[i]: if self.keywords[i] not in (CMD_NOMATCH, CMD_NOINPUT): helptext += "%s, " % self.keywords[i] else: helptext += "%s, " % (i + 1) helptext = helptext.rstrip(", ") + ")" self.helptext = helptext # Format text display string = "" if text: string += "%s\n" % text # format the choices into as many collumns as specified choices = [] for ilink, link in enumerate(self.links): choice = "" if self.keywords[ilink]: if self.keywords[ilink] not in (CMD_NOMATCH, CMD_NOINPUT): choice += "{g%s{n" % self.keywords[ilink] else: choice += "{g %i{n" % (ilink + 1) if self.linktexts[ilink]: choice += " - %s" % self.linktexts[ilink] choices.append(choice) cols = [[] for i in range(min(len(choices), cols))] while True: for i in range(len(cols)): if not choices: cols[i].append("") else: cols[i].append(choices.pop(0)) if not choices: break ftable = utils.format_table(cols) for row in ftable: string +="\n" + "".join(row) # store text self.text = self.separator + "\n" + string.rstrip() def init(self, menutree): """ Called by menu tree. Initializes the commands needed by the menutree structure. """ # Create the relevant cmdset self.cmdset = MenuCmdSet() if not self.nodefaultcmds: # add default menu commands self.cmdset.add(CmdMenuLook()) self.cmdset.add(CmdMenuHelp()) for i, link in enumerate(self.links): if self.selectcmds[i]: cmd = self.selectcmds[i]() else: cmd = CmdMenuNode() cmd.key = str(i + 1) # this is the operable command, it moves us to the next node. cmd.code = "self.menutree.goto('%s')" % link # also custom commands get access to the menutree. cmd.menutree = menutree if self.keywords[i] and cmd.key not in (CMD_NOMATCH, CMD_NOINPUT): cmd.aliases = [self.keywords[i]] self.cmdset.add(cmd) def __str__(self): "Returns the string representation." return self.text # # A simple yes/no question. Call this from a command to give object # a cmdset where they may say yes or no to a question. Does not # make use the node system since there is only one level of choice. # def prompt_yesno(caller, question="", yescode="", nocode="", default="N"): """ This sets up a simple yes/no questionnaire. Question will be asked, followed by a Y/[N] prompt where the [x] signifies the default selection. """ # creating and defining commands cmdyes = CmdMenuNode() cmdyes.key = "yes" cmdyes.aliases = ["y"] # this will be executed in the context of the yes command (so self.caller will be available) cmdyes.code = yescode + "\nself.caller.cmdset.delete('menucmdset')\ndel self.caller.db._menu_data" cmdno = CmdMenuNode() cmdno.key = "no" cmdno.aliases = ["n"] # this will be executed in the context of the no command cmdno.code = nocode + "\nself.caller.cmdset.delete('menucmdset')\ndel self.caller.db._menu_data" errorcmd = CmdMenuNode() errorcmd.key = CMD_NOMATCH errorcmd.code = "self.caller.msg('Please choose either Yes or No.')" defaultcmd = CmdMenuNode() defaultcmd.key = CMD_NOINPUT defaultcmd.code = "self.caller.execute_cmd('%s')" % default # creating cmdset (this will already have look/help commands) yesnocmdset = MenuCmdSet() yesnocmdset.add(cmdyes) yesnocmdset.add(cmdno) yesnocmdset.add(errorcmd) yesnocmdset.add(defaultcmd) # assinging menu data flags to caller. caller.db._menu_data = {"help":"Please select Yes or No.", "look":"Please select Yes or No."} # assign cmdset and ask question caller.cmdset.add(yesnocmdset) if default == "Y": prompt = "[Y]/N" else: prompt = "Y/[N]" prompt = "%s %s: " % (question, prompt) caller.msg(prompt) # # Menu command test # class CmdMenuTest(Command): """ testing menu module Usage: menu menu yesno This will test the menu system. The normal operation will produce a small menu tree you can move around in. The 'yesno' option will instead show a one-time yes/no question. """ key = "menu" locks = "cmd:all()" help_category = "Menu" def func(self): "Testing the menu system" if not self.args or self.args != "yesno": # testing the full menu-tree system node0 = MenuNode("START", text="Start node. Select one of the links below. Here the links are ordered in one column.", links=["node1", "node2", "END"], linktexts=["Goto first node", "Goto second node", "Quit"]) node1 = MenuNode("node1", text="First node. This node shows letters instead of numbers for the choices.", links=["END", "START"], linktexts=["Quit", "Back to start"], keywords=["q","b"]) node2 = MenuNode("node2", text="Second node. This node lists choices in two columns.", links=["node3", "START"], linktexts=["Set an attribute", "Back to start"], cols=2) node3 = MenuNode("node3", text="Attribute 'menutest' set on you. You can examine it (only works if you are allowed to use the examine command) or remove it. You can also quit and examine it manually.", links=["node4", "node5", "node2", "END"], linktexts=["Remove attribute", "Examine attribute", "Back to second node", "Quit menu"], cols=2, code="self.caller.db.menutest='Testing!'") node4 = MenuNode("node4", text="Attribute 'menutest' removed again.", links=["node2"], linktexts=["Back to second node."], cols=2, code="del self.caller.db.menutest") node5 = MenuNode("node5", links=["node4", "node2"], linktexts=["Remove attribute", "Back to second node."], cols=2, code="self.caller.msg('%s/%s = %s' % (self.caller.key, 'menutest', self.caller.db.menutest))") menu = MenuTree(self.caller, nodes=(node0, node1, node2, node3, node4, node5)) menu.start() else: "Testing the yesno question" prompt_yesno(self.caller, question="Please answer yes or no - Are you the master of this mud or not?", yescode="self.caller.msg('{gGood for you!{n')", nocode="self.caller.msg('{GNow you are just being modest ...{n')", default="N")
Python
""" Room Typeclasses for the TutorialWorld. """ import random from src.commands.cmdset import CmdSet from src.utils import create, utils from src.objects.models import ObjectDB from game.gamesrc.scripts.basescript import Script from game.gamesrc.commands.basecommand import Command from game.gamesrc.objects.baseobjects import Room from contrib.tutorial_world import scripts as tut_scripts from contrib.tutorial_world.objects import LightSource, TutorialObject #------------------------------------------------------------ # # Tutorial room - parent room class # # This room is the parent of all rooms in the tutorial. # It defines a tutorial command on itself (available to # all who is in a tutorial room). # #------------------------------------------------------------ class CmdTutorial(Command): """ Get help during the tutorial Usage: tutorial [obj] This command allows you to get behind-the-scenes info about an object or the current location. """ key = "tutorial" aliases = ["tut"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """ All we do is to scan the current location for an attribute called `tutorial_info` and display that. """ caller = self.caller if not self.args: target = self.obj # this is the room object the command is defined on else: target = caller.search(self.args.strip()) if not target: return helptext = target.db.tutorial_info if helptext: caller.msg("{G%s{n" % helptext) else: caller.msg("{RSorry, there is no tutorial help available here.{n") class TutorialRoomCmdSet(CmdSet): "Implements the simple tutorial cmdset" key = "tutorial_cmdset" def at_cmdset_creation(self): "add the tutorial cmd" self.add(CmdTutorial()) class TutorialRoom(Room): """ This is the base room type for all rooms in the tutorial world. It defines a cmdset on itself for reading tutorial info about the location. """ def at_object_creation(self): "Called when room is first created" self.db.tutorial_info = "This is a tutorial room. It allows you to use the 'tutorial' command." self.cmdset.add_default(TutorialRoomCmdSet) def reset(self): "Can be called by the tutorial runner." pass #------------------------------------------------------------ # # Weather room - scripted room # # The weather room is called by a script at # irregular intervals. The script is generally useful # and so is split out into tutorialworld.scripts. # #------------------------------------------------------------ class WeatherRoom(TutorialRoom): """ This should probably better be called a rainy room... This sets up an outdoor room typeclass. At irregular intervals, the effects of weather will show in the room. Outdoor rooms should inherit from this. """ def at_object_creation(self): "Called when object is first created." super(WeatherRoom, self).at_object_creation() # we use the imported IrregularEvent script self.scripts.add(tut_scripts.IrregularEvent) self.db.tutorial_info = \ "This room has a Script running that has it echo a weather-related message at irregular intervals." def update_irregular(self): "create a tuple of possible texts to return." strings = ( "The rain coming down from the iron-grey sky intensifies.", "A gush of wind throws the rain right in your face. Despite your cloak you shiver.", "The rainfall eases a bit and the sky momentarily brightens.", "For a moment it looks like the rain is slowing, then it begins anew with renewed force.", "The rain pummels you with large, heavy drops. You hear the rumble of thunder in the distance.", "The wind is picking up, howling around you, throwing water droplets in your face. It's cold.", "Bright fingers of lightning flash over the sky, moments later followed by a deafening rumble.", "It rains so hard you can hardly see your hand in front of you. You'll soon be drenched to the bone.", "Lightning strikes in several thundering bolts, striking the trees in the forest to your west.", "You hear the distant howl of what sounds like some sort of dog or wolf.", "Large clouds rush across the sky, throwing their load of rain over the world.") # get a random value so we can select one of the strings above. Send this to the room. irand = random.randint(0, 15) if irand > 10: return # don't return anything, to add more randomness self.msg_contents("{w%s{n" % strings[irand]) #----------------------------------------------------------------------------------- # # Dark Room - a scripted room # # This room limits the movemenets of its denizens unless they carry a and active # LightSource object (LightSource is defined in tutorialworld.objects.LightSource) # #----------------------------------------------------------------------------------- class CmdLookDark(Command): """ Look around in darkness Usage: look Looks in darkness """ key = "look" aliases = ["l", 'feel', 'feel around', 'fiddle'] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "Implement the command." caller = self.caller # we don't have light, grasp around blindly. messages = ("It's pitch black. You fumble around but cannot find anything.", "You don't see a thing. You feel around, managing to bump your fingers hard against something. Ouch!", "You don't see a thing! Blindly grasping the air around you, you find nothing.", "It's totally dark here. You almost stumble over some un-evenness in the ground.", "You are completely blind. For a moment you think you hear someone breathing nearby ... \n ... surely you must be mistaken.", "Blind, you think you find some sort of object on the ground, but it turns out to be just a stone.", "Blind, you bump into a wall. The wall seems to be covered with some sort of vegetation, but its too damp to burn.", "You can't see anything, but the air is damp. It feels like you are far underground.") irand = random.randint(0, 10) if irand < len(messages): caller.msg(messages[irand]) else: # check so we don't already carry a lightsource. carried_lights = [obj for obj in caller.contents if utils.inherits_from(obj, LightSource)] if carried_lights: string = "You don't want to stumble around in blindness anymore. You already found what you need. Let's get light already!" caller.msg(string) return #if we are lucky, we find the light source. lightsources = [obj for obj in self.obj.contents if utils.inherits_from(obj, LightSource)] if lightsources: lightsource = lightsources[0] else: # create the light source from scratch. lightsource = create.create_object(LightSource, key="torch") lightsource.location = caller string = "Your fingers bump against a piece of wood in a corner. Smelling it you sense the faint smell of tar. A {c%s{n!" string += "\nYou pick it up, holding it firmly. Now you just need to {wlight{n it using the flint and steel you carry with you." caller.msg(string % lightsource.key) class CmdDarkHelp(Command): """ Help command for the dark state. """ key = "help" locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "Implements the help command." string = "Can't help you until you find some light! Try feeling around for something to burn." string += " You cannot give up even if you don't find anything right away." self.caller.msg(string) # the nomatch system command will give a suitable error when we cannot find the normal commands. from src.commands.default.syscommands import CMD_NOMATCH class CmdDarkNoMatch(Command): "This is called when there is no match" key = CMD_NOMATCH locks = "cmd:all()" def func(self): "Implements the command." self.caller.msg("Until you find some light, there's not much you can do. Try feeling around.") class DarkCmdSet(CmdSet): "Groups the commands." key = "darkroom_cmdset" mergetype = "Replace" # completely remove all other commands def at_cmdset_creation(self): "populates the cmdset." self.add(CmdTutorial()) self.add(CmdLookDark()) self.add(CmdDarkHelp()) self.add(CmdDarkNoMatch()) # # Darkness room two-state system # class DarkState(Script): """ The darkness state is a script that keeps tabs on when a player in the room carries an active light source. It places a new, very restrictive cmdset (DarkCmdSet) on all the players in the room whenever there is no light in it. Upon turning on a light, the state switches off and moves to LightState. """ def at_script_creation(self): "This setups the script" self.key = "tutorial_darkness_state" self.desc = "A dark room" self.persistent = True def at_start(self): "called when the script is first starting up." for char in [char for char in self.obj.contents if char.has_player]: if char.is_superuser: char.msg("You are Superuser, so you are not affected by the dark state.") else: char.cmdset.add(DarkCmdSet) char.msg("The room is pitch dark! You are likely to be eaten by a Grue.") def is_valid(self): "is valid only as long as noone in the room has lit the lantern." return not self.obj.is_lit() def at_stop(self): "Someone turned on a light. This state dies. Switch to LightState." for char in [char for char in self.obj.contents if char.has_player]: char.cmdset.delete(DarkCmdSet) self.obj.db.is_dark = False self.obj.scripts.add(LightState) class LightState(Script): """ This is the counterpart to the Darkness state. It is active when the lantern is on. """ def at_script_creation(self): "Called when script is first created." self.key = "tutorial_light_state" self.desc = "A room lit up" self.persistent = True def is_valid(self): "This state is only valid as long as there is an active light source in the room." return self.obj.is_lit() def at_stop(self): "Light disappears. This state dies. Return to DarknessState." self.obj.db.is_dark = True self.obj.scripts.add(DarkState) class DarkRoom(TutorialRoom): """ A dark room. This tries to start the DarkState script on all objects entering. The script is responsible for making sure it is valid (that is, that there is no light source shining in the room). """ def is_lit(self): """ Helper method to check if the room is lit up. It checks all characters in room to see if they carry an active object of type LightSource. """ return any([any([True for obj in char.contents if utils.inherits_from(obj, LightSource) and obj.is_active]) for char in self.contents if char.has_player]) def at_object_creation(self): "Called when object is first created." super(DarkRoom, self).at_object_creation() self.db.tutorial_info = "This is a room with custom command sets on itself." # this variable is set by the scripts. It makes for an easy flag to look for # by other game elements (such as the crumbling wall in the tutorial) self.db.is_dark = True # the room starts dark. self.scripts.add(DarkState) def at_object_receive(self, character, source_location): "Called when an object enters the room. We crank the wheels to make sure scripts are synced." if character.has_player: if not self.is_lit() and not character.is_superuser: character.cmdset.add(DarkCmdSet) if character.db.health and character.db.health <= 0: # heal character coming here from being defeated by mob. health = character.db.health_max if not health: health = 20 character.db.health = health self.scripts.validate() def at_object_leave(self, character, target_location): "In case people leave with the light, we make sure to update the states accordingly." character.cmdset.delete(DarkCmdSet) # in case we are teleported away self.scripts.validate() #------------------------------------------------------------ # # Teleport room - puzzle room # # This is a sort of puzzle room that requires a certain # attribute on the entering character to be the same as # an attribute of the room. If not, the character will # be teleported away to a target location. This is used # by the Obelisk - grave chamber puzzle, where one must # have looked at the obelisk to get an attribute set on # oneself, and then pick the grave chamber with the # matching imagery for this attribute. # #------------------------------------------------------------ class TeleportRoom(TutorialRoom): """ Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to teleport_to - where to teleport to in case of failure to match """ def at_object_creation(self): "Called at first creation" super(TeleportRoom, self).at_object_creation() # what character.db.puzzle_clue must be set to, to avoid teleportation. self.db.puzzle_value = 1 # the target of the success teleportation. Can be a dbref or a unique room name. self.db.success_teleport_to = "treasure room" # the target of the failure teleportation. self.db.failure_teleport_to = "dark cell" def at_object_receive(self, character, source_location): "This hook is called by the engine whenever the player is moved into this room." if not character.has_player or character.is_superuser: # only act on player characters. return #print character.db.puzzle_clue, self.db.puzzle_value if character.db.puzzle_clue != self.db.puzzle_value: # we didn't pass the puzzle. See if we can teleport. teleport_to = self.db.failure_teleport_to # this is a room name else: # passed the puzzle teleport_to = self.db.success_teleport_to # this is a room name results = ObjectDB.objects.object_search(teleport_to, global_search=True) if not results or len(results) > 1: # we cannot move anywhere since no valid target was found. print "no valid teleport target for %s was found." % teleport_to return if character.player.is_superuser: # superusers don't get teleported character.msg("Superuser block: You would have been teleported to %s." % results[0]) return # teleport character.execute_cmd("look") character.location = results[0] # stealth move character.location.at_object_receive(character, self) #------------------------------------------------------------ # # Bridge - unique room # # Defines a special west-eastward "bridge"-room, a large room it takes # several steps to cross. It is complete with custom commands and a # chance of falling off the bridge. This room has no regular exits, # instead the exiting are handled by custom commands set on the player # upon first entering the room. # # Since one can enter the bridge room from both ends, it is # divided into five steps: # westroom <- 0 1 2 3 4 -> eastroom # #------------------------------------------------------------ class CmdEast(Command): """ Try to cross the bridge eastwards. """ key = "east" aliases = ["e"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "move forward" caller = self.caller bridge_step = min(5, caller.db.tutorial_bridge_position + 1) if bridge_step > 4: # we have reached the far east end of the bridge. Move to the east room. eexit = ObjectDB.objects.object_search(self.obj.db.east_exit) if eexit: caller.move_to(eexit[0]) else: caller.msg("No east exit was found for this room. Contact an admin.") return caller.db.tutorial_bridge_position = bridge_step caller.execute_cmd("look") # go back across the bridge class CmdWest(Command): """ Go back across the bridge westwards. """ key = "west" aliases = ["w"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "move forward" caller = self.caller bridge_step = max(-1, caller.db.tutorial_bridge_position - 1) if bridge_step < 0: # we have reached the far west end of the bridge. Move to the west room. wexit = ObjectDB.objects.object_search(self.obj.db.west_exit) if wexit: caller.move_to(wexit[0]) else: caller.msg("No west exit was found for this room. Contact an admin.") return caller.db.tutorial_bridge_position = bridge_step caller.execute_cmd("look") class CmdLookBridge(Command): """ looks around at the bridge. """ key = 'look' aliases = ["l"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "Looking around, including a chance to fall." bridge_position = self.caller.db.tutorial_bridge_position messages =("You are standing {wvery close to the the bridge's western foundation{n. If you go west you will be back on solid ground ...", "The bridge slopes precariously where it extends eastwards towards the lowest point - the center point of the hang bridge.", "You are {whalfways{n out on the unstable bridge.", "The bridge slopes precariously where it extends westwards towards the lowest point - the center point of the hang bridge.", "You are standing {wvery close to the bridge's eastern foundation{n. If you go east you will be back on solid ground ...") moods = ("The bridge sways in the wind.", "The hanging bridge creaks dangerously.", "You clasp the ropes firmly as the bridge sways and creaks under you.", "From the castle you hear a distant howling sound, like that of a large dog or other beast.", "The bridge creaks under your feet. Those planks does not seem very sturdy.", "Far below you the ocean roars and throws its waves against the cliff, as if trying its best to reach you.", "Parts of the bridge come loose behind you, falling into the chasm far below!", "A gust of wind causes the bridge to sway precariously.", "Under your feet a plank comes loose, tumbling down. For a moment you dangle over the abyss ...", "The section of rope you hold onto crumble in your hands, parts of it breaking apart. You sway trying to regain balance.") message = "{c%s{n\n" % self.obj.key + messages[bridge_position] + "\n" + moods[random.randint(0, len(moods) - 1)] self.caller.msg(message) # there is a chance that we fall if we are on the western or central part of the bridge. if bridge_position < 3 and random.random() < 0.05 and not self.caller.is_superuser: # we fall on 5% of the times. fexit = ObjectDB.objects.object_search(self.obj.db.fall_exit) if fexit: string = "\n Suddenly the plank you stand on gives way under your feet! You fall!" string += "\n You try to grab hold of an adjoining plank, but all you manage to do is to " string += "divert your fall westwards, towards the cliff face. This is going to hurt ... " string += "\n ... The world goes dark ...\n" # note that we move silently so as to not call look hooks (this is a little trick to leave # the player with the "world goes dark ..." message, giving them ample time to read it. They # have to manually call look to find out their new location). Thus we also call the # at_object_leave hook manually (otherwise this is done by move_to()). self.caller.msg("{r%s{n" % string) self.obj.at_object_leave(self.caller, fexit) self.caller.location = fexit[0] # stealth move, without any other hook calls. self.obj.msg_contents("A plank gives way under %s's feet and they fall from the bridge!" % self.caller.key) # custom help command class CmdBridgeHelp(Command): """ Overwritten help command """ key = "help" aliases = ["h"] locks = "cmd:all()" help_category = "Tutorial world" def func(self): "Implements the command." string = "You are trying hard not to fall off the bridge ..." string += "\n\nWhat you can do is trying to cross the bridge {weast{n " string += "or try to get back to the mainland {wwest{n)." self.caller.msg(string) class BridgeCmdSet(CmdSet): "This groups the bridge commands. We will store it on the room." key = "Bridge commands" priority = 1 # this gives it precedence over the normal look/help commands. def at_cmdset_creation(self): self.add(CmdTutorial()) self.add(CmdEast()) self.add(CmdWest()) self.add(CmdLookBridge()) self.add(CmdBridgeHelp()) class BridgeRoom(TutorialRoom): """ The bridge room implements an unsafe bridge. It also enters the player into a state where they get new commands so as to try to cross the bridge. We want this to result in the player getting a special set of commands related to crossing the bridge. The result is that it will take several steps to cross it, despite it being represented by only a single room. We divide the bridge into steps: self.db.west_exit - - | - - self.db.east_exit 0 1 2 3 4 The position is handled by a variabled stored on the player when entering and giving special move commands will increase/decrease the counter until the bridge is crossed. """ def at_object_creation(self): "Setups the room" super(BridgeRoom, self).at_object_creation() # at irregular intervals, this will call self.update_irregular() self.scripts.add(tut_scripts.IrregularEvent) # this identifies the exits from the room (should be the command # needed to leave through that exit). These are defaults, but you # could of course also change them after the room has been created. self.db.west_exit = "cliff" self.db.east_exit = "gate" self.db.fall_exit = "cliffledge" # add the cmdset on the room. self.cmdset.add_default(BridgeCmdSet) self.db.tutorial_info = \ """The bridge seem large but is actually only a single room that assigns custom west/east commands.""" def update_irregular(self): """ This is called at irregular intervals and makes the passage over the bridge a little more interesting. """ strings = ( "The rain intensifies, making the planks of the bridge even more slippery.", "A gush of wind throws the rain right in your face.", "The rainfall eases a bit and the sky momentarily brightens.", "The bridge shakes under the thunder of a closeby thunder strike.", "The rain pummels you with large, heavy drops. You hear the distinct howl of a large hound in the distance.", "The wind is picking up, howling around you and causing the bridge to sway from side to side.", "Some sort of large bird sweeps by overhead, giving off an eery screech. Soon it has disappeared in the gloom.", "The bridge sways from side to side in the wind.") self.msg_contents("{w%s{n" % strings[random.randint(0, 7)]) def at_object_receive(self, character, source_location): """ This hook is called by the engine whenever the player is moved into this room. """ if character.has_player: # we only run this if the entered object is indeed a player object. # check so our east/west exits are correctly defined. wexit = ObjectDB.objects.object_search(self.db.west_exit) eexit = ObjectDB.objects.object_search(self.db.east_exit) fexit = ObjectDB.objects.object_search(self.db.fall_exit) if not wexit or not eexit or not fexit: character.msg("The bridge's exits are not properly configured. Contact an admin. Forcing west-end placement.") character.db.tutorial_bridge_position = 0 return if source_location == eexit[0]: character.db.tutorial_bridge_position = 4 else: character.db.tutorial_bridge_position = 0 def at_object_leave(self, character, target_location): """ This is triggered when the player leaves the bridge room. """ if character.has_player: # clean up the position attribute del character.db.tutorial_bridge_position #----------------------------------------------------------- # # Intro Room - unique room # # This room marks the start of the tutorial. It sets up properties on the player char # that is needed for the tutorial. # #------------------------------------------------------------ class IntroRoom(TutorialRoom): """ Intro room properties to customize: char_health - integer > 0 (default 20) """ def at_object_receive(self, character, source_location): """ Assign properties on characters """ # setup health = self.db.char_health if not health: health = 20 if character.has_player: character.db.health = health character.db.health_max = health if character.is_superuser: string = "-"*78 string += "\nWARNING: YOU ARE PLAYING AS A SUPERUSER (%s). TO EXPLORE NORMALLY YOU NEED " % character.key string += "\nTO CREATE AND LOG IN AS A REGULAR USER INSTEAD. IF YOU CONTINUE, KNOW THAT " string += "\nMANY FUNCTIONS AND PUZZLES WILL IGNORE THE PRESENCE OF A SUPERUSER.\n" string += "-"*78 character.msg("{r%s{n" % string) #------------------------------------------------------------ # # Outro room - unique room # # Cleans up the character from all tutorial-related properties. # #------------------------------------------------------------ class OutroRoom(TutorialRoom): """ Outro room. """ def at_object_receive(self, character, source_location): """ Do cleanup. """ if character.has_player: del character.db.health del character.db.has_climbed del character.db.puzzle_clue del character.db.combat_parry_mode del character.db.tutorial_bridge_position for tut_obj in [obj for obj in character.contents if utils.inherits_from(obj, TutorialObject)]: tut_obj.reset()
Python
""" TutorialWorld - basic objects - Griatch 2011 This module holds all "dead" object definitions for the tutorial world. Object-commands and -cmdsets are also defined here, together with the object. Objects: TutorialObject Readable Obelisk LightSource CrumblingWall Weapon """ import time, random from src.utils import utils, create from game.gamesrc.objects.baseobjects import Object, Exit from game.gamesrc.commands.basecommand import Command from game.gamesrc.commands.basecmdset import CmdSet from game.gamesrc.scripts.basescript import Script #------------------------------------------------------------ # # TutorialObject # # The TutorialObject is the base class for all items # in the tutorial. They have an attribute "tutorial_info" # on them that a global tutorial command can use to extract # interesting behind-the scenes information about the object. # # TutorialObjects may also be "reset". What the reset means # is up to the object. It can be the resetting of the world # itself, or the removal of an inventory item from a # character's inventory when leaving the tutorial, for example. # #------------------------------------------------------------ class TutorialObject(Object): """ This is the baseclass for all objects in the tutorial. """ def at_object_creation(self): "Called when the object is first created." super(TutorialObject, self).at_object_creation() self.db.tutorial_info = "No tutorial info is available for this object." #self.db.last_reset = time.time() def reset(self): "Resets the object, whatever that may mean." self.location = self.home #------------------------------------------------------------ # # Readable - an object one can "read". # #------------------------------------------------------------ class CmdRead(Command): """ Usage: read [obj] Read some text. """ key = "read" locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "Implement the read command." if self.args: obj = self.caller.search(self.args.strip()) else: obj = self.obj if not obj: return # we want an attribute read_text to be defined. readtext = obj.db.readable_text if readtext: string = "You read {C%s{n:\n %s" % (obj.key, readtext) else: string = "There is nothing to read on %s." % obj.key self.caller.msg(string) class CmdSetReadable(CmdSet): "CmdSet for readables" def at_cmdset_creation(self): "called when object is created." self.add(CmdRead()) class Readable(TutorialObject): """ This object defines some attributes and defines a read method on itself. """ def at_object_creation(self): "Called when object is created" super(Readable, self).at_object_creation() self.db.tutorial_info = "This is an object with a 'read' command defined in a command set on itself." self.db.readable_text = "There is no text written on %s." % self.key # define a command on the object. self.cmdset.add_default(CmdSetReadable, permanent=True) #------------------------------------------------------------ # # Climbable object # # The climbable object works so that once climbed, it sets # a flag on the climber to show that it was climbed. A simple # command 'climb' handles the actual climbing. # #------------------------------------------------------------ class CmdClimb(Command): """ Usage: climb <object> """ key = "climb" locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "Implements function" if not self.args: self.caller.msg("What do you want to climb?") return obj = self.caller.search(self.args.strip()) if not obj: return if obj != self.obj: self.caller.msg("Try as you might, you cannot climb that.") return ostring = self.obj.db.climb_text if not ostring: ostring = "You climb %s. Having looked around, you climb down again." % self.obj.name self.caller.msg(ostring) self.caller.db.last_climbed = self.obj class CmdSetClimbable(CmdSet): "Climbing cmdset" def at_cmdset_creation(self): "populate set" self.add(CmdClimb()) class Climbable(TutorialObject): "A climbable object." def at_object_creation(self): "Called at initial creation only" self.cmdset.add_default(CmdSetClimbable, permanent=True) #------------------------------------------------------------ # # Obelisk - a unique item # # The Obelisk is an object with a modified return_appearance # method that causes it to look slightly different every # time one looks at it. Since what you actually see # is a part of a game puzzle, the act of looking also # stores a key attribute on the looking object for later # reference. # #------------------------------------------------------------ OBELISK_DESCS = ["You can briefly make out the image of {ba woman with a blue bird{n.", "You for a moment see the visage of {ba woman on a horse{n.", "For the briefest moment you make out an engraving of {ba regal woman wearing a crown{n.", "You think you can see the outline of {ba flaming shield{n in the stone.", "The surface for a moment seems to portray {ba woman fighting a beast{n."] class Obelisk(TutorialObject): """ This object changes its description randomly. """ def at_object_creation(self): "Called when object is created." super(Obelisk, self).at_object_creation() self.db.tutorial_info = "This object changes its desc randomly, and makes sure to remember which one you saw." # make sure this can never be picked up self.locks.add("get:false()") def return_appearance(self, caller): "Overload the default version of this hook." clueindex = random.randint(0, len(OBELISK_DESCS)-1) # set this description string = "The surface of the obelisk seem to waver, shift and writhe under your gaze, with " string += "different scenes and structures appearing whenever you look at it. " self.db.desc = string + OBELISK_DESCS[clueindex] # remember that this was the clue we got. caller.db.puzzle_clue = clueindex # call the parent function as normal (this will use db.desc we just set) return super(Obelisk, self).return_appearance(caller) #------------------------------------------------------------ # # LightSource # # This object that emits light and can be # turned on or off. It must be carried to use and has only # a limited burn-time. # When burned out, it will remove itself from the carrying # character's inventory. # #------------------------------------------------------------ class StateLightSourceOn(Script): """ This script controls how long the light source is burning. When it runs out of fuel, the lightsource goes out. """ def at_script_creation(self): "Called at creation of script." self.key = "lightsourceBurn" self.desc = "Keeps lightsources burning." self.start_delay = True # only fire after self.interval s. self.repeats = 1 # only run once. self.persistent = True # survive a server reboot. def at_start(self): "Called at script start - this can also happen if server is restarted." self.interval = self.obj.db.burntime self.db.script_started = time.time() def at_repeat(self): # this is only called when torch has burnt out self.obj.db.burntime = -1 self.obj.reset() def at_stop(self): """ Since the user may also turn off the light prematurely, this hook will store the current burntime. """ # calculate remaining burntime try: time_burnt = time.time() - self.db.script_started except TypeError: # can happen if script_started is not defined time_burnt = self.interval burntime = self.interval - time_burnt self.obj.db.burntime = burntime def is_valid(self): "This script is only valid as long as the lightsource burns." return self.obj.db.is_active class CmdLightSourceOn(Command): """ Switches on the lightsource. """ key = "on" aliases = ["switch on", "turn on", "light"] locks = "cmd:holds()" # only allow if command.obj is carried by caller. help_category = "TutorialWorld" def func(self): "Implements the command" if self.obj.db.is_active: self.caller.msg("%s is already burning." % self.obj.key) else: # set lightsource to active self.obj.db.is_active = True # activate the script to track burn-time. self.obj.scripts.add(StateLightSourceOn) self.caller.msg("{gYou light {C%s.{n" % self.obj.key) self.caller.location.msg_contents("%s lights %s!" % (self.caller, self.obj.key), exclude=[self.caller]) # we run script validation on the room to make light/dark states tick. self.caller.location.scripts.validate() # look around self.caller.execute_cmd("look") class CmdLightSourceOff(Command): """ Switch off the lightsource. """ key = "off" aliases = ["switch off", "turn off", "dowse"] locks = "cmd:holds()" # only allow if command.obj is carried by caller. help_category = "TutorialWorld" def func(self): "Implements the command " if not self.obj.db.is_active: self.caller.msg("%s is not burning." % self.obj.key) else: # set lightsource to inactive self.obj.db.is_active = False # validating the scripts will kill it now that is_active=False. self.obj.scripts.validate() self.caller.msg("{GYou dowse {C%s.{n" % self.obj.key) self.caller.location.msg_contents("%s dowses %s." % (self.caller, self.obj.key), exclude=[self.caller]) self.caller.location.scripts.validate() self.caller.execute_cmd("look") # we run script validation on the room to make light/dark states tick. class CmdSetLightSource(CmdSet): "CmdSet for the lightsource commands" key = "lightsource_cmdset" def at_cmdset_creation(self): "called at cmdset creation" self.add(CmdLightSourceOn()) self.add(CmdLightSourceOff()) class LightSource(TutorialObject): """ This implements a light source object. When burned out, lightsource will be moved to its home - which by default is the location it was first created at. """ def at_object_creation(self): "Called when object is first created." super(LightSource, self).at_object_creation() self.db.tutorial_info = "This object can be turned on off and has a timed script controlling it." self.db.is_active = False self.db.burntime = 60 # 1 minute self.db.desc = "A splinter of wood with remnants of resin on it, enough for burning." # add commands self.cmdset.add_default(CmdSetLightSource, permanent=True) def reset(self): """ Can be called by tutorial world runner, or by the script when the lightsource has burned out. """ if self.db.burntime <= 0: # light burned out. Since the lightsources's "location" should be # a character, notify them this way. try: loc = self.location.location except AttributeError: loc = self.location loc.msg_contents("{c%s{n {Rburns out.{n" % self.key) self.db.is_active = False try: # validate in holders current room, if possible self.location.location.scripts.validate() except AttributeError: # maybe it was dropped, try validating at current location. try: self.location.scripts.validate() except AttributeError,e: pass self.delete() #------------------------------------------------------------ # # Crumbling wall - unique exit # # This implements a simple puzzle exit that needs to be # accessed with commands before one can get to traverse it. # # The puzzle is currently simply to move roots (that have # presumably covered the wall) aside until a button for a # secret door is revealed. The original position of the # roots blocks the button, so they have to be moved to a certain # position - when they have, the "press button" command # is made available and the Exit is made traversable. # #------------------------------------------------------------ # There are four roots - two horizontal and two vertically # running roots. Each can have three positions: top/middle/bottom # and left/middle/right respectively. There can be any number of # roots hanging through the middle position, but only one each # along the sides. The goal is to make the center position clear. # (yes, it's really as simple as it sounds, just move the roots # to each side to "win". This is just a tutorial, remember?) class CmdShiftRoot(Command): """ Shifts roots around. shift blue root left/right shift red root left/right shift yellow root up/down shift green root up/down """ key = "shift" aliases = ["move"] # the locattr() lock looks for the attribute is_dark on the current room. locks = "cmd:not locattr(is_dark)" help_category = "TutorialWorld" def parse(self): "custom parser; split input by spaces" self.arglist = self.args.strip().split() def func(self): """ Implement the command. blue/red - vertical roots yellow/green - horizontal roots """ if not self.arglist: self.caller.msg("What do you want to move, and in what direction?") return if "root" in self.arglist: self.arglist.remove("root") # we accept arguments on the form <color> <direction> if not len(self.arglist) > 1: self.caller.msg("You must define which colour of root you want to move, and in which direction.") return color = self.arglist[0].lower() direction = self.arglist[1].lower() # get current root positions dict root_pos = self.obj.db.root_pos if not color in root_pos: self.caller.msg("No such root to move.") return # first, vertical roots (red/blue) - can be moved left/right if color == "red": if direction == "left": root_pos[color] = max(-1, root_pos[color] - 1) self.caller.msg("You shift the reddish root to the left.") if root_pos[color] != 0 and root_pos[color] == root_pos["blue"]: root_pos["blue"] += 1 self.caller.msg("The root with blue flowers gets in the way and is pushed to the right.") elif direction == "right": root_pos[color] = min(1, root_pos[color] + 1) self.caller.msg("You shove the reddish root to the right.") if root_pos[color] != 0 and root_pos[color] == root_pos["blue"]: root_pos["blue"] -= 1 self.caller.msg("The root with blue flowers gets in the way and is pushed to the left.") else: self.caller.msg("You cannot move the root in that direction.") elif color == "blue": if direction == "left": root_pos[color] = max(-1, root_pos[color] - 1) self.caller.msg("You shift the root with small blue flowers to the left.") if root_pos[color] != 0 and root_pos[color] == root_pos["red"]: root_pos["red"] += 1 self.caller.msg("The reddish root is to big to fit as well, so that one falls away to the left.") elif direction == "right": root_pos[color] = min(1, root_pos[color] + 1) self.caller.msg("You shove the root adorned with small blue flowers to the right.") if root_pos[color] != 0 and root_pos[color] == root_pos["red"]: root_pos["red"] -= 1 self.caller.msg("The thick reddish root gets in the way and is pushed back to the left.") else: self.caller.msg("You cannot move the root in that direction.") # now the horizontal roots (yellow/green). They can be moved up/down elif color == "yellow": if direction == "up": root_pos[color] = max(-1, root_pos[color] - 1) self.caller.msg("You shift the root with small yellow flowers upwards.") if root_pos[color] != 0 and root_pos[color] == root_pos["green"]: root_pos["green"] += 1 self.caller.msg("The green weedy root falls down.") elif direction == "down": root_pos[color] = min(1, root_pos[color] +1) self.caller.msg("You shove the root adorned with small yellow flowers downwards.") if root_pos[color] != 0 and root_pos[color] == root_pos["green"]: root_pos["green"] -= 1 self.caller.msg("The weedy green root is shifted upwards to make room.") else: self.caller.msg("You cannot move the root in that direction.") elif color == "green": if direction == "up": root_pos[color] = max(-1, root_pos[color] - 1) self.caller.msg("You shift the weedy green root upwards.") if root_pos[color] != 0 and root_pos[color] == root_pos["yellow"]: root_pos["yellow"] += 1 self.caller.msg("The root with yellow flowers falls down.") elif direction == "down": root_pos[color] = min(1, root_pos[color] + 1) self.caller.msg("You shove the weedy green root downwards.") if root_pos[color] != 0 and root_pos[color] == root_pos["yellow"]: root_pos["yellow"] -= 1 self.caller.msg("The root with yellow flowers gets in the way and is pushed upwards.") else: self.caller.msg("You cannot move the root in that direction.") # store new position self.obj.db.root_pos = root_pos # check victory condition if root_pos.values().count(0) == 0: # no roots in middle position self.caller.db.crumbling_wall_found_button = True self.caller.msg("Holding aside the root you think you notice something behind it ...") class CmdPressButton(Command): """ Presses a button. """ key = "press" aliases = ["press button", "button", "push", "push button"] locks = "cmd:attr(crumbling_wall_found_button) and not locattr(is_dark)" # only accessible if the button was found and there is light. help_category = "TutorialWorld" def func(self): "Implements the command" if self.caller.db.crumbling_wall_found_exit: # we already pushed the button self.caller.msg("The button folded away when the secret passage opened. You cannot push it again.") return # pushing the button string = "You move your fingers over the suspicious depression, then gives it a " string += "decisive push. First nothing happens, then there is a rumble and a hidden " string += "{wpassage{n opens, dust and pebbles rumbling as part of the wall moves aside." # we are done - this will make the exit traversable! self.caller.db.crumbling_wall_found_exit = True # this will make it into a proper exit eloc = self.caller.search(self.obj.db.destination, global_search=True) if not eloc: self.caller.msg("The exit leads nowhere, there's just more stone behind it ...") return self.obj.destination = eloc self.caller.msg(string) class CmdSetCrumblingWall(CmdSet): "Group the commands for crumblingWall" key = "crumblingwall_cmdset" def at_cmdset_creation(self): "called when object is first created." self.add(CmdShiftRoot()) self.add(CmdPressButton()) class CrumblingWall(TutorialObject, Exit): """ The CrumblingWall can be examined in various ways, but only if a lit light source is in the room. The traversal itself is blocked by a traverse: lock on the exit that only allows passage if a certain attribute is set on the trying player. Important attribute destination - this property must be set to make this a valid exit whenever the button is pushed (this hides it as an exit until it actually is) """ def at_object_creation(self): "called when the object is first created." super(CrumblingWall, self).at_object_creation() self.aliases = ["secret passage", "crack", "opening", "secret door"] # this is assigned first when pushing button, so assign this at creation time! self.db.destination = 2 # locks on the object directly transfer to the exit "command" self.locks.add("cmd:not locattr(is_dark)") self.db.tutorial_info = "This is an Exit with a conditional traverse-lock. Try to shift the roots around." # the lock is important for this exit; we only allow passage if we "found exit". self.locks.add("traverse:attr(crumbling_wall_found_exit)") # set cmdset self.cmdset.add(CmdSetCrumblingWall, permanent=True) # starting root positions. H1/H2 are the horizontally hanging roots, V1/V2 the # vertically hanging ones. Each can have three positions: (-1, 0, 1) where # 0 means the middle position. yellow/green are horizontal roots and red/blue vertical. # all may have value 0, but never any other identical value. self.db.root_pos = {"yellow":0, "green":0, "red":0, "blue":0} def _translate_position(self, root, ipos): "Translates the position into words" rootnames = {"red": "The {rreddish{n vertical-hanging root ", "blue": "The thick vertical root with {bblue{n flowers ", "yellow": "The thin horizontal-hanging root with {yyellow{n flowers ", "green": "The weedy {ggreen{n horizontal root "} vpos = {-1: "hangs far to the {wleft{n on the wall.", 0: "hangs straight down the {wmiddle{n of the wall.", 1: "hangs far to the {wright{n of the wall."} hpos = {-1: "covers the {wupper{n part of the wall.", 0: "passes right over the {wmiddle{n of the wall.", 1: "nearly touches the floor, near the {wbottom{n of the wall."} if root in ("yellow", "green"): string = rootnames[root] + hpos[ipos] else: string = rootnames[root] + vpos[ipos] return string def return_appearance(self, caller): "This is called when someone looks at the wall. We need to echo the current root positions." if caller.db.crumbling_wall_found_button: string = "Having moved all the roots aside, you find that the center of the wall, " string += "previously hidden by the vegetation, hid a curious square depression. It was maybe once " string += "concealed and made to look a part of the wall, but with the crumbling of stone around it," string += "it's now easily identifiable as some sort of button." else: string = "The wall is old and covered with roots that here and there have permeated the stone. " string += "The roots (or whatever they are - some of them are covered in small non-descript flowers) " string += "crisscross the wall, making it hard to clearly see its stony surface.\n" for key, pos in self.db.root_pos.items(): string += "\n" + self._translate_position(key, pos) self.db.desc = string # call the parent to continue execution (will use desc we just set) return super(CrumblingWall, self).return_appearance(caller) def at_after_traverse(self, traverser, source_location): "This is called after we traversed this exit. Cleans up and resets the puzzle." del traverser.db.crumbling_wall_found_button del traverser.db.crumbling_wall_found_exit self.reset() def at_failed_traverse(self, traverser): "This is called if the player fails to pass the Exit." traverser.msg("No matter how you try, you cannot force yourself through %s." % self.key) def reset(self): "Called by tutorial world runner, or whenever someone successfully traversed the Exit." self.location.msg_contents("The secret door closes abruptly, roots falling back into place.") for obj in self.location.contents: # clear eventual puzzle-solved attribues on everyone that didn't get out in time. They # have to try again. del obj.db.crumbling_wall_found_exit # Reset the roots with some random starting positions for the roots: start_pos = [{"yellow":1, "green":0, "red":0, "blue":0}, {"yellow":0, "green":0, "red":0, "blue":0}, {"yellow":0, "green":1, "red":-1, "blue":0}, {"yellow":1, "green":0, "red":0, "blue":0}, {"yellow":0, "green":0, "red":0, "blue":1}] self.db.root_pos = start_pos[random.randint(0, 4)] self.destination = None #------------------------------------------------------------ # # Weapon - object type # # A weapon is necessary in order to fight in the tutorial # world. A weapon (which here is assumed to be a bladed # melee weapon for close combat) has three commands, # stab, slash and defend. Weapons also have a property "magic" # to determine if they are usable against certain enemies. # # Since Characters don't have special skills in the tutorial, # we let the weapon itself determine how easy/hard it is # to hit with it, and how much damage it can do. # #------------------------------------------------------------ class CmdAttack(Command): """ Attack the enemy. Commands: stab <enemy> slash <enemy> parry stab - (thrust) makes a lot of damage but is harder to hit with. slash - is easier to land, but does not make as much damage. parry - forgoes your attack but will make you harder to hit on next enemy attack. """ # this is an example of implementing many commands as a single command class, # using the given command alias to separate between them. key = "attack" aliases = ["hit","kill", "fight", "thrust", "pierce", "stab", "slash", "chop", "parry", "defend"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "Implements the stab" cmdstring = self.cmdstring if cmdstring in ("attack", "fight"): string = "How do you want to fight? Choose one of 'stab', 'slash' or 'defend'." self.caller.msg(string) return # parry mode if cmdstring in ("parry", "defend"): string = "You raise your weapon in a defensive pose, ready to block the next enemy attack." self.caller.msg(string) self.caller.db.combat_parry_mode = True self.caller.location.msg_contents("%s takes a defensive stance" % self.caller, exclude=[self.caller]) return if not self.args: self.caller.msg("Who do you attack?") return target = self.caller.search(self.args.strip()) if not target: return string = "" tstring = "" ostring = "" if cmdstring in ("thrust", "pierce", "stab"): hit = float(self.obj.db.hit) * 0.7 # modified due to stab damage = self.obj.db.damage * 2 # modified due to stab string = "You stab with %s. " % self.obj.key tstring = "%s stabs at you with %s. " % (self.caller.key, self.obj.key) ostring = "%s stabs at %s with %s. " % (self.caller.key, target.key, self.obj.key) self.caller.db.combat_parry_mode = False elif cmdstring in ("slash", "chop"): hit = float(self.obj.db.hit) # un modified due to slash damage = self.obj.db.damage # un modified due to slash string = "You slash with %s. " % self.obj.key tstring = "%s slash at you with %s. " % (self.caller.key, self.obj.key) ostring = "%s slash at %s with %s. " % (self.caller.key, target.key, self.obj.key) self.caller.db.combat_parry_mode = False else: self.caller.msg("You fumble with your weapon, unable to choose an appropriate action...") self.caller.location.msg_contents("%s fumbles with their weapon." % self.obj.key) self.caller.db.combat_parry_mode = False return if target.db.combat_parry_mode: # target is defensive; even harder to hit! hit *= 0.5 if random.random() <= hit: self.caller.msg(string + "{gIt's a hit!{n") target.msg(tstring + "{rIt's a hit!{n") self.caller.location.msg_contents(ostring + "It's a hit!", exclude=[target,self.caller]) # call enemy hook if hasattr(target, "at_hit"): # should return True if target is defeated, False otherwise. return target.at_hit(self.obj, self.caller, damage) elif target.db.health: target.db.health -= damage else: # sorry, impossible to fight this enemy ... self.caller.msg("The enemy seems unaffacted.") return False else: self.caller.msg(string + "{rYou miss.{n") target.msg(tstring + "{gThey miss you.{n") self.caller.location.msg_contents(ostring + "They miss.", exclude=[target, self.caller]) class CmdSetWeapon(CmdSet): "Holds the attack command." def at_cmdset_creation(self): "called at first object creation." self.add(CmdAttack()) class Weapon(TutorialObject): """ This defines a bladed weapon. Important attributes (set at creation): hit - chance to hit (0-1) parry - chance to parry (0-1) damage - base damage given (modified by hit success and type of attack) (0-10) """ def at_object_creation(self): "Called at first creation of the object" super(Weapon, self).at_object_creation() self.db.hit = 0.4 # hit chance self.db.parry = 0.8 # parry chance self.damage = 8.0 self.magic = False self.cmdset.add_default(CmdSetWeapon, permanent=True) def reset(self): "When reset, the weapon is simply deleted, unless it has a place to return to." if self.location.has_player and self.home == self.location: self.location.msg_contents("%s suddenly and magically fades into nothingness, as if it was never there ..." % self.key) self.delete() else: self.location = self.home #------------------------------------------------------------ # # Weapon rack - spawns weapons # #------------------------------------------------------------ class CmdGetWeapon(Command): """ Usage: get weapon This will try to obtain a weapon from the container. """ key = "get" aliases = "get weapon" locks = "cmd:all()" help_cateogory = "TutorialWorld" def func(self): "Implement the command" rack_id = self.obj.db.rack_id if eval("self.caller.db.%s" % rack_id): # we don't allow to take more than one weapon from rack. self.caller.msg("%s has no more to offer." % self.obj.name) else: dmg, name, aliases, desc, magic = self.obj.randomize_type() new_weapon = create.create_object(Weapon, key=name, aliases=aliases,location=self.caller) new_weapon.db.rack_id = rack_id new_weapon.db.damage = dmg new_weapon.db.desc = desc new_weapon.db.magic = magic ostring = self.obj.db.get_text if not ostring: ostring = "You pick up %s." if '%s' in ostring: self.caller.msg(ostring % name) else: self.caller.msg(ostring) # tag the caller so they cannot keep taking objects from the rack. exec("self.caller.db.%s = True" % rack_id) class CmdSetWeaponRack(CmdSet): "group the rack cmd" key = "weaponrack_cmdset" mergemode = "Replace" def at_cmdset_creation(self): self.add(CmdGetWeapon()) class WeaponRack(TutorialObject): """ This will spawn a new weapon for the player unless the player already has one from this rack. attribute to set at creation: min_dmg - the minimum damage of objects from this rack max_dmg - the maximum damage of objects from this rack magic - if weapons should be magical (have the magic flag set) get_text - the echo text to return when getting the weapon. Give '%s' to include the name of the weapon. """ def at_object_creation(self): "called at creation" self.cmdset.add_default(CmdSetWeaponRack, permanent=True) self.rack_id = "weaponrack_1" self.db.min_dmg = 1.0 self.db.max_dmg = 4.0 self.db.magic = False def randomize_type(self): """ this returns a random weapon """ min_dmg = float(self.db.min_dmg) max_dmg = float(self.db.max_dmg) magic = bool(self.db.magic) dmg = min_dmg + random.random()*(max_dmg - min_dmg) aliases = [self.db.rack_id, "weapon"] if dmg < 1.5: name = "Knife" desc = "A rusty kitchen knife. Better than nothing." elif dmg < 2.0: name = "Rusty dagger" desc = "A double-edged dagger with nicked edge. It has a wooden handle." elif dmg < 3.0: name = "Sword" desc = "A rusty shortsword. It has leather wrapped around the handle." elif dmg < 4.0: name = "Club" desc = "A heavy wooden club with some rusty spikes in it." elif dmg < 5.0: name = "Ornate Longsword" aliases.extend(["longsword","ornate"]) desc = "A fine longsword." elif dmg < 6.0: name = "Runeaxe" aliases.extend(["rune","axe"]) desc = "A single-bladed axe, heavy but yet easy to use." elif dmg < 7.0: name = "Broadsword named Thruning" aliases.extend(["thruning","broadsword"]) desc = "This heavy bladed weapon is marked with the name 'Thruning'. It is very powerful in skilled hands." elif dmg < 8.0: name = "Silver Warhammer" aliases.append("warhammer") desc = "A heavy war hammer with silver ornaments. This huge weapon causes massive damage." elif dmg < 9.0: name = "Slayer Waraxe" aliases.extend(["waraxe","slayer"]) desc = "A huge double-bladed axe marked with the runes for 'Slayer'. It has more runic inscriptions on its head, which you cannot decipher." elif dmg < 10.0: name = "The Ghostblade" aliases.append("ghostblade") desc = "This massive sword is large as you are tall. Its metal shine with a bluish glow." else: name = "The Hawkblade" aliases.append("hawkblade") desc = "White surges of magical power runs up and down this runic blade. The hawks depicted on its hilt almost seems to have a life of their own." if dmg < 9 and magic: desc += "\nThe metal seems to glow faintly, as if imbued with more power than what is immediately apparent." return dmg, name, aliases, desc, magic
Python
""" This module implements a simple mobile object with a very rudimentary AI as well as an aggressive enemy object based on that mobile class. """ import random, time from django.conf import settings from src.objects.models import ObjectDB from src.utils import utils from game.gamesrc.scripts.basescript import Script from contrib.tutorial_world import objects as tut_objects from contrib.tutorial_world import scripts as tut_scripts BASE_CHARACTER_TYPECLASS = settings.BASE_CHARACTER_TYPECLASS #------------------------------------------------------------ # # Mob - mobile object # # This object utilizes exits and moves about randomly from # room to room. # #------------------------------------------------------------ class Mob(tut_objects.TutorialObject): """ This type of mobile will roam from exit to exit at random intervals. Simply lock exits against the is_mob attribute to block them from the mob (lockstring = "traverse:not attr(is_mob)"). """ def at_object_creation(self): "This is called when the object is first created." self.db.tutorial_info = "This is a moving object. It moves randomly from room to room." self.scripts.add(tut_scripts.IrregularEvent) # this is a good attribute for exits to look for, to block # a mob from entering certain exits. self.db.is_mob = True self.db.last_location = None # only when True will the mob move. self.db.roam_mode = True def announce_move_from(self, destination): "Called just before moving" self.location.msg_contents("With a cold breeze, %s drifts in the direction of %s." % (self.key, destination.key)) def announce_move_to(self, source_location): "Called just after arriving" self.location.msg_contents("With a wailing sound, %s appears from the %s." % (self.key, source_location.key)) def update_irregular(self): "Called at irregular intervals. Moves the mob." if self.roam_mode: exits = [ex for ex in self.location.exits if ex.access(self, "traverse")] if exits: # Try to make it so the mob doesn't backtrack. new_exits = [ex for ex in exits if ex.destination != self.db.last_location] if new_exits: exits = new_exits self.db.last_location = self.location # execute_cmd() allows the mob to respect exit and exit-command locks, # but may pose a problem if there is more than one exit with the same name. # - see Enemy example for another way to move self.execute_cmd("%s" % exits[random.randint(0, len(exits) - 1)].key) #------------------------------------------------------------ # # Enemy - mobile attacking object # # An enemy is a mobile that is aggressive against players # in its vicinity. An enemy will try to attack characters # in the same location. It will also pursue enemies through # exits if possible. # # An enemy needs to have a Weapon object in order to # attack. # # This particular tutorial enemy is a ghostly apparition that can only # be hurt by magical weapons. It will also not truly "die", but only # teleport to another room. Players defeated by the apparition will # conversely just be teleported to a holding room. # #------------------------------------------------------------ class AttackTimer(Script): """ This script is what makes an eneny "tick". """ def at_script_creation(self): "This sets up the script" self.key = "AttackTimer" self.desc = "Drives an Enemy's combat." self.interval = random.randint(2, 3) # how fast the Enemy acts self.start_delay = True # wait self.interval before first call self.persistent = True def at_repeat(self): "Called every self.interval seconds." if self.obj.db.inactive: return #print "attack timer: at_repeat", self.dbobj.id, self.ndb.twisted_task, id(self.ndb.twisted_task) if self.obj.db.roam_mode: self.obj.roam() #return elif self.obj.db.battle_mode: #print "attack" self.obj.attack() return elif self.obj.db.pursue_mode: #print "pursue" self.obj.pursue() #return else: #dead mode. Wait for respawn. dead_at = self.db.dead_at if not dead_at: self.db.dead_at = time.time() if (time.time() - self.db.dead_at) > self.db.dead_timer: self.obj.reset() class Enemy(Mob): """ This is a ghostly enemy with health (hit points). Their chance to hit, damage etc is determined by the weapon they are wielding, same as characters. An enemy can be in four modes: roam (inherited from Mob) - where it just moves around randomly battle - where it stands in one place and attacks players pursue - where it follows a player, trying to enter combat again dead - passive and invisible until it is respawned Upon creation, the following attributes describe the enemy's actions desc - description full_health - integer number > 0 defeat_location - unique name or #dbref to the location the player is taken when defeated. If not given, will remain in room. defeat_text - text to show player when they are defeated (just before being whisped away to defeat_location) defeat_text_room - text to show other players in room when a player is defeated win_text - text to show player when defeating the enemy win_text_room - text to show room when a player defeates the enemy respawn_text - text to echo to room when the mob is reset/respawn in that room. """ def at_object_creation(self): "Called at object creation." super(Enemy, self).at_object_creation() self.db.tutorial_info = "This moving object will attack players in the same room." # state machine modes self.db.roam_mode = True self.db.battle_mode = False self.db.pursue_mode = False self.db.dead_mode = False # health (change this at creation time) self.db.full_health = 20 self.db.health = 20 self.db.dead_at = time.time() self.db.dead_timer = 100 # how long to stay dead self.db.inactive = True # this is used during creation to make sure the mob doesn't move away # store the last player to hit self.db.last_attacker = None # where to take defeated enemies self.db.defeat_location = "darkcell" self.scripts.add(AttackTimer) def update_irregular(self): "the irregular event is inherited from Mob class" strings = self.db.irregular_echoes if strings: self.location.msg_contents(strings[random.randint(0, len(strings) - 1)]) def roam(self): "Called by Attack timer. Will move randomly as long as exits are open." # in this mode, the mob is healed. self.db.health = self.db.full_health players = [obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser] if players: # we found players in the room. Attack. self.db.roam_mode = False self.db.pursue_mode = False self.db.battle_mode = True elif random.random() < 0.2: # no players to attack, move about randomly. exits = [ex.destination for ex in self.location.exits if ex.access(self, "traverse")] if exits: # Try to make it so the mob doesn't backtrack. new_exits = [ex for ex in exits if ex.destination != self.db.last_location] if new_exits: exits = new_exits self.db.last_location = self.location # locks should be checked here self.move_to(exits[random.randint(0, len(exits) - 1)]) else: # no exits - a dead end room. Respawn back to start. self.move_to(self.home) def attack(self): """ This is the main mode of combat. It will try to hit players in the location. If players are defeated, it will whisp them off to the defeat location. """ last_attacker = self.db.last_attacker players = [obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser] if players: # find a target if last_attacker in players: # prefer to attack the player last attacking. target = last_attacker else: # otherwise attack a random player in location target = players[random.randint(0, len(players) - 1)] # try to use the weapon in hand attack_cmds = ("thrust", "pierce", "stab", "slash", "chop") cmd = attack_cmds[random.randint(0, len(attack_cmds) - 1)] self.execute_cmd("%s %s" % (cmd, target)) # analyze result. if target.db.health <= 0: # we reduced enemy to 0 health. Whisp them off to the prison room. tloc = ObjectDB.objects.object_search(self.db.defeat_location, global_search=True) tstring = self.db.defeat_text if not tstring: tstring = "You feel your conciousness slip away ... you fall to the ground as " tstring += "the misty apparition envelopes you ...\n The world goes black ...\n" target.msg(tstring) ostring = self.db.defeat_text_room if tloc: if not ostring: ostring = "\n%s envelops the fallen ... and then their body is suddenly gone!" % self.key # silently move the player to defeat location (we need to call hook manually) target.location = tloc[0] tloc[0].at_object_receive(target, self.location) elif not ostring: ostring = "%s falls to the ground!" % target.key self.location.msg_contents(ostring, exclude=[target]) else: # no players found, this could mean they have fled. Switch to pursue mode. self.battle_mode = False self.roam_mode = False self.pursue_mode = True def pursue(self): """ In pursue mode, the enemy tries to find players in adjoining rooms, preferably those that previously attacked it. """ last_attacker = self.db.last_attacker players = [obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser] if players: # we found players in the room. Maybe we caught up with some, or some walked in on us # before we had time to pursue them. Switch to battle mode. self.battle_mode = True self.roam_mode = False self.pursue_mode = False else: # find all possible destinations. destinations = [ex.destination for ex in self.location.exits if ex.access(self, "traverse")] # find all players in the possible destinations. OBS-we cannot just use the player's # current position to move the Enemy; this might have changed when the move is performed, # causing the enemy to teleport out of bounds. players = {} for dest in destinations: for obj in [o for o in dest.contents if utils.inherits_from(o, BASE_CHARACTER_TYPECLASS)]: players[obj] = dest if players: # we found targets. Move to intercept. if last_attacker in players: # preferably the one that last attacked us self.move_to(players[last_attacker]) else: # otherwise randomly. key = players.keys()[random.randint(0, len(players) - 1)] self.move_to(players[key]) else: # we found no players nearby. Return to roam mode. self.battle_mode = False self.roam_mode = True self.pursue_mode = False def at_hit(self, weapon, attacker, damage): """ Called when this object is hit by an enemy's weapon Should return True if enemy is defeated, False otherwise. In the case of players attacking, we handle all the events and information from here, so the return value is not used. """ self.db.last_attacker = attacker if not self.db.battle_mode: # we were attacked, so switch to battle mode. self.db.roam_mode = False self.db.pursue_mode = False self.db.battle_mode = True #self.scripts.add(AttackTimer) if not weapon.db.magic: # In the tutorial, the enemy is a ghostly apparition, so # only magical weapons can harm it. string = self.db.weapon_ineffective_text if not string: string = "Your weapon just passes through your enemy, causing no effect!" attacker.msg(string) return else: # an actual hit health = float(self.db.health) health -= damage self.db.health = health if health <= 0: string = self.db.win_text if not string: string = "After your last hit, %s folds in on itself, it seems to fade away into nothingness. " % self.key string += "In a moment there is nothing left but the echoes of its screams. But you have a " string += "feeling it is only temporarily weakened. " string += "You fear it's only a matter of time before it materializes somewhere again." attacker.msg(string) string = self.db.win_text_room if not string: string = "After %s's last hit, %s folds in on itself, it seems to fade away into nothingness. " % (attacker.name, self.key) string += "In a moment there is nothing left but the echoes of its screams. But you have a " string += "feeling it is only temporarily weakened. " string += "You fear it's only a matter of time before it materializes somewhere again." self.location.msg_contents(string, exclude=[attacker]) # put enemy in dead mode and hide it from view. IrregularEvent will bring it back later. self.db.roam_mode = False self.db.pursue_mode = False self.db.battle_mode = False self.db.dead_mode = True self.db.dead_at = time.time() self.location = None else: self.location.msg_contents("%s wails, shudders and writhes." % self.key) return False def reset(self): "If the mob was 'dead', respawn it to its home position and reset all modes and damage." if self.db.dead_mode: self.db.health = self.db.full_health self.db.roam_mode = True self.db.pursue_mode = False self.db.battle_mode = False self.db.dead_mode = False self.location = self.home string = self.db.respawn_text if not string: string = "%s fades into existence from out of thin air. It's looking pissed." % self.key self.location.msg_contents(string)
Python
""" This defines some generally useful scripts for the tutorial world. """ import random from game.gamesrc.scripts.basescript import Script #------------------------------------------------------------ # # IrregularEvent - script firing at random intervals # # This is a generally useful script for updating # objects at irregular intervals. This is used by as diverse # entities as Weather rooms and mobs. # # # #------------------------------------------------------------ class IrregularEvent(Script): """ This script, which should be tied to a particular object upon instantiation, calls update_irregular on the object at random intervals. """ def at_script_creation(self): "This setups the script" self.key = "update_irregular" self.desc = "Updates at irregular intervals" self.interval = random.randint(30, 70) # interval to call. self.start_delay = True # wait at least self.interval seconds before calling at_repeat the first time self.persistent = True # this attribute determines how likely it is the # 'update_irregular' method gets called on self.obj (value is # 0.0-1.0 with 1.0 meaning it being called every time.) self.db.random_chance = 0.2 def at_repeat(self): "This gets called every self.interval seconds." rand = random.random() if rand <= self.db.random_chance: try: #self.obj.msg_contents("irregular event for %s(#%i)" % (self.obj, self.obj.id)) self.obj.update_irregular() except Exception: pass class FastIrregularEvent(IrregularEvent): "A faster updating irregular event" def at_script_creation(self): super(FastIrregularEvent, self).at_script_creation() self.interval = 5 # every 5 seconds, 1/5 chance of firing #------------------------------------------------------------ # # Tutorial world Runner - root reset timer for TutorialWorld # # This is a runner that resets the world # #------------------------------------------------------------ # # # # This sets up a reset system -- it resets the entire tutorial_world domain # # and all objects inheriting from it back to an initial state, MORPG style. This is useful in order for # # different players to explore it without finding things missing. # # # # Note that this will of course allow a single player to end up with multiple versions of objects if # # they just wait around between resets; In a real game environment this would have to be resolved e.g. # # with custom versions of the 'get' command not accepting doublets. # # # # setting up an event for reseting the world. # UPDATE_INTERVAL = 60 * 10 # Measured in seconds # #This is a list of script parent objects that subscribe to the reset functionality. # RESET_SUBSCRIBERS = ["examples.tutorial_world.p_weapon_rack", # "examples.tutorial_world.p_mob"] # class EventResetTutorialWorld(Script): # """ # This calls the reset function on all subscribed objects # """ # def __init__(self): # super(EventResetTutorialWorld, self).__init__() # self.name = 'reset_tutorial_world' # #this you see when running @ps in game: # self.description = 'Reset the tutorial world .' # self.interval = UPDATE_INTERVAL # self.persistent = True # def event_function(self): # """ # This is called every self.interval seconds. # """ # #find all objects inheriting the subscribing parents # for parent in RESET_SUBSCRIBERS: # objects = Object.objects.global_object_script_parent_search(parent) # for obj in objects: # try: # obj.scriptlink.reset() # except: # logger.log_errmsg(traceback.print_exc())
Python
""" Evennia Talkative NPC Contribution - Griatch 2011 This is a simple NPC object capable of holding a simple menu-driven conversation. Create it by creating an object of typeclass contrib.talking_npc.TalkingNPC, For example using @create: @create John : contrib.talking_npc.TalkingNPC Walk up to it and give the talk command to strike up a conversation. If there are many talkative npcs in the same room you will get to choose which one's talk command to call (Evennia handles this automatically). Note that this is only a prototype class, showcasing the uses of the menusystem module. It is NOT a full mob implementation. """ from contrib import menusystem from game.gamesrc.objects.baseobjects import Object from game.gamesrc.commands.basecmdset import CmdSet from game.gamesrc.commands.basecommand import MuxCommand # # The talk command # class CmdTalk(MuxCommand): """ talks to an npc Usage: talk This command is only available if a talkative non-player-character (NPC) is actually present. It will strike up a conversation with that NPC and give you options on what to talk about. """ key = "talk" locks = "cmd:all()" help_category = "General" def func(self): "Implements the command." # self.obj is the NPC this is defined on obj = self.obj self.caller.msg("(You walk up and talk to %s.)" % self.obj.key) # conversation is a dictionary of keys, each pointing to a dictionary defining # the keyword arguments to the MenuNode constructor. conversation = obj.db.conversation if not conversation: self.caller.msg("%s says: 'Sorry, I don't have time to talk right now.'" % (self.obj.key)) return # build all nodes by loading them from the conversation tree. menu = menusystem.MenuTree(self.caller) for key, kwargs in conversation.items(): menu.add(menusystem.MenuNode(key, **kwargs)) menu.start() class TalkingCmdSet(CmdSet): "Stores the talk command." key = "talkingcmdset" def at_cmdset_creation(self): "populates the cmdset" self.add(CmdTalk()) # # Discussion tree. See contrib.menusystem.MenuNode for the keywords. # (This could be in a separate module too) # CONV = {"START":{"text": "Hello there, how can I help you?", "links":["info1", "info2"], "linktexts":["Hey, do you know what this 'Evennia' thing is all about?", "What's your name, little NPC?"], "keywords":None, "code":None}, "info1":{"text": "Oh, Evennia is where you are right now! Don't you feel the power?", "links":["info3", "info2", "END"], "linktexts":["Sure, *I* do, not sure how you do though. You are just an NPC.", "Sure I do. What's yer name, NPC?", "Ok, bye for now then."], "keywords":None, "code":None}, "info2":{"text":"My name is not really important ... I'm just an NPC after all.", "links":["info3", "info1"], "linktexts":["I didn't really want to know it anyhow.", "Okay then, so what's this 'Evennia' thing about?"], "keywords":None, "code":None}, "info3":{"text":"Well ... I'm sort of busy so, have to go. NPC business. Important stuff. You wouldn't understand.", "links":["END", "info2"], "linktexts":["Oookay ... I won't keep you. Bye.", "Wait, why don't you tell me your name first?"], "keywords":None, "code":None}, } class TalkingNPC(Object): """ This implements a simple Object using the talk command and using the conversation defined above. . """ def at_object_creation(self): "This is called when object is first created." # store the conversation. self.db.conversation = CONV self.db.desc = "This is a talkative NPC." # assign the talk command to npc self.cmdset.add_default(TalkingCmdSet, permanent=True)
Python
""" Menu-driven login system Contribution - Griatch 2011 This is an alternative login system for Evennia, using the contrib.menusystem module. As opposed to the default system it doesn't use emails for authentication and also don't auto-creates a Character with the same name as the Player (instead assuming some sort of character-creation to come next). Install is simple: To your settings file, add/edit the line: CMDSET_UNLOGGEDIN = "contrib.menu_login.UnloggedInCmdSet" That's it. The cmdset in this module will now be used instead of the default one. The initial login "graphic" is taken from strings in the module given by settings.CONNECTION_SCREEN_MODULE. You will want to edit the string in that module (at least comment out the default string that mentions commands that are not available) and add something more suitable for the initial splash screen. """ import re import traceback from django.conf import settings from src.players.models import PlayerDB from src.server.models import ServerConfig from src.comms.models import Channel from src.utils import create, logger, utils from src.commands.command import Command from src.commands.cmdset import CmdSet from src.commands.cmdhandler import CMD_LOGINSTART from contrib.menusystem import MenuNode, MenuTree, CMD_NOINPUT, CMD_NOMATCH CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE # Commands run on the unloggedin screen. Note that this is not using settings.UNLOGGEDIN_CMDSET but # the menu system, which is why some are named for the numbers in the menu. # # Also note that the menu system will automatically assign all # commands used in its structure a property "menutree" holding a reference # back to the menutree. This allows the commands to do direct manipulation # for example by triggering a conditional jump to another node. # # Menu entry 1a - Entering a Username class CmdBackToStart(Command): """ Step back to node0 """ key = CMD_NOINPUT locks = "cmd:all()" def func(self): "Execute the command" self.menutree.goto("START") class CmdUsernameSelect(Command): """ Handles the entering of a username and checks if it exists. """ key = CMD_NOMATCH locks = "cmd:all()" def func(self): "Execute the command" player = PlayerDB.objects.get_player_from_name(self.args) if not player: self.caller.msg("{rThis account name couldn't be found. Did you create it? If you did, make sure you spelled it right (case doesn't matter).{n") self.menutree.goto("node1a") else: self.menutree.player = player # store the player so next step can find it self.menutree.goto("node1b") # Menu entry 1b - Entering a Password class CmdPasswordSelectBack(Command): """ Steps back from the Password selection """ key = CMD_NOINPUT locks = "cmd:all()" def func(self): "Execute the command" self.menutree.goto("node1a") class CmdPasswordSelect(Command): """ Handles the entering of a password and logs into the game. """ key = CMD_NOMATCH locks = "cmd:all()" def func(self): "Execute the command" if not hasattr(self.menutree, "player"): self.caller.msg("{rSomething went wrong! The player was not remembered from last step!{n") self.menutree.goto("node1a") return player = self.menutree.player if not player.user.check_password(self.args): self.caller.msg("{rIncorrect password.{n") self.menutree.goto("node1b") return # before going on, check eventual bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0]==player.name for tup in bans) or any(tup[2].match(player.sessions[0].address[0]) for tup in bans if tup[2])): # this is a banned IP or name! string = "{rYou have been banned and cannot continue from here." string += "\nIf you feel this ban is in error, please email an admin.{x" self.caller.msg(string) self.caller.session_disconnect() return # we are ok, log us in. self.caller.msg("{gWelcome %s! Logging in ...{n" % player.key) self.caller.session_login(player) # abort menu, do cleanup. self.menutree.goto("END") # we are logged in. Look around. character = player.character if character: character.execute_cmd("look") else: # we have no character yet; use player's look, if it exists player.execute_cmd("look") # Menu entry 2a - Creating a Username class CmdUsernameCreate(Command): """ Handle the creation of a valid username """ key = CMD_NOMATCH locks = "cmd:all()" def func(self): "Execute the command" playername = self.args # sanity check on the name if not re.findall('^[\w. @+-]+$', playername) or not (3 <= len(playername) <= 30): self.caller.msg("\n\r {rAccount name should be between 3 and 30 characters. Letters, spaces, dig\ its and @/./+/-/_ only.{n") # this echoes the restrictions made by django's auth module. self.menutree.goto("node2a") return if PlayerDB.objects.get_player_from_name(playername): self.caller.msg("\n\r {rAccount name %s already exists.{n" % playername) self.menutree.goto("node2a") return # store the name for the next step self.menutree.playername = playername self.menutree.goto("node2b") # Menu entry 2b - Creating a Password class CmdPasswordCreateBack(Command): "Step back from the password creation" key = CMD_NOINPUT locks = "cmd:all()" def func(self): "Execute the command" self.menutree.goto("node2a") class CmdPasswordCreate(Command): "Handle the creation of a password. This also creates the actual Player/User object." key = CMD_NOMATCH locks = "cmd:all()" def func(self): "Execute the command" password = self.args if not hasattr(self.menutree, 'playername'): self.caller.msg("{rSomething went wrong! Playername not remembered from previous step!{n") self.menutree.goto("node2a") return playername = self.menutree.playername if len(password) < 3: # too short password string = "{rYour password must be at least 3 characters or longer." string += "\n\rFor best security, make it at least 8 characters long, " string += "avoid making it a real word and mix numbers into it.{n" self.caller.msg(string) self.menutree.goto("node2b") return # everything's ok. Create the new player account. Don't create a Character here. try: permissions = settings.PERMISSION_PLAYER_DEFAULT typeclass = settings.BASE_PLAYER_TYPECLASS new_player = create.create_player(playername, None, password, typeclass=typeclass, permissions=permissions, create_character=False) if not new_player: self.msg("There was an error creating the Player. This error was logged. Contact an admin.") self.menutree.goto("START") return utils.init_new_player(new_player) # join the new player to the public channel pchanneldef = settings.CHANNEL_PUBLIC if pchanneldef: pchannel = Channel.objects.get_channel(pchanneldef[0]) if not pchannel.connect_to(new_player): string = "New player '%s' could not connect to public channel!" % new_player.key logger.log_errmsg(string) # tell the caller everything went well. string = "{gA new account '%s' was created. Now go log in from the menu!{n" self.caller.msg(string % (playername)) self.menutree.goto("START") except Exception: # We are in the middle between logged in and -not, so we have to handle tracebacks # ourselves at this point. If we don't, we won't see any errors at all. string = "%s\nThis is a bug. Please e-mail an admin if the problem persists." self.caller.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc()) # Menu entry 3 - help screen LOGIN_SCREEN_HELP = \ """ Welcome to %s! To login you need to first create an account. This is easy and free to do: Choose option {w(1){n in the menu and enter an account name and password when prompted. Obs- the account name is {wnot{n the name of the Character you will play in the game! It's always a good idea (not only here, but everywhere on the net) to not use a regular word for your password. Make it longer than 3 characters (ideally 6 or more) and mix numbers and capitalization into it. The password also handles whitespace, so why not make it a small sentence - easy to remember, hard for a computer to crack. Once you have an account, use option {w(2){n to log in using the account name and password you specified. Use the {whelp{n command once you're logged in to get more aid. Hope you enjoy your stay! (return to go back)""" % settings.SERVERNAME # Menu entry 4 class CmdUnloggedinQuit(Command): """ We maintain a different version of the quit command here for unconnected players for the sake of simplicity. The logged in version is a bit more complicated. """ key = "4" aliases = ["quit", "qu", "q"] locks = "cmd:all()" def func(self): "Simply close the connection." self.menutree.goto("END") self.caller.msg("Good bye! Disconnecting ...") self.caller.session_disconnect() # The login menu tree, using the commands above START = MenuNode("START", text=utils.string_from_module(CONNECTION_SCREEN_MODULE), links=["node1a", "node2a", "node3", "END"], linktexts=["Log in with an existing account", "Create a new account", "Help", "Quit",], selectcmds=[None, None, None, CmdUnloggedinQuit]) node1a = MenuNode("node1a", text="Please enter your account name (empty to abort).", links=["START", "node1b"], helptext=["Enter the account name you previously registered with."], keywords=[CMD_NOINPUT, CMD_NOMATCH], selectcmds=[CmdBackToStart, CmdUsernameSelect], nodefaultcmds=True) # if we don't, default help/look will be triggered by names starting with l/h ... node1b = MenuNode("node1b", text="Please enter your password (empty to go back).", links=["node1a", "END"], keywords=[CMD_NOINPUT, CMD_NOMATCH], selectcmds=[CmdPasswordSelectBack, CmdPasswordSelect], nodefaultcmds=True) node2a = MenuNode("node2a", text="Please enter your desired account name (empty to abort).", links=["START", "node2b"], helptext="Account name can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.", keywords=[CMD_NOINPUT, CMD_NOMATCH], selectcmds=[CmdBackToStart, CmdUsernameCreate], nodefaultcmds=True) node2b = MenuNode("node2b", text="Please enter your password (empty to go back).", links=["node2a", "START"], helptext="Your password cannot contain any characters.", keywords=[CMD_NOINPUT, CMD_NOMATCH], selectcmds=[CmdPasswordCreateBack, CmdPasswordCreate], nodefaultcmds=True) node3 = MenuNode("node3", text=LOGIN_SCREEN_HELP, links=["START"], helptext="", keywords=[CMD_NOINPUT], selectcmds=[CmdBackToStart]) # access commands class UnloggedInCmdSet(CmdSet): "Cmdset for the unloggedin state" key = "UnloggedinState" priority = 0 def at_cmdset_creation(self): self.add(CmdUnloggedinLook()) class CmdUnloggedinLook(Command): """ An unloggedin version of the look command. This is called by the server when the player first connects. It sets up the menu before handing off to the menu's own look command.. """ key = CMD_LOGINSTART aliases = ["look", "l"] locks = "cmd:all()" def func(self): "Execute the menu" menu = MenuTree(self.caller, nodes=(START, node1a, node1b, node2a, node2b, node3), exec_end=None) menu.start()
Python
""" Evennia misc commands Contribution - Griatch 2011 This module offers some miscellaneous commands that may be useful depending on the game you run or the style of administration you prefer. Alternatively they can be looked at for inspiration. To make available in the game, import this module to game.gamesrc.commands.basecmdset.py (or your own equivalent) and add the command class(es) you want to the default command set. You need to reload the server to make them recognized. """ from django.conf import settings from src.commands.default.muxcommand import MuxCommand PERMISSION_HIERARCHY = settings.PERMISSION_HIERARCHY PERMISSION_HIERARCHY_LOWER = [perm.lower() for perm in PERMISSION_HIERARCHY] class CmdQuell(MuxCommand): """ Quelling permissions Usage: quell <command> [=permission level] This is an admin command that allows to execute another command as another (lower) permission level than what you currently have. This is useful for testing. Also superuser flag will be deactivated by this command. If no permission level is given, the command will be executed as the lowest level available in settings.PERMISSION_HIERARCHY. """ key = "quell" locks = "cmd:perm(all)" help_category = "General" def func(self): "Perform the command" if not self.args: self.caller.msg("Usage: quell <command> [=permission level]") return cmd = self.lhs perm = self.rhs if not PERMISSION_HIERARCHY: self.caller.msg("settings.PERMISSION_HIERARCHY is not defined. Add a hierarchy to use this command.") return if perm: if not perm.lower() in PERMISSION_HIERARCHY_LOWER: self.caller.msg("Unknown permission. Permission hierarchy is: [%s]" % ", ".join(PERMISSION_HIERARCHY)) return if not self.caller.locks.check_lockstring(self.caller, "dummy:perm(%s)" % perm): self.caller.msg("You cannot use a permission higher than the one you have.") return else: perm = PERMISSION_HIERARCHY_LOWER[0] # replace permission oldperm = self.caller.permissions old_superuser = self.caller.player.user.is_superuser newperm = [perm] + [perm for perm in oldperm if perm not in PERMISSION_HIERARCHY_LOWER] self.caller.permissions = newperm self.caller.player.user.is_superuser = False self.caller.player.user.save() try: ret = self.caller.execute_cmd(cmd) except Exception, e: self.caller.msg(str(e)) self.caller.permissions = oldperm self.caller.player.user.is_superuser = old_superuser self.caller.player.user.save() return ret
Python
""" Contribution - Griatch 2011 This is a simple character creation commandset. A suggestion is to test this together with menu_login, which doesn't create a Character on its own. This shows some more info and gives the Player the option to create a character without any more customizations than their name (further options are unique for each game anyway). Since this extends the OOC cmdset, logging in from the menu will automatically drop the Player into this cmdset unless they logged off while puppeting a Character already before. Installation: Import this module in game.gamesrc.basecmdset and add the following line to the end of OOCCmdSet's at_cmdset_creation(): self.add(chargen.OOCCmdSetCharGen) """ from django.conf import settings from src.commands.command import Command from src.commands.default.general import CmdLook from src.commands.default.cmdset_ooc import OOCCmdSet from src.objects.models import ObjectDB from src.utils import utils, create CHARACTER_TYPECLASS = settings.BASE_CHARACTER_TYPECLASS class CmdOOCLook(CmdLook): """ ooc look Usage: look look <character> This is an OOC version of the look command. Since a Player doesn't have an in-game existence, there is no concept of location or "self". If any characters are available for you to control, you may look at them with this command. """ key = "look" aliases = ["l", "ls"] locks = "cmd:all()" help_cateogory = "General" def func(self): """ Implements the ooc look command We use an attribute _character_dbrefs on the player in order to figure out which characters are "theirs". A drawback of this is that only the CmdCharacterCreate command adds this attribute, and thus e.g. player #1 will not be listed (although it will work). Existence in this list does not depend on puppeting rights though, that is checked by the @ic command directly. """ # making sure caller is really a player self.character = None if utils.inherits_from(self.caller, "src.objects.objects.Object"): # An object of some type is calling. Convert to player. #print self.caller, self.caller.__class__ self.character = self.caller if hasattr(self.caller, "player"): self.caller = self.caller.player if not self.character: # ooc mode, we are players avail_chars = self.caller.db._character_dbrefs if self.args: # Maybe the caller wants to look at a character if not avail_chars: self.caller.msg("You have no characters to look at. Why not create one?") return objs = ObjectDB.objects.get_objs_with_key_and_typeclass(self.args.strip(), CHARACTER_TYPECLASS) objs = [obj for obj in objs if obj.id in avail_chars] if not objs: self.caller.msg("You cannot see this Character.") return self.caller.msg(objs[0].return_appearance(self.caller)) return # not inspecting a character. Show the OOC info. charobjs = [] charnames = [] if self.caller.db._character_dbrefs: dbrefs = self.caller.db._character_dbrefs charobjs = [ObjectDB.objects.get_id(dbref) for dbref in dbrefs] charnames = [charobj.key for charobj in charobjs if charobj] if charnames: charlist = "The following Character(s) are available:\n\n" charlist += "\n\r".join(["{w %s{n" % charname for charname in charnames]) charlist += "\n\n Use {w@ic <character name>{n to switch to that Character." else: charlist = "You have no Characters." string = \ """ You, %s, are an {wOOC ghost{n without form. The world is hidden from you and besides chatting on channels your options are limited. You need to have a Character in order to interact with the world. %s Use {wcreate <name>{n to create a new character and {whelp{n for a list of available commands.""" % (self.caller.key, charlist) self.caller.msg(string) else: # not ooc mode - leave back to normal look self.caller = self.character # we have to put this back for normal look to work. super(CmdOOCLook, self).func() class CmdOOCCharacterCreate(Command): """ creates a character Usage: create <character name> This will create a new character, assuming the given character name does not already exist. """ key = "create" locks = "cmd:all()" def func(self): """ Tries to create the Character object. We also put an attribute on ourselves to remember it. """ # making sure caller is really a player self.character = None if utils.inherits_from(self.caller, "src.objects.objects.Object"): # An object of some type is calling. Convert to player. #print self.caller, self.caller.__class__ self.character = self.caller if hasattr(self.caller, "player"): self.caller = self.caller.player if not self.args: self.caller.msg("Usage: create <character name>") return charname = self.args.strip() old_char = ObjectDB.objects.get_objs_with_key_and_typeclass(charname, CHARACTER_TYPECLASS) if old_char: self.caller.msg("Character {c%s{n already exists." % charname) return # create the character new_character = create.create_object(CHARACTER_TYPECLASS, key=charname) if not new_character: self.caller.msg("{rThe Character couldn't be created. This is a bug. Please contact an admin.") return # make sure to lock the character to only be puppeted by this player new_character.locks.add("puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" % (new_character.id, self.caller.id)) # save dbref avail_chars = self.caller.db._character_dbrefs if avail_chars: avail_chars.append(new_character.id) else: avail_chars = [new_character.id] self.caller.db._character_dbrefs = avail_chars self.caller.msg("{gThe Character {c%s{g was successfully created!" % charname) class OOCCmdSetCharGen(OOCCmdSet): """ Extends the default OOC cmdset. """ def at_cmdset_creation(self): "Install everything from the default set, then overload" #super(OOCCmdSetCharGen, self).at_cmdset_creation() self.add(CmdOOCLook()) self.add(CmdOOCCharacterCreate())
Python
#! /usr/bin/python # # Auto-generate reST documentation for Sphinx from Evennia source # code. # # Uses etinenned's sphinx autopackage script. Install it to folder # "autogen" in this same directory: # # hg clone https://bitbucket.org/etienned/sphinx-autopackage-script autogen # # Create a directory tree "code/" containing one directory for every # package in the PACKAGE dictionary below. Make sure EVENNIA_DIR # points to an Evennia root dir. Then just run this script. A new # folder sphinx/source/code will be created with the reST sources. # # Note - this is not working very well at the moment, not all sources # seems to be properly detected and you get lots of errors when # compiling. To nevertheless make a link to the code from the doc # front page, edit docs/sphinx/sources/index.rst to reference # code/modules. # import os, subprocess, shutil EVENNIA_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) SPHINX_DIR = os.path.join(os.path.join(EVENNIA_DIR, "docs"), "sphinx") SPHINX_SRC_DIR = os.path.join(SPHINX_DIR, "source") SPHINX_CODE_DIR = os.path.join(SPHINX_SRC_DIR, "code") CONVERT_DIR = os.path.join(SPHINX_DIR, 'src2rest') AUTOGEN_EXE = os.path.join(CONVERT_DIR, os.path.join("autogen", "generate_modules.py")) def src2rest(): """ Run import """ try: shutil.rmtree(SPHINX_CODE_DIR) print "Emptied old %s." % SPHINX_CODE_DIR except OSError: pass os.mkdir(SPHINX_CODE_DIR) inpath = EVENNIA_DIR outpath = SPHINX_CODE_DIR excludes = [r".*/migrations/.*", r"evennia\.py$", r"manage\.py$", r"runner\.py$", r"server.py$", r"portal.py$"] subprocess.call(["python", AUTOGEN_EXE, "-n", "Evennia", "-d", outpath, "-s", "rst", "-f", inpath] + excludes) if __name__ == '__main__': try: src2rest() except Exception, e: print e print "Make sure to read the header of this file so that it's properly set up."
Python
#! /usr/bin/python # # Converts Evennia's google-style wiki pages to reST documents # # Setting up to run: # # 1) From this directory, use SVN to download wiki2html converter by Chris Roos. Make sure # to download into a directory "wiki2html" like this: # # svn co http://chrisroos.googlecode.com/svn/trunk/google-wiki-syntax wiki2html # # This is a Ruby program! Sorry, couldn't find a Python lib to do this. So if you # don't have Ruby, you need to install that too. # # You also need to patch a bug in above program to make multiline code snippets work. # From the same folder as the patch file, apply the patch like this: # # patch -p0 -i wiki2html.patch # # 2) Install pandoc (converts from html to reST): # # apt-get install pandoc (debian) # or download from # http://johnmacfarlane.net/pandoc/ # # 3) Retrieve wiki files (*.wiki) from Google code by mercurial. Make sure # to retrieve them into a directory wikiconvert/wiki: # # hg clone https://code.google.com/p/evennia.wiki wiki # # 4) Check so that you have the following file structure: # # wiki/ (containing google code wiki files) # wiki2html/ (containing the wiki_converter.rb ruby program (patch applied).) # html/ (empty) # rest/ (empty) # (this file) # # Usage: # # 1) Pull the wiki files into wiki/ so you have the latest. # 2) Run wiki2rest.py. Folders html and rest will end up containing the conversions and the contents # of rest/ will automatically be copied over to docs/sphinx/source/wiki. # import sys, os, subprocess, re, urllib # Setup EVENNIA_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) SPHINX_DIR = os.path.join(os.path.join(EVENNIA_DIR, "docs"), "sphinx") SPHINX_SRC_DIR = os.path.join(SPHINX_DIR, "source") SPHINX_WIKI_DIR = os.path.join(SPHINX_SRC_DIR, "wiki") CONVERT_DIR = os.path.join(SPHINX_DIR, "wiki2rest") WIKI_DIR = os.path.join(CONVERT_DIR, "wiki") HTML_DIR = os.path.join(CONVERT_DIR, "html") REST_DIR = os.path.join(CONVERT_DIR, "rest") WIKI2HTML_DIR = os.path.join(CONVERT_DIR, "wiki2html") PANDOC_EXE = "pandoc" RUBY_EXE = "ruby" WIKI_ROOT_URL = "http://code.google.com/p/evennia/wiki/" WIKI_CRUMB_URL = "/p/evennia/wiki/" # files to not convert (no file ending) NO_CONVERT = ["SideBar", "Screenshot"] #------------------------------------------------------------ # This is a version of the importer that imports Google html pages # directly instead of going through the ruby converter. Alas, while # being a lot cleaner in implementation, this seems to produce worse # results in the end (both visually and with broken-link issues), so # not using it at this time. # # See the wiki2html at the bottom for the ruby-version. #------------------------------------------------------------ def fetch_google_wiki_html_files(): """ Acquire wiki html pages from google code """ # use wiki repo to find html filenames html_urls = dict([(re.sub(r"\.wiki", "", fn), WIKI_ROOT_URL + re.sub(r"\.wiki", "?show=content", fn)) for fn in os.listdir(WIKI_DIR) if fn.endswith(".wiki")]) #html_urls = {"Index":html_urls["Index"]} #SR! html_pages = {} for name, html_url in html_urls.items(): print "urllib: fetching %s ..." % html_url f = urllib.urlopen(html_url) s = f.read() s = clean_html(s) html_pages[name] = s #clean_html(f.read()) f.close() # saving html file for debugging f = open(os.path.join(HTML_DIR, "%s.html" % name), 'w') f.write(s) f.close() return html_pages def clean_html(htmlstring): """ Clean up html properties special to google code and not known by pandoc """ # remove wikiheader tag (searches over many lines). Unfortunately python <2.7 don't support # DOTALL flag in re.sub ... matches = re.findall(r'<div id="wikiheader">.*?</div>.*?</div>.*?</div>', htmlstring, re.DOTALL) for match in matches: htmlstring = htmlstring.replace(match, "") #htmlstring = re.sub(r'<div id="wikiheader">.*?</div>.*?</div>.*?</div>', "", htmlstring, re.DOTALL) # remove prefix from urls htmlstring = re.sub('href="' + WIKI_CRUMB_URL, 'href="', htmlstring) # remove #links from headers htmlstring = re.sub(r'(<h[0-9]>.*?)(<a href="#.*?</a>)(.*?</h[0-9]>)', r"\1\3", htmlstring) return htmlstring def html2rest(name, htmlstring): """ Convert html data to reST with pandoc """ print "pandoc: Converting %s ..." % name p = subprocess.Popen([PANDOC_EXE, '--from=html', '--to=rst', '--reference-links'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) return p.communicate(htmlstring)[0] def wiki2rest_ver2(): """ Convert Google wiki pages to reST. """ # obtain all html data from google code html_pages = fetch_google_wiki_html_files() # convert to output files for name, htmldata in html_pages.items(): restfilename = os.path.join(REST_DIR, "%s.rst" % name) f = open(restfilename, 'w') f.write(html2rest(name, htmldata)) f.close() #------------------------------------------------------------ # This converter uses the 3rd party ruby script to convert wiki pages # to html, seems to produce a better final result than downloading html # directly from google code. #------------------------------------------------------------ def wiki2rest(): """ Convert from wikifile to rst file, going through html """ # convert from wikifile to html with wiki2html subprocess.call([RUBY_EXE, "wiki_convertor.rb", WIKI_DIR, HTML_DIR], cwd=WIKI2HTML_DIR) # convert from html to rest with pandoc htmlfilenames = [fn for fn in os.listdir(HTML_DIR) if fn.endswith(".html") and not re.sub(r".html", "", fn) in NO_CONVERT] for filename in htmlfilenames: htmlfilename = os.path.join(HTML_DIR, filename) # cleanup of code string = "".join(open(htmlfilename, 'r').readlines()) string = re.sub(r'<p class="summary">[A-Za-z0-9 .-\:]*</p>', "", string) string = re.sub(r"&lt;wiki:toc max_depth=&quot;[0-9]*&quot; /&gt;", "", string) string = re.sub(r"&lt;wiki:toc max_depth<h1>&quot;[0-9]*&quot; /&gt;</h1>", "", string) string = re.sub(r"<p>#settings Featured</p>", "", string) string = re.sub(r'<p class="labels">Featured</p>', "", string) string = re.sub(r'&lt;wiki:comment&gt;', "", string) string = re.sub(r'&lt;/wiki:comment&gt;', "", string) #string = re.sub(r'&lt;wiki:comment&gt;[<>;a-zA\/\n-&Z0-9 ]*&lt;/wiki:comment&gt;', "", string) f = open(htmlfilename, 'w') f.write(string) f.close() rstfilename = os.path.join(REST_DIR, re.sub(r".html$", ".rst", filename)) print "pandoc: converting %s -> %s" % (htmlfilename, rstfilename) subprocess.call([PANDOC_EXE, "--from=html", "--to=rst", "-o", rstfilename, htmlfilename]) # main program if __name__ == "__main__": try: wiki2rest() except Exception, e: print e print "Make sure to read this file's header to make sure everything is correctly set up. " sys.exit() import shutil try: shutil.rmtree(SPHINX_WIKI_DIR) print "Deleted old %s." % SPHINX_WIKI_DIR except OSError: pass print "Copying %s -> %s" % (REST_DIR, SPHINX_WIKI_DIR) shutil.copytree(REST_DIR, SPHINX_WIKI_DIR)
Python
""" This special Python config file sets the default encoding for the codebase to UTF-8 instead of ascii. This allows for just about any language to be used in-game. It is not advisable to change the value set below, as there will be a lot of encoding errors that result in server crashes. """ import sys sys.setdefaultencoding('utf-8')
Python
#!/usr/bin/python # Importer script to convert Fineco xls files into QIF files, # for use, among others, by gnucash. # # Antonino Sabetta - antonino.sabetta@isti.cnr.it # (C) - 2009 # # This is based on Jelmer Vernooij's script # for PostBank mijn.postbank.nl .csv files. # Jelmer Vernooij <jelmer@samba.org>, 2007 import csv, sys, os ## # # def usage(): print "Usage: ....." sys.exit(-1) ## # # def wrong_format(): print "Unrecognized format in input file." sys.exit(-1) ## # # def check_input_file(): line = rows.next() line = rows.next() line = rows.next() assert line == ['Risultato ricerca movimenti'] line = rows.next() assert line == ['DataOperazione','Data Valuta','Entrate','Uscite','Descrizione','Causale'] ## # begin main program # if len(sys.argv) < 2: usage try: #print "converting XLS to CSV" os.system("rm out.csv") os.system("xls2csv " + sys.argv[1] + "> out.csv") except: usage try: csvfile = open("out.csv") except IOError: print "Error reading CSV file" sys.exit(-1) rows = csv.reader(csvfile,delimiter=',') try: check_input_file except AssertionError: wrong_format print '!Type:Bank\n' for l in rows: if "/" not in l[0]: #print "skipping" continue else: p = l[0].split("/") print "D%s/%s/%s" % (p[0], p[1], p[2]) # you can easily get month-day-year here... # print 'D%s/%s/%s' % (l[0][4:6], l[0][6:8], l[0][0:4]) # date if l[2] == '': print 'T-%s' % l[3] # negative amount else: print 'T%s' % l[2] # positive amount print 'P%s' % l[4] # payee / description print 'M%s %s' % (l[5], l[4]) # comment print '^\n' # end transaction
Python
#!/usr/bin/python # Importer script to convert Fineco Credit Card xls files into QIF files, # for use, among others, by gnucash. # # Based on the fineo2qif.py script by # Antonino Sabetta - antonino.sabetta@isti.cnr.it # (C) - 2009 # # Modified by Marco Aicardi - marco [a] aicardi d0t org # # Released under GPLv3 License - www.gnu.org/licenses/g... # # This is based on Jelmer Vernooij's script # for PostBank mijn.postbank.nl .csv files. # Jelmer Vernooij <jelmer@samba.org>, 2007 import csv, sys, os ## # # def usage(): print "Usage: ....." sys.exit(-1) ## # # def wrong_format(): print "Unrecognized format in input file." sys.exit(-1) ## # # def check_input_file(): line = rows.next() line = rows.next() line = rows.next() assert line == ['Risultato ricerca movimenti'] line = rows.next() assert line == ['Data operazione','Data Registrazione','Descrizione Operazione','Tipo spesa','Tipo rimborso','Importo in euro'] ## # begin main program # if len(sys.argv) < 2: usage try: #print "converting XLS to CSV" os.system("rm out.csv") os.system("xls2csv " + sys.argv[1] + "> out.csv") except: usage try: csvfile = open("out.csv") except IOError: print "Error reading CSV file" sys.exit(-1) rows = csv.reader(csvfile,delimiter=',') try: check_input_file except AssertionError: wrong_format print '!Type:Bank\n' for l in rows: if "/" not in l[0]: #print "skipping" continue else: p = l[0].split("/") print "D%s/%s/%s" % (p[0], p[1], p[2]) # you can easily get month-day-year here... # print 'D%s/%s/%s' % (l[0][4:6], l[0][6:8], l[0][0:4]) # date print 'T-%s' % l[5] # negative amount print 'P%s' % l[2] # payee / description print 'M%s' % l[2] # comment print '^\n' # end transaction
Python
#!/usr/bin/python from datetime import datetime from itertools import combinations, dropwhile from math import ceil from os.path import join from random import seed, shuffle from sys import argv try: from pygame import init as pyGameInit from pygame import Surface from pygame import NOFRAME from pygame import BLEND_MIN, BLEND_ADD from pygame.display import set_mode from pygame.image import load, save, get_extended #from pygame.transform import flip from pygame.transform import smoothscale except ImportError, ex: raise ImportError("%s: %s\n\nPlease install PyGame v1.9.1 or later: http://pygame.org\n" % (ex.__class__.__name__, ex)) try: from pygame.font import SysFont except ImportError, ex: SysFont = None print "\nWARNING: pygame.font cannot be imported, text information will not be available" assert get_extended() PROGRAM_NAME = 'Fingerprints.py' EXTENSION = 'png' TITLE = "Fingerprints for Games Generator" USAGE_INFO = """Usage: python %s generate - Create initial sequence file. python %s <filename> <mask> - Create fingerprints sheet for the specified mask and save it to filename.%s. python %s <fileName> - Create fingeprints sheets for all masks in the specified sequence file.""" % (PROGRAM_NAME, PROGRAM_NAME, EXTENSION, PROGRAM_NAME) SEED = 518 N = 14 # Number of possible elements in a fingerprint K = 7 # Number of elements on a person's fingerprint NPLAYERS = 200 DPI = 300 DPC = DPI / 2.54 PAGE_WIDTH = int(29.7 * DPC) PAGE_HEIGHT = int(21 * DPC) FIELD = 3 NCOLUMNS = 8 NROWS = 4 SAMPLES = ((7, 4), (5, 2), (4, 7), (3, 10), (2, 7), (1, 2)) assert sum(nFingers for (nSamples, nFingers) in SAMPLES) == NCOLUMNS * NROWS BLANK_SAMPLES = ((N, NROWS * NCOLUMNS),) CELL_WIDTH = int((PAGE_WIDTH - FIELD) // NCOLUMNS) CELL_HEIGHT = int((PAGE_HEIGHT - FIELD) // NROWS) BACKGROUND_COLOR = (255, 255, 255) # white MASK_COLOR = (178, 178, 178) # gray FULL_COLOR = BACKGROUND_COLOR # white PART_COLOR = (0, 0, 0) # black FONT_NAMES = ('Verdana', 'Arial', None) TITLE_POSITION = (int(0.3 * DPC), int(0.25 * DPC)) FONT_SIZE = int(0.3 * DPC) BASE_CHAR = 'A' BACK_CHAR = '@' FULL_CHAR = '$' PART_CHAR = '&' MASK_CHAR = '#' LAYERS = ''.join(chr(ord(BASE_CHAR) + i) for i in xrange(N)) ALL_LAYERS = BACK_CHAR + FULL_CHAR + PART_CHAR + MASK_CHAR + LAYERS layers = {} font = None assert PAGE_WIDTH >= CELL_WIDTH assert PAGE_HEIGHT >= CELL_HEIGHT def createSequence(): masks = [''.join(c) for c in combinations(LAYERS, K)] length = len(masks) print '# %s' % TITLE print '# N=%d K=%d C=%d P=%d S=%d Created at %s' % (N, K, length, NPLAYERS, SEED, datetime.now().strftime('%Y-%m-%d %H:%M:%S')) print 'blank ' + LAYERS seed(SEED) shuffle(masks) for (name, mask) in zip(xrange(1, NPLAYERS + 1), masks): print '%%0%dd %%s' % len(str(NPLAYERS)) % (name, mask) def getFileName(n): return '%s.%s' % (n, EXTENSION) def initGraphics(): print '\n%s\n' % TITLE pyGameInit() set_mode((1, 1), NOFRAME) for n in ALL_LAYERS: layers[n] = smoothscale(load(join('Layers', getFileName(n))), (CELL_WIDTH, CELL_HEIGHT)) global font # pylint: disable=W0603 font = dropwhile(lambda font: not font, (SysFont(fontName, FONT_SIZE, bold = True) for fontName in FONT_NAMES)).next() if SysFont else None def createFinger(mask, name = ''): finger = Surface((CELL_WIDTH, CELL_HEIGHT)) # pylint: disable=E1121 finger.fill(BACKGROUND_COLOR) for m in mask + (MASK_CHAR if len(mask) > K else '') + BACK_CHAR + (MASK_CHAR if len(mask) > K else FULL_CHAR if len(mask) == K else PART_CHAR): finger.blit(layers[m], (0, 0), special_flags = BLEND_ADD if m == MASK_CHAR else BLEND_MIN) if font: finger.blit(font.render(name or u' \u0411', True, MASK_COLOR if len(mask) > K else FULL_COLOR if len(mask) == K else PART_COLOR), TITLE_POSITION) # using russian 'B' to indicate proper viewing position return finger def createSheet(name, mask): fileName = getFileName(name) print '%s -> %s' % (mask, fileName) fileName = join('Result', fileName) sheet = Surface((PAGE_WIDTH, PAGE_HEIGHT)) # pylint: disable=E1121 sheet.fill(BACKGROUND_COLOR) if name.isdigit(): fullFingers = [] partFingers = [] seed((int(name) + 1) * SEED) for (nSamples, nFingers) in SAMPLES: samples = [''.join(c) for c in combinations(mask, nSamples)] shuffle(samples) samples = (samples * int(ceil(float(nFingers) / len(samples))))[:nFingers] samples = (createFinger(sample, name if i == 0 and nSamples >= K else '') for (i, sample) in enumerate(samples)) (fullFingers if nSamples >= K else partFingers).extend(samples) shuffle(partFingers) fingers = fullFingers + partFingers else: fingers = (createFinger(mask),) * NROWS * NCOLUMNS assert len(fingers) <= NROWS * NCOLUMNS x = y = 0 for (i, finger) in enumerate(fingers, 1): sheet.blit(finger, (x, y)) if i % NROWS == 0: y = 0 x += CELL_WIDTH else: y += CELL_HEIGHT #if name.isdigit(): # sheet = flip(sheet, True, False) # for printing backwards on transparent film save(sheet, fileName) def createSheets(fileName): fileLines = (line.strip() for line in open(fileName)) lines = (line for line in fileLines if line and not line.startswith('#')) for (name, mask) in (line.split() for line in lines): createSheet(name, mask) def main(*args): if len(args) == 2: if args[1].lower() == 'generate': createSequence() else: initGraphics() createSheets(args[1]) elif len(args) == 3: initGraphics() createSheet(args[1], args[2]) else: print '\nERROR: Bad parameters\n\n%s\n' % USAGE_INFO if __name__ == '__main__': main(*argv)
Python
#!/usr/bin/python from datetime import datetime from itertools import combinations, dropwhile from math import ceil from os.path import join from random import seed, shuffle from sys import argv try: from pygame import init as pyGameInit from pygame import Surface from pygame import NOFRAME from pygame import BLEND_MIN, BLEND_ADD from pygame.display import set_mode from pygame.image import load, save, get_extended #from pygame.transform import flip from pygame.transform import smoothscale except ImportError, ex: raise ImportError("%s: %s\n\nPlease install PyGame v1.9.1 or later: http://pygame.org\n" % (ex.__class__.__name__, ex)) try: from pygame.font import SysFont except ImportError, ex: SysFont = None print "\nWARNING: pygame.font cannot be imported, text information will not be available" assert get_extended() PROGRAM_NAME = 'Fingerprints.py' EXTENSION = 'png' TITLE = "Fingerprints for Games Generator" USAGE_INFO = """Usage: python %s generate - Create initial sequence file. python %s <filename> <mask> - Create fingerprints sheet for the specified mask and save it to filename.%s. python %s <fileName> - Create fingeprints sheets for all masks in the specified sequence file.""" % (PROGRAM_NAME, PROGRAM_NAME, EXTENSION, PROGRAM_NAME) SEED = 518 N = 14 # Number of possible elements in a fingerprint K = 7 # Number of elements on a person's fingerprint NPLAYERS = 200 DPI = 300 DPC = DPI / 2.54 PAGE_WIDTH = int(29.7 * DPC) PAGE_HEIGHT = int(21 * DPC) FIELD = 3 NCOLUMNS = 8 NROWS = 4 SAMPLES = ((7, 4), (5, 2), (4, 7), (3, 10), (2, 7), (1, 2)) assert sum(nFingers for (nSamples, nFingers) in SAMPLES) == NCOLUMNS * NROWS BLANK_SAMPLES = ((N, NROWS * NCOLUMNS),) CELL_WIDTH = int((PAGE_WIDTH - FIELD) // NCOLUMNS) CELL_HEIGHT = int((PAGE_HEIGHT - FIELD) // NROWS) BACKGROUND_COLOR = (255, 255, 255) # white MASK_COLOR = (178, 178, 178) # gray FULL_COLOR = BACKGROUND_COLOR # white PART_COLOR = (0, 0, 0) # black FONT_NAMES = ('Verdana', 'Arial', None) TITLE_POSITION = (int(0.3 * DPC), int(0.25 * DPC)) FONT_SIZE = int(0.3 * DPC) BASE_CHAR = 'A' BACK_CHAR = '@' FULL_CHAR = '$' PART_CHAR = '&' MASK_CHAR = '#' LAYERS = ''.join(chr(ord(BASE_CHAR) + i) for i in xrange(N)) ALL_LAYERS = BACK_CHAR + FULL_CHAR + PART_CHAR + MASK_CHAR + LAYERS layers = {} font = None assert PAGE_WIDTH >= CELL_WIDTH assert PAGE_HEIGHT >= CELL_HEIGHT def createSequence(): masks = [''.join(c) for c in combinations(LAYERS, K)] length = len(masks) print '# %s' % TITLE print '# N=%d K=%d C=%d P=%d S=%d Created at %s' % (N, K, length, NPLAYERS, SEED, datetime.now().strftime('%Y-%m-%d %H:%M:%S')) print 'blank ' + LAYERS seed(SEED) shuffle(masks) for (name, mask) in zip(xrange(1, NPLAYERS + 1), masks): print '%%0%dd %%s' % len(str(NPLAYERS)) % (name, mask) def getFileName(n): return '%s.%s' % (n, EXTENSION) def initGraphics(): print '\n%s\n' % TITLE pyGameInit() set_mode((1, 1), NOFRAME) for n in ALL_LAYERS: layers[n] = smoothscale(load(join('Layers', getFileName(n))), (CELL_WIDTH, CELL_HEIGHT)) global font # pylint: disable=W0603 font = dropwhile(lambda font: not font, (SysFont(fontName, FONT_SIZE, bold = True) for fontName in FONT_NAMES)).next() if SysFont else None def createFinger(mask, name = ''): finger = Surface((CELL_WIDTH, CELL_HEIGHT)) # pylint: disable=E1121 finger.fill(BACKGROUND_COLOR) for m in mask + (MASK_CHAR if len(mask) > K else '') + BACK_CHAR + (MASK_CHAR if len(mask) > K else FULL_CHAR if len(mask) == K else PART_CHAR): finger.blit(layers[m], (0, 0), special_flags = BLEND_ADD if m == MASK_CHAR else BLEND_MIN) if font: finger.blit(font.render(name or u' \u0411', True, MASK_COLOR if len(mask) > K else FULL_COLOR if len(mask) == K else PART_COLOR), TITLE_POSITION) # using russian 'B' to indicate proper viewing position return finger def createSheet(name, mask): fileName = getFileName(name) print '%s -> %s' % (mask, fileName) fileName = join('Result', fileName) sheet = Surface((PAGE_WIDTH, PAGE_HEIGHT)) # pylint: disable=E1121 sheet.fill(BACKGROUND_COLOR) if name.isdigit(): fullFingers = [] partFingers = [] seed((int(name) + 1) * SEED) for (nSamples, nFingers) in SAMPLES: samples = [''.join(c) for c in combinations(mask, nSamples)] shuffle(samples) samples = (samples * int(ceil(float(nFingers) / len(samples))))[:nFingers] samples = (createFinger(sample, name if i == 0 and nSamples >= K else '') for (i, sample) in enumerate(samples)) (fullFingers if nSamples >= K else partFingers).extend(samples) shuffle(partFingers) fingers = fullFingers + partFingers else: fingers = (createFinger(mask),) * NROWS * NCOLUMNS assert len(fingers) <= NROWS * NCOLUMNS x = y = 0 for (i, finger) in enumerate(fingers, 1): sheet.blit(finger, (x, y)) if i % NROWS == 0: y = 0 x += CELL_WIDTH else: y += CELL_HEIGHT #if name.isdigit(): # sheet = flip(sheet, True, False) # for printing backwards on transparent film save(sheet, fileName) def createSheets(fileName): fileLines = (line.strip() for line in open(fileName)) lines = (line for line in fileLines if line and not line.startswith('#')) for (name, mask) in (line.split() for line in lines): createSheet(name, mask) def main(*args): if len(args) == 2: if args[1].lower() == 'generate': createSequence() else: initGraphics() createSheets(args[1]) elif len(args) == 3: initGraphics() createSheet(args[1], args[2]) else: print '\nERROR: Bad parameters\n\n%s\n' % USAGE_INFO if __name__ == '__main__': main(*argv)
Python
import sys sys.path.append(r'bin') import wx, os, pylab, numpy, Neuron, tuningFunctions, tools, simulateData class findV1(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(300,200), style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE) self.CreateStatusBar() # A StatusBar in the bottom of the window # Setting up the menu. filemenu= wx.Menu() p = wx.Panel(self) modelButton = wx.Button(p,wx.ID_ANY,"Test Model", pos = (20,20), size = (100,40)) fitButton = wx.Button(p,wx.ID_ANY,"Fit the Model", pos = (20,100), size = (100,40)) quitButton = wx.Button(p,wx.ID_ANY,"Quit", pos = (150,20), size = (100,40)) menuAbout = filemenu.Append(wx.ID_ANY, "&About"," Information about this program") menuExit = filemenu.Append(wx.ID_ANY,"E&xit"," Terminate the program") modelmenu = wx.Menu() runModel = modelmenu.Append(wx.ID_ANY, "&Run Model", "A version of the model to play around with") fitModel = modelmenu.Append(wx.ID_ANY, "&Fit Model", "Fit the model to data") # Creating the menubar. menuBar = wx.MenuBar() menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar menuBar.Append(modelmenu, "&Run Model") self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. # Set events. self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout) self.Bind(wx.EVT_MENU, self.OnExit, menuExit) self.Bind(wx.EVT_MENU, self.OnFit, fitModel) self.Bind(wx.EVT_MENU, self.OnRun, runModel) self.Bind(wx.EVT_BUTTON, self.OnFit, fitButton) self.Bind(wx.EVT_BUTTON, self.OnRun, modelButton) self.Bind(wx.EVT_BUTTON, self.OnExit, quitButton) self.Show(True) def OnGA(self,e): f = wx.Frame(self, size = (200,200)) p = self.gaPanel(f) f.Show() def OnAbout(self,e): dlg = wx.MessageDialog( self, "A small text editor", "About Sample Editor", wx.OK) dlg.ShowModal() # Show it dlg.Destroy() # finally destroy it when finished. def OnLoad(self,e): f = wx.Frame(self, size = (200,200)) p = self.expoPanel(f) f.Show() def OnFit(self,e): f = wx.Frame(self, size = (450,400)) p = self.fittingPanel(f) f.Show() def OnRun(self,e): f = wx.Frame(self, size = (450,500)) p = self.modelPanel(f) f.Show() def OnExit(self,e): self.Close(True) # Close the frame. class expoPanel(wx.Panel): def __init__(self, parent): self.expoFile = '' wx.Panel.__init__(self,parent) self.quote = wx.StaticText(self, label="Load a file :", pos=(20, 30)) self.radioList = ['m177/m177ab','m177/m177ac','m177/m177ad','m177/m177ae', 'm177/m177ag','m177/m177am','m177/m177b','m177/m177c', 'm177/m177d','m177/m177e','m177/m177f','m177/m177g', 'm177/m177j','m177/m177m','m177/m177n','m177/m177o', 'm177/m177p','m177/m177q','m177/m177r','m177/m177u', 'm177/m177w','m177/m177x','m177/m177z'] rb = wx.ComboBox(self, -1, pos=(20, 100), choices=self.radioList, style=wx.CB_DROPDOWN) self.Bind(wx.EVT_COMBOBOX, self.EvtComboBox, rb) loadButton = wx.Button(self,wx.ID_ANY,"Load File", pos = (20,130)) self.Bind(wx.EVT_BUTTON, self.EvtLoadButton, loadButton) def EvtComboBox(self, event): self.expoFile = self.radioList[event.GetSelection()] def EvtLoadButton(self, event): plotExpo.plotExpo(self.expoFile) class modelPanel(wx.Panel): def __init__(self, parent): self.params = numpy.array([0.0, 0.0, 100.0, 0.5, 1.1, 1.0, 5.0, 2.0, 0.004, 0.0053]) self.oricurve = False self.sfcurve = False self.sizecurve = False self.contcurve = False self.tfcurve = False wx.Panel.__init__(self,parent) loadButton = wx.Button(self,wx.ID_ANY,"Run Model", pos = (20,20)) self.Bind(wx.EVT_BUTTON, self.EvtLoadButton, loadButton) wx.StaticText(self,-1,pos=(20,90),label="Orientation:") ori = wx.TextCtrl(self, -1, pos = (300,90), value = str(self.params[0])) wx.StaticText(self,-1,pos=(20,120),label="Gain of the CRF:") crfG = wx.TextCtrl(self, -1, pos = (300,120), value = str(self.params[2])) wx.StaticText(self,-1,pos=(20,150),label="Size of the CRF:") crfW = wx.TextCtrl(self, -1, pos = (300,150), value = str(self.params[3])) wx.StaticText(self,-1,pos=(20,180),label="Gain of the Surround:") surrG = wx.TextCtrl(self, -1, pos = (300,180), value = str(self.params[5])) wx.StaticText(self,-1,pos=(20,210),label="Size of the Surround:") surrW = wx.TextCtrl(self, -1, pos = (300,210), value = str(self.params[6])) wx.StaticText(self,-1,pos=(20,240),label="Normalisation pool exponent:") NPE = wx.TextCtrl(self, -1, pos = (300,240), value = str(self.params[4])) wx.StaticText(self,-1,pos=(20,270),label="Spatial frequency:") sf = wx.TextCtrl(self, -1, pos = (300,270), value = str(self.params[7])) wx.StaticText(self,-1,pos=(20,300),label="First time constant of the temporal filter:") tau1 = wx.TextCtrl(self, -1, pos = (300,300), value = str(self.params[8])) wx.StaticText(self,-1,pos=(20,330),label="Second time constant of the temporal filter:") tau2 = wx.TextCtrl(self, -1, pos = (300,330), value = str(self.params[9])) crfButton = wx.Button(self,wx.ID_ANY,"View CRF", pos = (20,400)) self.Bind(wx.EVT_BUTTON, self.EvtCrfButton, crfButton) self.allBox = wx.CheckBox(self, -1 ,'Plot all', (150, 20)) self.oriBox = wx.CheckBox(self, -1 ,'Orientation tuning', (20, 40)) self.sfBox = wx.CheckBox(self, -1 ,'Sf tuning', (175, 40)) self.sizeBox = wx.CheckBox(self, -1 ,'Size tuning', (275, 40)) self.contBox = wx.CheckBox(self, -1 ,'Contrast tuning', (20, 60)) self.tfBox = wx.CheckBox(self, -1 ,'Tf tuning', (175, 60)) self.Bind(wx.EVT_TEXT, self.setOri, ori) self.Bind(wx.EVT_TEXT, self.setCrfG, crfG) self.Bind(wx.EVT_TEXT, self.setCrfW, crfW) self.Bind(wx.EVT_TEXT, self.setSurrG, surrG) self.Bind(wx.EVT_TEXT, self.setSurrW, surrW) self.Bind(wx.EVT_TEXT, self.setNPE, NPE) self.Bind(wx.EVT_TEXT, self.setSf, sf) self.Bind(wx.EVT_TEXT, self.setTau1, tau1) self.Bind(wx.EVT_TEXT, self.setTau2, tau2) self.Bind(wx.EVT_CHECKBOX, self.checkAll, self.allBox) self.Bind(wx.EVT_CHECKBOX, self.checkOri, self.oriBox) self.Bind(wx.EVT_CHECKBOX, self.checkSf, self.sfBox) self.Bind(wx.EVT_CHECKBOX, self.checkSize, self.sizeBox) self.Bind(wx.EVT_CHECKBOX, self.checkCont, self.contBox) self.Bind(wx.EVT_CHECKBOX, self.checkTf, self.tfBox) def EvtCrfButton(self, e): modelNeur = Neuron.V1neuron(sizeDeg=3, sizePix=128, crfWidth=self.params[3], ori = self.params[0], surroundWidth=self.params[6], surroundGain=self.params[5], normPoolExp=self.params[4], phase=self.params[1], sf = self.params[7], crfGain=self.params[2], tau1 = self.params[8], tau2 = self.params[9]) C = numpy.real(numpy.fft.ifft2(modelNeur.crfPrimaryFilter,axes=[1,2])) pylab.show() p = pylab.pcolor(numpy.linspace(-1.5,1.5,128),numpy.linspace(-1.5,1.5,128),C[0],vmin=C.min(),vmax=C.max()) for i in range(1,len(C)/2): p.set_array(C[i,0:-1,0:-1].ravel()) pylab.draw() def checkAll(self,e): if e.IsChecked(): self.oriBox.SetValue(state = True) self.sfBox.SetValue(state = True) self.sizeBox.SetValue(state = True) self.contBox.SetValue(state = True) self.tfBox.SetValue(state = True) self.oricurve = True self.sfcurve = True self.sizecurve = True self.contcurve = True self.tfcurve = True else: self.oriBox.SetValue(state = False) self.sfBox.SetValue(state = False) self.sizeBox.SetValue(state = False) self.contBox.SetValue(state = False) self.tfBox.SetValue(state = False) self.oricurve = False self.sfcurve = False self.sizecurve = False self.contcurve = False self.tfcurve = False def checkOri(self,e): self.oricurve = e.IsChecked() def checkSf(self,e): self.sfcurve = e.IsChecked() def checkSize(self,e): self.sizecurve = e.IsChecked() def checkCont(self,e): self.contcurve = e.IsChecked() def checkTf(self,e): self.tfcurve = e.IsChecked() def setOri(self,e): self.params[0] = float(e.GetString()) def setCrfG(self,e): self.params[2] = float(e.GetString()) def setCrfW(self,e): self.params[3] = float(e.GetString()) def setSurrG(self,e): self.params[5] = float(e.GetString()) def setSurrW(self,e): self.params[6] = float(e.GetString()) def setNPE(self,e): self.params[4] = float(e.GetString()) def setSf(self,e): self.params[7] = float(e.GetString()) def setTau1(self,e): self.params[8] = float(e.GetString()) def setTau2(self,e): self.params[9] = float(e.GetString()) def EvtComboBox(self, event): self.expoFile = self.radioList[event.GetSelection()] def EvtLoadButton(self, event): modelNeur = Neuron.V1neuron(sizeDeg=3, sizePix=128, crfWidth=self.params[3], ori = self.params[0], surroundWidth=self.params[6], surroundGain=self.params[5], normPoolExp=self.params[4], phase=self.params[1], sf = self.params[7], crfGain=self.params[2], tau1 = self.params[8], tau2 = self.params[9]) pylab.figure(1,figsize=(21,7)) if self.oricurve: modOris, P, F0ori, F1ori = tuningFunctions.oriTuning(modelNeur) pylab.subplot(1,5,1) pylab.plot(modOris, F1ori[0,:], 'k', lw = 2) pylab.title('Orientation') pylab.xticks([0, 90, 180, 270]) pylab.ylim(ymin=0) if self.sfcurve: modSFS, P, F0sf, F1sf = tuningFunctions.sfTuning(modelNeur) pylab.subplot(1,5,2) pylab.plot(modSFS, F1sf[0,:], 'k', lw = 2) pylab.title('Spatial frequency') pylab.ylim(ymin=0) if self.sizecurve: modSize, P, F0size, F1size = tuningFunctions.sizeTuning(modelNeur) pylab.subplot(1,5,3) pylab.plot(modSize, F1size[0,:], 'k', lw = 2) pylab.title('Size') pylab.ylim(ymin=0) if self.contcurve: modCont, P, F0cont, F1cont = tuningFunctions.contrastTuning(modelNeur) pylab.subplot(1,5,4) pylab.semilogx(modCont, F1cont[0,:], 'k', lw = 2) pylab.title('Contrast') pylab.ylim(ymin=0) pylab.xticks([0.01, 0.1, 1.0]) if self.tfcurve: modTf, P, F0Tf, F1Tf = tuningFunctions.tfTuning(modelNeur) pylab.subplot(1,5,5) pylab.plot(modTf, F1Tf[0,:], 'k', lw = 2) pylab.title('Temporal frequency') pylab.ylim(ymin=0) pylab.show() class gaPanel(expoPanel): def EvtLoadButton(self, event): SPEA_retrive.SPEA_retrive(self.expoFile) class fittingPanel(wx.Panel): def __init__(self, parent): self.params = numpy.array([0.0,0.0, 100.0, 0.5, 1.1, 1.0, 5.0, 1.0, 0.004, 0.0053]) self.simParams = numpy.array([1.05343039e+02, 9.76213328e+01, 1.14415904e+00, 1.17027548e+00, 3.46819754e+00, 2.95904032e-01, 1.99332238e+00, 3.13554779e-03, 8.91559749e-03]) self.setDefault() self.hints = 0 wx.Panel.__init__(self,parent) simButton = wx.Button(self,wx.ID_ANY,"Simulate data", pos = (20,20)) plotDataButton = wx.Button(self,wx.ID_ANY,"Plot simulated tuning", pos = (150,20)) plotFitButton = wx.Button(self,wx.ID_ANY,"Plot fit", pos = (330,20)) hintButton = wx.Button(self,wx.ID_ANY,"Show me a parameter", pos = (20,330)) answerButton = wx.Button(self,wx.ID_ANY,"Show me the answer", pos = (250,330)) self.Bind(wx.EVT_BUTTON, self.EvtSimButton, simButton) self.Bind(wx.EVT_BUTTON, self.EvtPlotSimButton, plotDataButton) self.Bind(wx.EVT_BUTTON, self.EvtPlotFitButton, plotFitButton) self.Bind(wx.EVT_BUTTON, self.EvtHintButton, hintButton) self.Bind(wx.EVT_BUTTON, self.EvtAnswerButton, answerButton) wx.StaticText(self,-1,pos=(20,60),label="Orientation:") ori = wx.TextCtrl(self, -1, pos = (300,60), value = str(self.params[0])) wx.StaticText(self,-1,pos=(20,90),label="Gain of the CRF:") crfG = wx.TextCtrl(self, -1, pos = (300,90), value = str(self.params[2])) wx.StaticText(self,-1,pos=(20,120),label="Size of the CRF:") crfW = wx.TextCtrl(self, -1, pos = (300,120), value = str(self.params[3])) wx.StaticText(self,-1,pos=(20,150),label="Gain of the Surround:") surrG = wx.TextCtrl(self, -1, pos = (300,150), value = str(self.params[5])) wx.StaticText(self,-1,pos=(20,180),label="Size of the Surround:") surrW = wx.TextCtrl(self, -1, pos = (300,180), value = str(self.params[6])) wx.StaticText(self,-1,pos=(20,210),label="Normalisation pool exponent:") NPE = wx.TextCtrl(self, -1, pos = (300,210), value = str(self.params[4])) wx.StaticText(self,-1,pos=(20,240),label="Spatial frequency:") sf = wx.TextCtrl(self, -1, pos = (300,240), value = str(self.params[7])) wx.StaticText(self,-1,pos=(20,270),label="First time constant of the temporal filter:") tau1 = wx.TextCtrl(self, -1, pos = (300,270), value = str(self.params[8])) wx.StaticText(self,-1,pos=(20,300),label="Second time constant of the temporal filter:") tau2 = wx.TextCtrl(self, -1, pos = (300,300), value = str(self.params[9])) self.Bind(wx.EVT_TEXT, self.setOri, ori) self.Bind(wx.EVT_TEXT, self.setCrfG, crfG) self.Bind(wx.EVT_TEXT, self.setCrfW, crfW) self.Bind(wx.EVT_TEXT, self.setSurrG, surrG) self.Bind(wx.EVT_TEXT, self.setSurrW, surrW) self.Bind(wx.EVT_TEXT, self.setNPE, NPE) self.Bind(wx.EVT_TEXT, self.setSf, sf) self.Bind(wx.EVT_TEXT, self.setTau1, tau1) self.Bind(wx.EVT_TEXT, self.setTau2, tau2) def setDefault(self): self.modOris = numpy.array([ 0.,40.,80.,120.,160.,200.,240.,280.,320.,360.]) self.F1ori = numpy.array([[1.02846992e-03,1.46457027e-03,1.21368653e+00,6.00252913e+00,7.12598679e-03,5.10922188e-04,1.92160428e-03,2.20473281e+00,2.16186657e-02,1.02846992e-03]]) self.modSFS = numpy.array([0.1, 0.64444444, 1.18888889, 1.73333333, 2.27777778, 2.82222222, 3.36666667, 3.91111111, 4.45555556,5.]) self.F1sf = numpy.array([[0.07829737, 0.60486854, 2.15158881, 3.53118444, 3.37018641, 2.14168597, 0.72962723, 0.06288583, 0.03441861, 0.08202204]]) self.modSize = numpy.array([0.1, 0.4625, 0.825, 1.1875, 1.55, 1.9125, 2.275, 2.6375, 3.]) self.F1size = numpy.array([[0.01642062, 0.66102566, 2.42317178, 5.62242689, 8.72942597, 11.00279346, 12.42118782, 12.90178358, 12.96191376]]) self.modCont = numpy.array([5.00000000e-04, 3.00000000e-02, 7.00000000e-02, 1.25000000e-01, 2.50000000e-01, 5.00000000e-01, 1.00000000e+00]) self.F1cont = numpy.array([[ 0.03698687, 1.06298268, 2.0464756, 3.12305085, 4.98359496, 7.62979167, 11.44100442]]) self.modTf = numpy.array([1.00000000e-02, 3.13375000e+00, 6.25750000e+00, 9.38125000e+00, 1.25050000e+01, 1.56287500e+01, 1.87525000e+01, 2.18762500e+01, 2.50000000e+01]) self.F1Tf = numpy.array([[0.24777051, 7.06629939, 9.41203233, 5.70825721, 3.65618796, 2.93503845, 2.61555329, 2.03054383, 1.15735793]]) #Parameter boxes def setOri(self,e): try: self.params[0] = float(e.GetString()) except: print "Could not read Orientation" def setCrfG(self,e): try: self.params[2] = float(e.GetString()) except: print "Could not read CrfG" def setCrfW(self,e): try: self.params[3] = float(e.GetString()) except: print "Could not read CrfW" def setSurrG(self,e): try: self.params[5] = float(e.GetString()) except: print "Could not read SurrG" def setSurrW(self,e): try: self.params[6] = float(e.GetString()) except: print "Could not read SurrW" def setNPE(self,e): try: self.params[4] = float(e.GetString()) except: print "Could not read NPE" def setSf(self,e): try: self.params[7] = float(e.GetString()) except: print "Could not read spatial frequency" def setTau1(self,e): try: self.params[8] = float(e.GetString()) except: print "Could not read tau1" def setTau2(self,e): try: self.params[9] = float(e.GetString()) except: print "Could not read tau2" #Button actions def EvtSimButton(self, event): dat = simulateData.simulateData() self.simParams = dat.getParams() self.hints = 0 self.modOris, self.F1ori, self.modSFS, self.F1sf, self.modSize, self.F1size, self.modCont, self.F1cont, self.modTf, self.F1Tf = dat.getResponses() def EvtPlotSimButton(self, event): pylab.figure(1,figsize=(21,7)) pylab.subplot(1,5,1) pylab.plot(self.modOris, self.F1ori[0,:], 'k', lw = 2) pylab.title('Orientation') pylab.xticks([0, 90, 180, 270]) pylab.ylim(ymin=0) pylab.subplot(1,5,2) pylab.plot(self.modSFS, self.F1sf[0,:], 'k', lw = 2) pylab.title('Spatial frequency') pylab.ylim(ymin=0) pylab.subplot(1,5,3) pylab.plot(self.modSize, self.F1size[0,:], 'k', lw = 2) pylab.title('Size') pylab.ylim(ymin=0) pylab.subplot(1,5,4) pylab.semilogx(self.modCont, self.F1cont[0,:], 'k', lw = 2) pylab.title('Contrast') pylab.ylim(ymin=0) pylab.xticks([0.01, 0.1, 1.0]) pylab.subplot(1,5,5) pylab.plot(self.modTf, self.F1Tf[0,:], 'k', lw = 2) pylab.title('Temporal frequency') pylab.ylim(ymin=0) pylab.show() def EvtPlotFitButton(self, event): pylab.close() dialog = wx.ProgressDialog( 'Progress', 'Computing Responses', maximum = 7, style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME ) modelNeur = Neuron.V1neuron(sizeDeg=3, sizePix=128, crfWidth=self.params[3], ori = self.params[0], surroundWidth=self.params[6], surroundGain=self.params[5], normPoolExp=self.params[4], phase=self.params[1], sf = self.params[7], crfGain=self.params[2], tau1 = self.params[8], tau2 = self.params[9]) dialog.Update ( 1, 'Computing Orientation') guessOris, P, F0ori, guessF1ori = tuningFunctions.oriTuning(modelNeur) dialog.Update ( 2, 'Computing Spatial Frequency') guessSFS, P, F0sf, guessF1sf = tuningFunctions.sfTuning(modelNeur) dialog.Update ( 3, 'Computing Size tuning') guessSize, P, F0size, guessF1size = tuningFunctions.sizeTuning(modelNeur) dialog.Update ( 4, 'Computing Contrast tuning') guessCont, P, F0cont, guessF1cont = tuningFunctions.contrastTuning(modelNeur) dialog.Update ( 5, 'Computing Temporal Frequency') guessTf, P, F0Tf, guessF1Tf = tuningFunctions.tfTuning(modelNeur) dialog.Update ( 6, 'Plotting') pylab.figure(1,figsize=(21,7)) pylab.subplot(1,5,1) pylab.plot(self.modOris, self.F1ori[0,:], 'k', lw = 2) pylab.plot(guessOris, guessF1ori[0,:], 'k--', lw = 2) pylab.title('Orientation') pylab.xticks([0, 90, 180, 270]) pylab.ylim(ymin=0) pylab.subplot(1,5,2) pylab.plot(self.modSFS, self.F1sf[0,:], 'k', lw = 2) pylab.plot(guessSFS, guessF1sf[0,:], 'k--', lw = 2) pylab.title('Spatial frequency') pylab.ylim(ymin=0) pylab.subplot(1,5,3) pylab.plot(self.modSize, self.F1size[0,:], 'k', lw = 2) pylab.plot(guessSize, guessF1size[0,:], 'k--', lw = 2) pylab.title('Size') pylab.ylim(ymin=0) pylab.subplot(1,5,4) pylab.semilogx(self.modCont, self.F1cont[0,:], 'k', lw = 2) pylab.semilogx(guessCont, guessF1cont[0,:], 'k--', lw = 2) pylab.title('Contrast') pylab.ylim(ymin=0) pylab.xticks([0.01, 0.1, 1.0]) pylab.subplot(1,5,5) pylab.plot(self.modTf, self.F1Tf[0,:], 'k', lw = 2, label='Simulated Data') pylab.plot(guessTf, guessF1Tf[0,:], 'k--', lw = 2, label='Current guess') pylab.title('Temporal frequency') pylab.ylim(ymin=0) pylab.legend() dialog.Update ( 7, 'Done') dialog.Close(True) pylab.show() def EvtHintButton(self,event): if self.hints == 0: hint = " Second time constant has value %0.5f \n This is a hard parameter to guess based on the tuning curves \n \n It was probably a good idea to get this one." %self.simParams[8] self.hints += 1 elif self.hints == 1: hint = " First time constant has value %0.5f \n Strongly correlated with tau2 \n Also quite hard to guess." %self.simParams[7] self.hints += 1 elif self.hints == 2: hint = " Surround width has value %0.2f \n The width of the surround can be deducted from how \n quickly the size tuning curve falls off after the maximum. \n \n This parameter can be hard to guess due to the fact that many \n combinations of parameters can produce similar tunings" %self.simParams[5] self.hints += 1 elif self.hints == 3: hint = " The gain of the CRF is %0.2f \n \n Setting the gain to the correct value should help a lot \n in setting the remaining parameters" %self.simParams[1] self.hints += 1 elif self.hints == 4: hint = " The gain of the surround is %0.2f \n This parameter effects the general gain of all curves and especially \n how much the the size tuning curve decreases after its maximum" %self.simParams[4] self.hints += 1 elif self.hints == 5: hint = " The width of the CRF is %0.2f \n This parameter can be deduced from the max of the size tuning curve" %self.simParams[4] self.hints += 1 elif self.hints == 5: hint = " The Normalisation pool exponent is %0.2f \n The exponent determines the saturation of the contrast tuning curve" %self.simParams[3] self.hints += 1 elif self.hints == 6: hint = " Spatial frequency is %0.2f \n This value is close to the peak of the spatial frequency curve" %self.simParams[6] self.hints += 1 elif self.hints == 6: hint = " Orientation is %0.2f \n This is your last hint, now you should have a match" %self.simParams[0] self.hints += 1 else: hint = " You have seen all parameters. Still does not fit? \n Try looking at the full answer." f = wx.Frame(self, size = (500,200)) p = self.hintPanel(f, hint) f.Show() def EvtAnswerButton(self,event): f = wx.Frame(self, size = (550,450)) p = self.answerPanel(f,p=self.simParams) f.Show() class answerPanel(wx.Panel): def __init__(self, parent, p=[]): wx.Panel.__init__(self,parent) wx.StaticText(self,-1,pos=(20,60),label="Orientation:") o = '%.2f' %p[0] wx.StaticText(self, -1, pos = (350,60), label = o) wx.StaticText(self,-1,pos=(20,90),label="Gain of the CRF:") o = '%.2f' %p[1] wx.StaticText(self, -1, pos = (350,90), label = o) wx.StaticText(self,-1,pos=(20,120),label="Size of the CRF:") o = '%.2f' %p[2] wx.StaticText(self, -1, pos = (350,120), label = o) wx.StaticText(self,-1,pos=(20,150),label="Gain of the Surround:") o = '%.2f' %p[4] wx.StaticText(self, -1, pos = (350,150), label = o) wx.StaticText(self,-1,pos=(20,180),label="Size of the Surround:") o = '%.2f' %p[5] wx.StaticText(self, -1, pos = (350,180), label = o) wx.StaticText(self,-1,pos=(20,210),label="Normalisation pool exponent:") o = '%.2f' %p[3] wx.StaticText(self, -1, pos = (350,210), label = o) wx.StaticText(self,-1,pos=(20,240),label="Spatial frequency:") o = '%.2f' %p[6] wx.StaticText(self, -1, pos = (350,240), label = o) wx.StaticText(self,-1,pos=(20,270),label="First time constant of the temporal filter:") o = '%.5f' %p[7] wx.StaticText(self, -1, pos = (350,270), label = o) wx.StaticText(self,-1,pos=(20,300),label="Second time constant of the temporal filter:") o = '%.5f' %p[8] wx.StaticText(self, -1, pos = (350,300), label = o) wx.StaticText(self, -1, pos = (20,350), label = "Did you get close to the real parameters? \n Maybe you found a different solution that gave very similar tuning properties") class hintPanel(wx.Panel): def __init__(self, parent, hint = "Here is a hint"): wx.Panel.__init__(self,parent) self.parent = parent wx.StaticText(self,-1,pos=(10,10),label=hint) closeButton = wx.Button(self,1001,"Close", pos = (230,150)) self.Bind(wx.EVT_BUTTON, self.EvtCloseButton, closeButton, id=1001) self.Show(True) def EvtCloseButton(self, event): self.parent.Close(True) app = wx.PySimpleApp() frame = findV1(None,"Find V1") app.MainLoop()
Python
#!/usr/bin/env python2.6 # -*- coding: utf-8 -*- import sys from future_builtins import * import cgi import getpass import json import re import time import urllib import httplib2 if len(sys.argv) == 1: username = raw_input('Username: ') password = getpass.getpass() elif len(sys.argv) == 2: username = sys.argv[1] password = getpass.getpass() elif len(sys.argv) == 3: username = sys.argv[1] password = sys.argv[2] else: print >> sys.stderr, 'Usage: findmyiphone.py [username] [password]' sys.exit(1) http = httplib2.Http() response, content = http.request('https://auth.me.com/authenticate', 'POST', body=urllib.urlencode({'service': 'account', 'ssoNamespace': 'primary-me', 'returnURL': 'https://secure.me.com/account/#findmyiphone'.encode('base64'), 'anchor': 'findmyiphone', 'formID': 'loginForm', 'username': username, 'password': password}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) if 'set-cookie' not in response: print >> sys.stderr, 'Incorrect member name or password.' sys.exit(1) cookie1 = response['set-cookie'] response, content = http.request('https://secure.me.com/wo/WebObjects/Account2.woa?lang=en&anchor=findmyiphone', 'GET', headers={'Cookie': cookie1, 'X-Mobileme-Version': '1.0'}) cookie2 = response['set-cookie'] lsc, = re.search('isc-secure\\.me\\.com=(.*?);', response['set-cookie']).groups() response, content = http.request('https://secure.me.com/wo/WebObjects/DeviceMgmt.woa', 'POST', headers={'Cookie': cookie1 + ', ' + cookie2, 'X-Mobileme-Version': '1.0', 'X-Mobileme-Isc': lsc}) if json.loads(content)['status'] == 0: print >> sys.stderr, 'Find My iPhone is unavailable.' sys.exit(1) id, os_version = re.search('new Device\\([0-9]+, \'(.*?)\', \'.*?\', \'.*?\', \'(.*?)\', \'(?:false|true)\', \'(?:false|true)\'\\)', content).groups() response, content = http.request('https://secure.me.com/wo/WebObjects/DeviceMgmt.woa/wa/LocateAction/locateStatus', 'POST', body='postBody=' + json.dumps({'deviceId': id, 'deviceOsVersion': os_version}), headers={'Cookie': cookie1 + ', ' + cookie2, 'X-Mobileme-Version': '1.0', 'X-Mobileme-Isc': lsc}) for key, value in sorted(json.loads(content).items()): print '{key:22} {value}'.format(key=key, value=value)
Python
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import webapp2 class MainHandler(webapp2.RequestHandler): def get(self): self.response.write('Hello world!') app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True)
Python