code
stringlengths
1
1.72M
language
stringclasses
1 value
# coding: utf-8 # imports import re # django imports from django import template from django.contrib.contenttypes.models import ContentType from django.contrib import admin from django.db import models from django.db.models import Q from django.contrib.auth.models import Group # grappelli imports from grappelli.models.help import HelpItem from grappelli.models.navigation import Navigation, NavigationItem from grappelli.settings import * register = template.Library() # GENERIC OBJECTS class do_get_generic_objects(template.Node): def __init__(self): pass def render(self, context): return_string = "var MODEL_URL_ARRAY = {" for c in ContentType.objects.all().order_by('id'): return_string = "%s%d: '%s/%s'," % (return_string, c.id, c.app_label, c.model) return_string = "%s}" % return_string[:-1] return return_string def get_generic_relation_list(parser, token): """ Returns a list of installed applications and models. Needed for lookup of generic relationships. """ tokens = token.contents.split() return do_get_generic_objects() register.tag('get_generic_relation_list', get_generic_relation_list) # CONTEXT-SENSITIVE HELP def get_help(path): """ Context Sensitive Help (currently not implemented). """ try: helpitem = HelpItem.objects.get(link=path) except HelpItem.DoesNotExist: helpitem = "" return { 'helpitem': helpitem } register.inclusion_tag('admin/includes_grappelli/help.html')(get_help) # NAVIGATION def get_navigation(user): """ User-related Navigation/Sidebar on the Admin Index Page. """ if user.is_superuser: object_list = NavigationItem.objects.all() else: object_list = NavigationItem.objects.filter(Q(groups__in=user.groups.all()) | Q(users=user)).distinct() return { 'object_list': object_list } register.inclusion_tag('admin/includes_grappelli/navigation.html')(get_navigation) # SEARCH FIELDS VERBOSE class GetSearchFields(template.Node): def __init__(self, opts, var_name): self.opts = template.Variable(opts) self.var_name = var_name def render(self, context): opts = str(self.opts.resolve(context)).split('.') model = models.get_model(opts[0], opts[1]) try: field_list = admin.site._registry[model].search_fields_verbose except: field_list = "" context[self.var_name] = ", ".join(field_list) return "" def do_get_search_fields_verbose(parser, token): """ Get search_fields_verbose in order to display on the Changelist. """ try: tag, arg = token.contents.split(None, 1) except: raise template.TemplateSyntaxError, "%s tag requires arguments" % token.contents.split()[0] m = re.search(r'(.*?) as (\w+)', arg) if not m: raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag opts, var_name = m.groups() return GetSearchFields(opts, var_name) register.tag('get_search_fields_verbose', do_get_search_fields_verbose) # ADMIN_TITLE def get_admin_title(): """ Returns the Title for the Admin-Interface. """ return ADMIN_TITLE register.simple_tag(get_admin_title) # ADMIN_URL def get_admin_url(): """ Returns the URL for the Admin-Interface. """ return ADMIN_URL register.simple_tag(get_admin_url) # GRAPPELLI MESSAGING SYSTEM def get_messages(session): """ Get Success and Error Messages. """ try: msg = session['grappelli']['message'] del session['grappelli']['message'] session.modified = True except: msg = "" return { 'message': msg } register.inclusion_tag('admin/includes_grappelli/messages.html')(get_messages)
Python
# coding: utf-8 from django.conf import settings # Admin Site Title ADMIN_HEADLINE = getattr(settings, "GRAPPELLI_ADMIN_HEADLINE", 'Fimu 2010') ADMIN_TITLE = getattr(settings, "GRAPPELLI_ADMIN_TITLE", 'Fimu 2010') # Link to your Main Admin Site (no slashes at start and end) ADMIN_URL = getattr(settings, "GRAPPELLI_ADMIN_URL", '/admin/')
Python
# coding: utf-8 from django.contrib import admin from django.utils.translation import ugettext as _ from django import forms from django.conf import settings from grappelli.models.navigation import Navigation, NavigationItem from grappelli.models.bookmarks import Bookmark, BookmarkItem from grappelli.models.help import Help, HelpItem class NavigationItemInline(admin.StackedInline): model = NavigationItem extra = 1 classes = ('collapse-open',) fieldsets = ( ('', { 'fields': ('title', 'link', 'category',) }), ('', { 'fields': ('groups', 'users',), }), ('', { 'fields': ('order',), }), ) filter_horizontal = ('users',) # Grappelli Options allow_add = True class NavigationOptions(admin.ModelAdmin): # List Options list_display = ('order', 'title',) list_display_links = ('title',) # Fieldsets fieldsets = ( ('', { 'fields': ('title', 'order',) }), ) # Misc save_as = True # Inlines inlines = [NavigationItemInline] # Grappelli Options order = 0 class BookmarkItemInline(admin.TabularInline): model = BookmarkItem extra = 1 classes = ('collapse-open',) fieldsets = ( ('', { 'fields': ('title', 'link', 'order',) }), ) # Grappelli Options allow_add = True class BookmarkOptions(admin.ModelAdmin): # List Options list_display = ('user',) list_display_links = ('user',) # Fieldsets fieldsets = ( ('', { 'fields': ('user',) }), ) # Misc save_as = True # Inlines inlines = [BookmarkItemInline] # Grappelli Options order = 1 def has_change_permission(self, request, obj=None): has_class_permission = super(BookmarkOptions, self).has_change_permission(request, obj) if not has_class_permission: return False if obj is not None and not request.user.is_superuser and request.user.id != obj.user.id: return False return True def save_model(self, request, obj, form, change): if not request.user.is_superuser: if not change: obj.user = request.user obj.save() def queryset(self, request): if request.user.is_superuser: return Bookmark.objects.all() return Bookmark.objects.filter(user=request.user) class HelpItemInline(admin.StackedInline): model = HelpItem extra = 1 classes = ('collapse-open',) fieldsets = ( ('', { 'fields': ('title', 'link', 'body', 'order',) }), ) # Grappelli Options allow_add = True class HelpOptions(admin.ModelAdmin): # List Options list_display = ('order', 'title',) list_display_links = ('title',) # Fieldsets fieldsets = ( ('', { 'fields': ('title', 'order',) }), ) # Misc save_as = True # Inlines inlines = [HelpItemInline] # Grappelli Options order = 2 # Media class Media: js = [ settings.ADMIN_MEDIA_PREFIX + 'tinymce/jscripts/tiny_mce/tiny_mce.js', settings.ADMIN_MEDIA_PREFIX + 'tinymce_setup/tinymce_setup.js', ] class HelpItemOptions(admin.ModelAdmin): # List Options list_display = ('order', 'title',) list_display_links = ('title',) # Fieldsets fieldsets = ( ('', { 'fields': ('help', 'title', 'link', 'body', 'order',) }), ) # Grappelli Options order = 3 # Media class Media: js = [ settings.ADMIN_MEDIA_PREFIX + 'tinymce/jscripts/tiny_mce/tiny_mce.js', settings.ADMIN_MEDIA_PREFIX + 'tinymce_setup/tinymce_setup.js', ] admin.site.register(Navigation, NavigationOptions) admin.site.register(Bookmark, BookmarkOptions) admin.site.register(Help, HelpOptions) admin.site.register(HelpItem, HelpItemOptions)
Python
# coding: utf-8 import re from django import http, template from django.contrib.admin import ModelAdmin from django.contrib.admin import actions from django.contrib.auth import authenticate, login from django.db.models.base import ModelBase from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django.shortcuts import render_to_response from django.utils.functional import update_wrapper from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext_lazy, ugettext as _ from django.views.decorators.cache import never_cache from django.conf import settings try: set except NameError: from sets import Set as set # Python 2.3 fallback from django.contrib.admin.sites import AdminSite class GrappelliSite(AdminSite): """ An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the root() method can then be used as a Django view function that presents a full admin interface for the collection of registered models. """ def __init__(self, name=None, app_name='admin'): self._registry = {} # model_class class -> admin_class instance self.root_path = None if name is None: self.name = 'admin' else: self.name = name self.app_name = app_name self._actions = {'delete_selected': actions.delete_selected} self._global_actions = self._actions.copy() self.groups = {} self.collections = {} self.group_template = "" self.collection_template = "" def index(self, request, extra_context=None): """ Displays the main admin index page, which lists all of the installed apps that have been registered in this site. """ app_dict = {} user = request.user for model, model_admin in self._registry.items(): app_label = model._meta.app_label has_module_perms = user.has_module_perms(app_label) if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): try: order = model_admin.order except: order = 0 model_dict = { 'order': order, 'name': capfirst(model._meta.verbose_name_plural), 'admin_url': mark_safe('%s/%s/' % (app_label, model.__name__.lower())), 'perms': perms, } if app_label in app_dict: app_dict[app_label]['models'].append(model_dict) else: app_dict[app_label] = { 'app_label': app_label, 'name': app_label.title(), 'app_url': app_label + '/', 'has_module_perms': has_module_perms, 'models': [model_dict], } # Sort the apps alphabetically. app_list = app_dict.values() app_list.sort(lambda x, y: cmp(x['name'], y['name'])) # First: Sort the models alphabetically within each app. # Second: Sort the models according to their order-attribute. for app in app_list: app['models'].sort(lambda x, y: cmp(x['name'], y['name'])) app['models'].sort(lambda x, y: cmp(x['order'], y['order'])) # set cookie if not request.session.get('grappelli'): request.session['grappelli'] = {} request.session['grappelli']['home'] = request.get_full_path() request.session.modified = True # Assign Apps to Groups group_list = {} custom_app_list = app_list for k,v in self.groups.items(): if request.GET.get("g") and k != int(request.GET.get("g")): continue if request.GET.get("c") and k not in self.collections[int(request.GET.get("c"))]['groups']: continue group_list[k] = v application_list = [] for app in v['apps']: try: application_list.append(app_dict[app]) # remove assigned app from custom app_list custom_app_list = [d for d in custom_app_list if d.get('app_label') != app] except: pass if len(application_list): group_list[k]['applications'] = application_list else: group_list[k]['applications'] = "" # Subsections for Groups and Collections # set template and title # clear app_list if request.GET.get("g"): try: title = group_list[int(request.GET.get("g"))]['title'] except: title = _('Site administration') try: group_template = group_list[int(request.GET.get("g"))]['template'] except: group_template = None tpl = group_template or self.group_template or "admin/index_group.html" custom_app_list = [] elif request.GET.get("c"): try: title = self.collections[int(request.GET.get("c"))]['title'] except: title = _('Site administration') try: collection_template = self.collections[int(request.GET.get("c"))]['template'] except: collection_template = None tpl = collection_template or self.collection_template or "admin/index_collection.html" custom_app_list = [] else: title = _('Site administration') tpl = self.index_template or "admin/index.html" # Reset grouplist if users has no permissions if not app_list: group_list = {} context = { 'title': title, 'app_list': custom_app_list, 'root_path': self.root_path, 'group_list': group_list } context.update(extra_context or {}) context_instance = template.RequestContext(request, current_app=self.name) return render_to_response(tpl, context, context_instance=context_instance ) index = never_cache(index) def app_index(self, request, app_label, extra_context=None): user = request.user has_module_perms = user.has_module_perms(app_label) app_dict = {} for model, model_admin in self._registry.items(): if app_label == model._meta.app_label: if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): try: order = model_admin.order except: order = 0 model_dict = { 'order': order, 'name': capfirst(model._meta.verbose_name_plural), 'admin_url': '%s/' % model.__name__.lower(), 'perms': perms, } if app_dict: app_dict['models'].append(model_dict), else: # First time around, now that we know there's # something to display, add in the necessary meta # information. app_dict = { 'name': app_label.title(), 'app_url': '', 'has_module_perms': has_module_perms, 'models': [model_dict], } if not app_dict: raise http.Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(lambda x, y: cmp(x['name'], y['name'])) app_dict['models'].sort(lambda x, y: cmp(x['order'], y['order'])) context = { 'title': _('%s administration') % capfirst(app_label), 'app_list': [app_dict], 'root_path': self.root_path, } context.update(extra_context or {}) context_instance = template.RequestContext(request, current_app=self.name) return render_to_response(self.app_index_template or ('admin/%s/app_index.html' % app_label, 'admin/app_index.html'), context, context_instance=context_instance )
Python
# -*- encoding: utf-8 -*- from django.conf import settings from django.utils.translation import ugettext_lazy as _ # Liste des applications pour le moteur de rubrique APPS = [('home', _('Page d\'accueil')), ('page', _('Page')), ('sitemap', _('Plan du site'))] for apps in settings.INSTALLED_APPS: app = apps.split('.') if app[0] == 'modulo' and app[1] not in ('page'): APPS.append((unicode(app[1]).lower(), unicode(app[1]).capitalize())) APPS.sort()
Python
# -*- encoding: utf-8 -*- from django.db import models from multilingual.translation import TranslationModel from django.utils.translation import ugettext_lazy as _ from modulo.page.models import Section class Gallery(models.Model): section = models.ForeignKey(Section, related_name="galleries", limit_choices_to = {'app': 'gallery'}, help_text=_(u"Selection de la rubrique contenant cette galerie.")) slug = models.CharField(_(u'Répertoire'), help_text=_(u'Répertoire contenant la galerie'), max_length=100) order = models.IntegerField(editable=False, default=0) def save(self): if self.order == 0: self.order = Gallery.objects.filter(section=self.section).count()+1 super(Gallery, self).save() def get_images(self): images = getattr(self, 'images', None) if images is None: from utils import get_images self.images = get_images(self.slug) return self.images def get_random_image(self): images = self.get_images() nb_images = len(images) if nb_images != 0: import random r = random.randint(0, nb_images-1) return images[r] else: return None def count(self): return len(self.get_images()) def get_absolute_url(self): return u'%s%d/' % (self.section.get_absolute_url(), self.id) def __unicode__(self): return u"%s : %s" % (self.slug, self.section) class Meta: verbose_name = _("galerie")
Python
# -*- encoding: utf-8 -*- from django.conf import settings from filebrowser import settings as fb_settings import re import os def get_images(path): # Precompile regular expressions filter_re = [] for exp in fb_settings.EXCLUDE: filter_re.append(re.compile(exp)) for k,v in fb_settings.VERSIONS.iteritems(): exp = (r'_%s.(%s)') % (k, '|'.join(fb_settings.EXTENSION_LIST)) filter_re.append(re.compile(exp)) # List images PATH = os.path.join('uploads', path) DIRECTORY = os.path.join(settings.MEDIA_ROOT, PATH) dir_list = [os.path.normcase(f) for f in os.listdir(DIRECTORY)] dir_list.sort() files = [] for file in dir_list: # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS filtered = file.startswith('.') for re_prefix in filter_re: if re_prefix.search(file): filtered = True if filtered: continue if os.path.splitext(file)[1] in ('.jpg', '.jpeg'): image = os.path.join(PATH, file) files.append(image) return files
Python
# -*- encoding: utf-8 -*- from models import Gallery from django.contrib import admin admin.site.register(Gallery)
Python
# -*- encoding: utf-8 -*- from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from django.contrib.auth.decorators import user_passes_test from django.views.decorators.cache import cache_page from models import Gallery @cache_page(60 * 15) def galleries(request): galleries = request.section.galleries.order_by('order') if len(galleries) == 1: request.object_id = galleries[0].id return gallery(request) else: return render_to_response('gallery/galleries.html', {'galleries': galleries,}, context_instance=RequestContext(request)) @cache_page(60 * 15) def gallery(request): gallery = get_object_or_404(Gallery, pk=request.object_id) return render_to_response('gallery/gallery.html', {'gallery': gallery,}, context_instance=RequestContext(request)) @user_passes_test(lambda u: u.is_superuser) def changeGalleryOrder(request): galleries = Gallery.objects.order_by('order') i = 1 for s in galleries: s.order = i s.save() i += 1 if request.method == "POST": if request.POST['galleries'] == 'order': for s in galleries: if s.order != request.POST[str(s.order)]: s.order = request.POST[str(s.order)] s.save() return HttpResponseRedirect(request.path) return render_to_response('admin/changeGallerieOrder.html', {'galleries': galleries}, context_instance=RequestContext(request))
Python
logger = None
Python
''' Created on 17-Mar-2011 @author: xie ''' ######################## matrix ################## import math import re import global_var class SparseVector: ''' A class that implement the sparse vector, in which the data is organized as a dic. And the dimension to be infinite. ''' vec = None def __init__(self, **keywords): # dic or list for key, value in keywords.iteritems(): if key == 'dic': self.vec = dict(value) return if key == 'list': dic = {} i = 0 for x in value: i = i + 1 dic[i] = x self.vec = dic return self.vec = {} def copy(self): return SparseVector(dic = self.vec) def set(self, index, value): if value == 0.0: if index in self.vec: del self.vec[index] return self.vec[index] = value def get(self, index): if index in self.vec: return self.vec[index] return 0.0 def inner_product(self, vector): s = 0.0 if self.non_zero_num() <= vector.non_zero_num(): for id, x in self.vec.iteritems(): s = s + x*vector.get(id) else: for id, x in vector.vec.iteritems(): s = s + x*self.get(id) return s def sum(self): s = 0 for v in self.vec.itervalues(): s = s + v return s def add(self, vector): ret = SparseVector() s = self.index_set() | vector.index_set() for index in s: t = self.get(index) + vector.get(index) ret.set(index, t) return ret def minus(self, vector): ret = SparseVector() s = self.index_set() | vector.index_set() for index in s: t = self.get(index) - vector.get(index) ret.set(index, t) return ret def scale(self, value): ret = SparseVector() for index, v in self.vec.iteritems(): ret.set(index, value*v) return ret def index_set(self): s = set() for index in self.vec.iterkeys(): s.add(index) return s def non_zero_num(self): return len(self.vec) def mod(self): s = 0.0 for x in self.vec.itervalues(): s = s + x*x return math.sqrt(s) def printInfo(self): if global_var.logger == None: print(self.vec) else: print >> global_var.logger, self.vec class SparseMatrix: ''' A class that implement the sparse matrix, in which the data is organized as a dic of SparseVector And the dimension to be infinite. ''' mat = None def __init__(self): self.mat = {} def clear(self): self.mat.clear() def copy(self): ret = SparseMatrix() for id, vec in self.mat.iteritems(): ret.setRow(id, vec) return ret def transpose(self): ret = SparseMatrix() for i, row in self.mat.iteritems(): for j, v in row.vec.iteritems(): ret.set(j,i,v) return ret def rowOne(self): ret = SparseMatrix() for i, row in self.mat.iteritems(): s = row.sum() if s != 0: ret.setRow(i, row.scale(1.0/s)) else: ret.setRow(i, row) return ret def modifySuperNode(self, p = 1 - 1e-5): # p: the possibility to transpose to itself sn = -1 for id, vec in self.mat.iteritems(): t = vec.get(id) if t != 0: # super node sn = id break vec = self.getRow(sn) s = vec.sum() - 1 if s == 0: return vec.set(sn, s*p/(1-p)) self.setRow(sn, vec) def loadFromMatFile(self, filename): self.mat.clear() f = file(filename, 'r') i = 0 for line in f: i = i + 1 res = line.split(' ') j = 0 for s in res: if s == '': continue j = j + 1 self.set(i,j,float(s)) f.close() def loadFromNwbFile(self, filename): self.mat.clear() f = file(filename, 'r') p = re.compile('[0-9]+ [0-9]+ [0-9]+') for line in f: m = p.match(line) if m != None: res = line.split(' ') i = int(res[0]) j = int(res[1]) cnt = int(res[2]) self.set(i, j, cnt) f.close() def set(self, i, j, value): row = None if i in self.mat: row = self.mat[i] else: row = SparseVector() self.mat[i] = row row.set(j, value) def setRow(self, i, row): vec = row.copy() self.mat[i] = vec def get(self, i, j): if i in self.mat: row = self.mat[i] return row.get(j) return 0.0 def getRow(self, i): vec = self.mat[i] return vec.copy() def map(self, vector): ret = SparseVector() for i, row in self.mat.iteritems(): s = row.inner_product(vector) ret.set(i, s) return ret def printInfo(self): for i, row in self.mat.iteritems(): if global_var.logger == None: print("row:" + str(i)) else: print >> global_var.logger, ("row:" + str(i)) row.printInfo() def prepareForRW(self): ret = self.copy() ret.modifySuperNode() ret = ret.rowOne() ret = ret.transpose() return ret def randomWalkPair(self, c, start_index, deta, file_name = None): vec = self.randomWalk(c, start_index, deta) vec_t = None for id in self.mat.iterkeys(): if id != start_index: vec_t = self.randomWalk(c, id, deta) else: vec_t = vec v = vec.get(id) v *= vec_t.get(start_index) vec.set(id, v) #vec.set(start_index, 0) list = sorted(vec.vec.items(), key = lambda d:d[1], reverse = True) print_cnt = 30 ########################## if file_name != None: f = file(file_name, 'w') for t in list: print >> f, t[0], t[1] f.close() short_list = list[0:print_cnt] if global_var.logger == None: print(short_list) else: print >> global_var.logger, short_list return short_list def randomWalk(self, c, start_index, deta, show = False, file_name = None): init_vec = SparseVector(dic = {start_index:1}) d = 99999 vec0 = init_vec.copy() while d > deta : vec1 = self.map(vec0) vec1 = vec1.scale(c) vec1 = vec1.add(init_vec.scale(1-c)) deta_vec = vec1.minus(vec0) d = deta_vec.mod() vec0 = vec1 if not show and file_name == None: return vec0 list = sorted(vec0.vec.items(), key = lambda d:d[1], reverse = True) print_cnt = 30 if file_name != None: f = file(file_name, 'w') for t in list: f.write(str(t)) f.close() short_list = list[0:print_cnt] if show: if global_var.logger == None: print(short_list) else: print >> global_var.logger, short_list return vec0 if __name__ == '__main__': ''' vec1 = SparseVector(list = [0.8147, 0.0975, 0.1576, 0.1419, 0.6557]) vec2 = SparseVector(list = [0.9058, 0.2785, 0.9706, 0.4218, 0.0357]) vec3 = SparseVector(list = [0.1270, 0.5469, 0.9572, 0.9157, 0.8491]) vec4 = SparseVector(list = [0.9134, 0.9575, 0.4854, 0.7922, 0.9340]) vec5 = SparseVector(list = [0.6324, 0.9649, 0.8003, 0.9595, 0.6787]) vec1 = vec1.scale(0.2) vec2 = vec2.scale(0.2) vec3 = vec3.scale(0.2) vec4 = vec4.scale(0.2) vec5 = vec5.scale(0.2) vec = SparseVector(list = [0.7577, 0.7431, 0.3922, 0.6555, 0.1712]) mat = SparseMatrix() mat.setRow(1, vec1) mat.setRow(2, vec2) mat.setRow(3, vec3) mat.setRow(4, vec4) mat.setRow(5, vec5) ''' mat = SparseMatrix() mat.loadFromNwbFile('/mnt/share/graph_2_complete_huixue.nwb') mat = mat.prepareForRW() mat.randomWalk(0.8, 12, 1e-5, True) mat.randomWalkPair(0.8, 12, 1e-5)
Python
###################### construct graph ########################## ###### the version : complete sub-graph with super node import matrix import global_var ### twitter api agent ### import twitter import MySQLdb import cPickle as pickle class TwitterApiAgentDB: api = twitter.Api( \ consumer_key = "S0HrvMBtFWrnccV9mXKKeQ", \ consumer_secret = "EVkctWVhzv1CdvT4Tkezf1pA6LU8xpk0udfgdWpNAk", \ access_token_key = "10434312-vEHrNtZYqpT7z2iPXqPqq5JEJlRsPulHLTLZEEk3K", \ access_token_secret = "4ifpNIckQkyBLKWw6rwJ8bMuqTYZs4W6NLiIy1Yi4") db = MySQLdb.connect(user='root',passwd='123',db='twitter') cursor = db.cursor() def getName(self, id): name = None sqltext = '''select id, name from user where id = ''' + str(id) cnt = self.cursor.execute(sqltext) if cnt > 0 : t = self.cursor.fetchone() return t[1] try: user = self.api.GetUser(id) name = user.screen_name except: msg = "id " + str(id) + " can not get name," \ + " maybe the id is not available." print >> global_var.logger, msg return "unknown name" user_str = pickle.dumps(user, 2) sqltext = '''insert into user values (%s, %s, %s )''' self.cursor.execute(sqltext,(id, name, user_str)) return name def getId(self, name): id = None sqltext = '''select id, name from user where name = ''' + '\'' + str(name) + '\'' cnt = self.cursor.execute(sqltext) if cnt > 0 : t = self.cursor.fetchone() return t[0] try: user = self.api.GetUser(name) id = user.id except: msg = "name " + str(name) + " can not get id," \ + " maybe the name is not available or network error!." print >> global_var.logger, msg return -1 user_str = pickle.dumps(user, 2) sqltext = '''insert into user values (%s, %s, %s )''' self.cursor.execute(sqltext,(id, name, user_str)) return id def getUser(self, id = None, name = None): user = None if isinstance(id, int) or isinstance(id, long): sqltext = '''select detail from user where id = ''' + '\'' + str(id) + '\'' cnt = self.cursor.execute(sqltext) if cnt > 0: t = self.cursor.fetchone() t = t[0] user = pickle.loads(t) return user try: user = self.api.GetUser(id) except: msg = "id " + str(id) + " can not get user," \ + " maybe the id is not available." print >> global_var.logger, msg return user if isinstance(name, str): sqltext = '''select detail from user where name = ''' + '\'' + str(name) + '\'' cnt = self.cursor.execute(sqltext) if cnt > 0: t = self.cursor.fetchone() t = t[0] user = pickle.loads(t) return user try: user = self.api.GetUser(name) except: msg = "name " + str(name) + " can not get user," \ + " maybe the name is not available." print >> global_var.logger, msg return user user_str = pickle.dumps(user, 2) sqltext = '''insert into user values (%s, %s, %s )''' self.cursor.execute(sqltext,(user.id, user.screen_name, user_str)) return user def isPrivate(self, id): user = self.getUser(id) return user.protected def isHub(self, id): # followers_n > 2000 user = self.getUser(id) return user.followers_count > 2000 def getFFT(self, id): # followers_n friends_n tweets_n user = self.getUser(id) return (user.followers_count, user.friends_count, user.statuses_count) def getFollowers(self, id): # 10,000 is the limit !!! followerids = [] if self.isPrivate(id): return followerids sqltext = '''select * from followers where id = ''' + str(id) cnt = self.cursor.execute(sqltext) if cnt > 0: t = self.cursor.fetchone() list = t[1] followerids = pickle.loads(list) return followerids try: results = self.api.GetFollowerIDs(id) followerids = results['ids'] while(results['next_cursor'] != 0): results = self.api.GetFollowerIDs(id, results['next_cursor']) followerids.extend(results['ids']) except: name = self.getName(id) msg = "" + name + "\'s followers id list can not be got, " + \ "maybe get data from twitter error." print >> global_var.logger, msg return followerids sqltext = '''insert into followers values (%s, %s) ''' self.cursor.execute(sqltext, (str(id), pickle.dumps(followerids, 2))) return followerids def getFriends(self, id): # 10,000 is the limit !!! friendids = [] if self.isPrivate(id): return friendis sqltext = '''select * from friends where id = ''' + str(id) cnt = self.cursor.execute(sqltext) if cnt > 0: t = self.cursor.fetchone() list = t[1] friendids = pickle.loads(list) return friendids try: results = self.api.GetFriendIDs(id) friendids = results['ids'] while(results['next_cursor'] != 0): results = self.api.GetFriendIDs(id, results['next_cursor']) friendids.extend(results['ids']) except: name = self.getName(id) msg = "" + name + "\'s friends id list can not be got, " + \ "maybe the user is private. or get data from twitter error." print >> global_var.logger, msg return friendids sqltext = '''insert into friends values (%s, %s) ''' self.cursor.execute(sqltext, (str(id), pickle.dumps(friendids, 2))) return friendids def loadTweets(self, user_id_or_name): all_twts = [] try: reslen = 1 i = 1 while reslen != 0: twts = self.api.GetUserTimeline(id=user_id_or_name, page= i, count = 200, include_rts=True, include_entities=True) reslen = len(twts) i += 1 all_twts.extend(twts) except: user = self.getUser(user_id_or_name, user_id_or_name) msg = "" + user.screen_name + "\'s tweets loading error!" print >> global_var.logger, msg return [] for twt in all_twts: name = twt.user.screen_name id = twt.user.id sqltext = ''' insert into tweets values (%s,%s,%s,%s,%s,%s,%s,%s)''' self.cursor.execute(sqltext,(twt.id, \ twt.text.encode('utf-8'), name, id, twt.in_reply_to_status_id, \ twt.in_reply_to_screen_name, twt.in_reply_to_user_id, \ pickle.dumps(twt,2))) return all_twts ######## global var GRAPH_SUPER_NODE_ID = 0.1 ### Class:Graph Node class GraphNode: id = -1 nodes_list = None # list tagged = False global GRAPH_SUPER_NODE_ID def __init__(self, id = -1, nodes_list = None, tagged = False): self.id = id self.nodes_list = nodes_list self.tagged = tagged def printNode(self, agent): namelist = []; for id in self.nodes_list: if id == GRAPH_SUPER_NODE_ID : namelist.append('super_node') continue name = agent.getName(id) namelist.append(name) if self.id == GRAPH_SUPER_NODE_ID: name = 'super_node' else: name = agent.getName(self.id) msg = str(name) + '\t' + str(namelist) + str(self.tagged) print >> global_var.logger, msg return msg def addTag(self): self.tagged = True def removeTag(self): self.tagged = False def isTagged(self): return self.tagged def haveNode(self, node_id): return node_id in self.nodes_list def deleteNode(self, node_id): if self.haveNode(node_id): self.nodes_list.remove(node_id) else: return False return True def addNode(self, node_id, dup = False): if dup: self.nodes_list.append(node_id) return if node_id not in self.nodes_list: self.nodes_list.append(node_id) ### Class:Graph from collections import deque class Graph: nodes_list = None global GRAPH_SUPER_NODE_ID def __init__(self): self.nodes_list = {} g_node = GraphNode(GRAPH_SUPER_NODE_ID, [GRAPH_SUPER_NODE_ID]) self.nodes_list[GRAPH_SUPER_NODE_ID] = g_node def clear(self): self.nodes_list.clear() def addEdge(self, source, target): if source in self.nodes_list: self.nodes_list[source].addNode(target) else: new_node = GraphNode(source, [target]) self.nodes_list[source] = new_node def construct_v2(self, agent, name, max_level = 10): start_id = agent.getId(name) if agent.isHub(start_id): msg = "%s is hub!" %(name) print >> global_var.logger, msg return if agent.isPrivate(start_id): msg = "%s is private!" %(name) print >> global_var.logger, msg return cache = set() queue = deque() entity = (start_id, 1) # id: start_id, level : 1 queue.append(entity) cache.add(start_id) while len(queue) > 0: entity = queue.popleft() travel_id = entity[0] level = entity[1] follower_ids = agent.getFollowers(travel_id) friend_ids = agent.getFriends(travel_id) if level < max_level: for id in follower_ids: try: user = agent.getUser(id) if user == None : continue except: continue self.addEdge(travel_id, id) if (not agent.isPrivate(id)) and (not agent.isHub(id)): if id not in cache: new_entity = (id, level + 1) queue.append(new_entity) cache.add(id) for id in friend_ids: try: user = agent.getUser(id) if user == None : continue except: continue self.addEdge(id, travel_id) if (not agent.isPrivate(id)) and (not agent.isHub(id)): if id not in cache: new_entity = (id, level + 1) queue.append(new_entity) cache.add(id) else: # the max_level for id in follower_ids: if id in cache: self.addEdge(travel_id, id) for id in friend_ids: if id in cache: self.addEdge(id, travel_id) for id in cache: if id not in self.nodes_list: g_node = GraphNode(id, []) self.nodes_list[id] = g_node def construct(self, agent, name, max_level = 10): start_id = agent.getId(name) in_nodes_list = {} cache = set() queue = deque() entity = (start_id, 1) # id: start_id, level : 1 queue.append(entity) cache.add(start_id) while len(queue) > 0 : entity = queue.popleft() travel_id = entity[0] level = entity[1] friend_ids = agent.getFriends(travel_id) in_nodes_list[travel_id] = friend_ids follower_ids = agent.getFollowers(travel_id) if level < max_level: node = GraphNode(travel_id, follower_ids) self.nodes_list[travel_id] = node for id in follower_ids: if id not in cache : new_entity = (id, level + 1) queue.append(new_entity) cache.add(id) else: # the max_level list = [] for id in follower_ids: if id in cache: list.append(id) else: list.append(GRAPH_SUPER_NODE_ID) node = GraphNode(travel_id, list) self.nodes_list[travel_id] = node for id, list in in_nodes_list.iteritems(): for tid in list: if tid not in cache: self.nodes_list[GRAPH_SUPER_NODE_ID].addNode(id, True) else: self.nodes_list[tid].addNode(id) def printGraph(self, agent, filename = ""): try: f = file(filename, 'w') for node in self.nodes_list.itervalues(): msg = node.printNode(agent) f.write(msg) f.write('\n') f.close() except: for node in self.nodes_list.itervalues(): node.printNode(agent) def generateNWB_v2(self, agent, filename = ""): try: sn = -1 f = file(filename, 'w') n = len(self.nodes_list) f.write("*Nodes " + str(n) + '\n') f.write("id*int label*string\n") index = 0 dict = {} in_degree = {} out_degree = {} for node in self.nodes_list: in_degree[node] = 0 index = index + 1 dict[node] = index f.write(str(index) + " " + "\"" + str(node) + "\"\n") if node == GRAPH_SUPER_NODE_ID: sn = index f.write("*DirectedEdges\n") f.write("source*int target*int weight*float\n") for id, node in self.nodes_list.iteritems(): source = id out_degree[source] = len(node.nodes_list) for target in node.nodes_list: f.write(str(dict[source]) + " " + str(dict[target]) + " " + str(1) + "\n") in_degree[target] += 1 for id, cnt in out_degree.iteritems() : if id == GRAPH_SUPER_NODE_ID: continue fo_n, fr_n, t_n = agent.getFFT(id) d = fo_n - cnt if d != 0 : f.write(str(dict[id]) + " " + str(sn) + " " + str(d) + "\n") for id, cnt in in_degree.iteritems() : if id == GRAPH_SUPER_NODE_ID: continue fo_n, fr_n, t_n = agent.getFFT(id) d = fr_n - cnt if d != 0 : f.write(str(sn) + " " + str(dict[id]) + " " + str(d) + "\n") f.close() except: msg = "file " + str(filename) + " can not open!" print >> global_var.logger, msg def generateNWB(self, agent, filename = ""): try: f = file(filename, 'w') n = len(self.nodes_list) f.write("*Nodes " + str(n) + '\n') f.write("id*int label*string\n") index = 0 dict = {} for node in self.nodes_list: index = index + 1 dict[node] = index f.write(str(index) + " " + "\"" + str(node) + "\"\n") f.write("*DirectedEdges\n") f.write("source*int target*int weight*float\n") for id, node in self.nodes_list.iteritems(): source = id dic = {} for tid in node.nodes_list: dic[tid] = 0 for tid in node.nodes_list: dic[tid] = dic[tid] + 1 for tid, cnt in dic.iteritems(): f.write(str(dict[source]) + " " + str(dict[tid]) + " " + str(cnt) + "\n") f.close() except: msg = "file " + str(filename) + " can not open!" print >> global_var.logger, msg import re def loadNwbMapping(filename, inverse = False): # have not super-node dic = {} f = file(filename, 'r') p = re.compile('[0-9]+ \"[0-9]+') for line in f: m = p.match(line) if m != None: line = line.replace('\"','') res = line.split(' ') i = int(res[0]) try: j = long(res[1]) if inverse: dic[j] = i else: dic[i] = j except: pass f.close() return dic def getIdIndex(id, filename): ret = -1 f = file(filename, 'r') p = re.compile('[0-9]+ \"[0-9]+') for line in f: m = p.match(line) if m != None: line = line.replace('\"','') res = line.split(' ') i = int(res[0]) try: j = long(res[1]) if j == id: ret = i except: pass f.close() print >> global_var.logger, ("start index:" + str(ret)) return ret def addNameForNwbFile(agent, filename): fout_name = filename + ".name" fout = file(fout_name,'w') f = file(filename, 'r') p = re.compile('[0-9]+ \"[0-9]+') for line in f: m = p.match(line) if m != None: line = line.replace('\"','') res = line.split(' ') i = int(res[0]) try: j = long(res[1]) name = agent.getName(j) s = str(i) + ' ' + '\"' + str(name) + '\"' fout.write(s) except: s = str(i) + ' ' + "\"OtherNodes\"" fout.write(s) fout.write('\n') else: fout.write(line) f.close() fout.close() def nwb2gexf(agent, nwb_filename, possibility_filename): head = \ '''<?xml version="1.0" encoding="UTF-8"?> <gexf xmlns="http://www.gexf.net/1.1draft" version="1.1" xmlns:viz="http://www.gexf.net/1.1draft/viz" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gexf.net/1.1draft http://www.gexf.net/1.1draft/gexf.xsd"> <meta> <creator>Xie Wei</creator> <description>Twitter Graph</description> </meta> <graph defaultedgetype="directed"> <attributes class="node" mode="static"> <attribute id="twt_id" title="Tweet Id" type="biginteger"></attribute> <attribute id="twt_name" title="Tweet Name" type="string"></attribute> <attribute id="p" title="Possibility" type="double"></attribute> <attribute id="private" title="Private" type="boolean"></attribute> <attribute id="hub" title="Hub" type="boolean"></attribute> <attribute id="followers_n" title="Number of Followers" type="integer"></attribute> <attribute id="friends_n" title="Number of Friends" type="integer"></attribute> <attribute id="tweets_n" title="Number of Tweets" type="integer"></attribute> </attributes> <nodes>''' gexf_file = file(nwb_filename + ".gexf" , 'w') nwb_file = file(nwb_filename, 'r') p_file = file(possibility_filename, 'r') print >> gexf_file, head p_dic = {} for line in p_file: res = line.split(' ') if len(res) == 2: id = int(res[0]) p = float(res[1]) p_dic[id] = p p_file.close() super_node_id = -1 p1 = re.compile('[0-9]+ \"[0-9]+') p2 = re.compile('[0-9]+ [0-9]+') for line in nwb_file: m = p1.match(line) if m != None: line2 = line.replace('\"','') res = line2.split(' ') i = int(res[0]) if "0.1" not in res[1]: j = long(res[1]) name = agent.getName(j) s = \ ''' <node id="%s" label="%s"> <attvalues> <attvalue for="twt_id" value="%s"></attvalue> <attvalue for="twt_name" value="%s"></attvalue> <attvalue for="p" value="%s"></attvalue> <attvalue for="private" value="%s"></attvalue> <attvalue for="hub" value="%s"></attvalue> <attvalue for="followers_n" value="%s"></attvalue> <attvalue for="friends_n" value="%s"></attvalue> <attvalue for="tweets_n" value="%s"></attvalue> </attvalues> </node>''' if i in p_dic: p = p_dic[i] else: p = 0 pri = agent.isPrivate(j) hub = agent.isHub(j) fo_n, fr_n, t_n = agent.getFFT(j) print >> gexf_file, s %(str(i),str(name),str(j),str(name),str(p),\ str(pri), str(hub), str(fo_n), str(fr_n), str(t_n)) else: super_node_id = i if line.startswith("source"): print >> gexf_file, " </nodes>" print >> gexf_file, " <edges>" m = p2.match(line) if m != None: s = ''' <edge source="%s" target="%s"></edge>''' res = line.split(' ') source = int(res[0]) target = int(res[1]) if super_node_id != source and super_node_id != target: print >> gexf_file, s %(str(source), str(target)) nwb_file.close() s = \ ''' </edges> </graph> </gexf>''' print >> gexf_file, s gexf_file.close() import time import sys if __name__ == '__main__': if len(sys.argv) <= 1: name = "huixue" hops = 2 p = 0.8 else: name = sys.argv[1] hops = int(sys.argv[2]) p = float(sys.argv[3]) agent = TwitterApiAgentDB() #agent = TwitterApiAgent() #filestr = "/mnt/share/graph/graph_2_0.8_crimsontrauma_1300848199.42.nwb" #addNameForNwbFile(agent, filestr) ''' if True: sys.exit() print 'I am not out!' ''' filestr = "/mnt/share/graph/graph_" + str(hops) + "_" \ + str(p) + "_" + str(name) + '_' + str(time.time()) + ".nwb" logfile = file(filestr + ".log", 'w') global_var.logger = logfile graph = Graph() graph.construct_v2(agent, name, hops) #graph.printGraph(agent) graph.generateNWB_v2(agent, filename = filestr) graph.clear() ''' dic = loadNwbMapping(filestr, inverse = True) for id in dic.iterkeys(): agent.loadTweets(id) ''' mat = matrix.SparseMatrix() mat.loadFromNwbFile(filestr) ######### #mat.printInfo() ######### mat = mat.prepareForRW() id = agent.getId(name) index = getIdIndex(id, filestr) mat.randomWalk(p, index, 1e-5, True) list = mat.randomWalkPair(p, index, 1e-5, filestr + ".p") mat.clear() nwb2gexf(agent, filestr, filestr + ".p") dic = loadNwbMapping(filestr) for t in list: if t[0] in dic: id = dic[t[0]] name = agent.getName(id) print >> logfile, name, t[1] logfile.close()
Python
#!/usr/bin/python # Copyright 2011 Google, Inc. All Rights Reserved. # simple script to walk source tree looking for third-party licenses # dumps resulting html page to stdout import os, re, mimetypes, sys # read source directories to scan from command line SOURCE = sys.argv[1:] # regex to find /* */ style comment blocks COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL) # regex used to detect if comment block is a license COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE) COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE) EXCLUDE_TYPES = [ "application/xml", "image/png", ] # list of known licenses; keys are derived by stripping all whitespace and # forcing to lowercase to help combine multiple files that have same license. KNOWN_LICENSES = {} class License: def __init__(self, license_text): self.license_text = license_text self.filenames = [] # add filename to the list of files that have the same license text def add_file(self, filename): if filename not in self.filenames: self.filenames.append(filename) LICENSE_KEY = re.compile(r"[^\w]") def find_license(license_text): # TODO(alice): a lot these licenses are almost identical Apache licenses. # Most of them differ in origin/modifications. Consider combining similar # licenses. license_key = LICENSE_KEY.sub("", license_text).lower() if license_key not in KNOWN_LICENSES: KNOWN_LICENSES[license_key] = License(license_text) return KNOWN_LICENSES[license_key] def discover_license(exact_path, filename): # when filename ends with LICENSE, assume applies to filename prefixed if filename.endswith("LICENSE"): with open(exact_path) as file: license_text = file.read() target_filename = filename[:-len("LICENSE")] if target_filename.endswith("."): target_filename = target_filename[:-1] find_license(license_text).add_file(target_filename) return None # try searching for license blocks in raw file mimetype = mimetypes.guess_type(filename) if mimetype in EXCLUDE_TYPES: return None with open(exact_path) as file: raw_file = file.read() # include comments that have both "license" and "copyright" in the text for comment in COMMENT_BLOCK.finditer(raw_file): comment = comment.group(1) if COMMENT_LICENSE.search(comment) is None: continue if COMMENT_COPYRIGHT.search(comment) is None: continue find_license(comment).add_file(filename) for source in SOURCE: for root, dirs, files in os.walk(source): for name in files: discover_license(os.path.join(root, name), name) print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>" for license in KNOWN_LICENSES.values(): print "<h3>Notices for files:</h3><ul>" filenames = license.filenames filenames.sort() for filename in filenames: print "<li>%s</li>" % (filename) print "</ul>" print "<pre>%s</pre>" % license.license_text print "</body></html>"
Python
# -*- coding: iso-8859-1 -*- ######################################################################################################## ### LICENSE ######################################################################################################## # # findmyhash.py - v 1.1.2 # # This script is under GPL v3 License (http://www.gnu.org/licenses/gpl-3.0.html). # # Only this source code is under GPL v3 License. Web services used in this script are under # different licenses. # # If you know some clause in one of these web services which forbids to use it inside this script, # please contact me to remove the web service as soon as possible. # # Developed by JulGor ( http://laxmarcaellugar.blogspot.com/ ) # Mail: bloglaxmarcaellugar AT gmail DOT com # twitter: @laXmarcaellugar # ######################################################################################################## ### IMPORTS ######################################################################################################## try: import sys import hashlib import urllib2 import getopt from os import path from urllib import urlencode from re import search, findall from random import seed, randint from base64 import decodestring, encodestring from cookielib import LWPCookieJar except: print """ Execution error: You required some basic Python libraries. This application use: sys, hashlib, urllib, urllib2, os, re, random, getopt, base64 and cookielib. Please, check if you have all of them installed in your system. """ sys.exit(1) try: from httplib2 import Http except: print """ Execution error: The Python library httplib2 is not installed in your system. Please, install it before use this application. """ sys.exit(1) try: from libxml2 import parseDoc except: print """ Execution error: The Python library libxml2 is not installed in your system. Because of that, some plugins aren't going to work correctly. Please, install it before use this application. """ ######################################################################################################## ### CONSTANTS ######################################################################################################## MD4 = "md4" MD5 = "md5" SHA1 = "sha1" SHA224 = "sha224" SHA256 = "sha256" SHA384 = "sha384" SHA512 = "sha512" RIPEMD = "rmd160" LM = "lm" NTLM = "ntlm" MYSQL = "mysql" CISCO7 = "cisco7" JUNIPER = "juniper" GOST = "gost" WHIRLPOOL = "whirlpool" LDAP_MD5 = "ldap_md5" LDAP_SHA1 = "ldap_sha1" USER_AGENTS = [ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Crazy Browser 1.0.5)", "curl/7.7.2 (powerpc-apple-darwin6.0) libcurl 7.7.2 (OpenSSL 0.9.6b)", "Mozilla/5.0 (X11; U; Linux amd64; en-US; rv:5.0) Gecko/20110619 Firefox/5.0", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b8pre) Gecko/20101213 Firefox/4.0b8pre", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) chromeframe/10.0.648.205", "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727)", "Opera/9.80 (Windows NT 6.1; U; sv) Presto/2.7.62 Version/11.01", "Opera/9.80 (Windows NT 6.1; U; pl) Presto/2.7.62 Version/11.00", "Opera/9.80 (X11; Linux i686; U; pl) Presto/2.6.30 Version/10.61", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.872.0 Safari/535.2", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.812.0 Safari/535.1", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" ] ######################################################################################################## ### CRACKERS DEFINITION ######################################################################################################## class SCHWETT: name = "schwett" url = "http://schwett.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://schwett.com/md5/index.php?md5value=%s&md5c=Hash+Match" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r"<h3><font color='red'>No Match Found</font></h3><br />", html) if match: return None else: return "The hash is broken, please contact with La X marca el lugar and send it the hash value to add the correct regexp." class NETMD5CRACK: name = "netmd5crack" url = "http://www.netmd5crack.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://www.netmd5crack.com/cgi-bin/Crack.py?InputHash=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None regexp = r'<tr><td class="border">%s</td><td class="border">[^<]*</td></tr></table>' % (hashvalue) match = search (regexp, html) if match: match2 = search ( "Sorry, we don't have that hash in our database", match.group() ) if match2: return None else: return match.group().split('border')[2].split('<')[0][2:] class MD5_CRACKER: name = "md5-cracker" url = "http://www.md5-cracker.tk" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://www.md5-cracker.tk/xml.php?md5=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response if response: try: doc = parseDoc ( response.read() ) except: print "INFO: You need libxml2 to use this plugin." return None else: return None result = doc.xpathEval("//data") if len(result): return result[0].content else: return None class BENRAMSEY: name = "benramsey" url = "http://tools.benramsey.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://tools.benramsey.com/md5/md5.php?hash=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<string><!\[CDATA\[[^\]]*\]\]></string>', html) if match: return match.group().split(']')[0][17:] else: return None class GROMWEB: name = "gromweb" url = "http://md5.gromweb.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5.gromweb.com/query/%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response if response: return response.read() return response class HASHCRACKING: name = "hashcracking" url = "http://md5.hashcracking.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5.hashcracking.com/search.php?md5=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'\sis.*', html) if match: return match.group()[4:] return None class VICTOROV: name = "hashcracking" url = "http://victorov.su" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://victorov.su/md5/?md5e=&md5d=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r': <b>[^<]*</b><br><form action="">', html) if match: return match.group().split('b>')[1][:-2] return None class THEKAINE: name = "thekaine" url = "http://md5.thekaine.de" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5.thekaine.de/?hash=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<td colspan="2"><br><br><b>[^<]*</b></td><td></td>', html) if match: match2 = search (r'not found', match.group() ) if match2: return None else: return match.group().split('b>')[1][:-2] class TMTO: name = "tmto" url = "http://www.tmto.org" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://www.tmto.org/api/latest/?hash=%s&auth=true" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'text="[^"]+"', html) if match: return decodestring(match.group().split('"')[1]) else: return None class MD5_DB: name = "md5-db" url = "http://md5-db.de" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5-db.de/%s.html" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response if not response: return None html = None if response: html = response.read() else: return None match = search (r'<strong>Es wurden 1 m.gliche Begriffe gefunden, die den Hash \w* verwenden:</strong><ul><li>[^<]*</li>', html) if match: return match.group().split('li>')[1][:-2] else: return None class MY_ADDR: name = "my-addr" url = "http://md5.my-addr.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5.my-addr.com/md5_decrypt-md5_cracker_online/md5_decoder_tool.php" # Build the parameters params = { "md5" : hashvalue, "x" : 21, "y" : 8 } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r"<span class='middle_title'>Hashed string</span>: [^<]*</div>", html) if match: return match.group().split('span')[2][3:-6] else: return None class MD5PASS: name = "md5pass" url = "http://md5pass.info" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = self.url # Build the parameters params = { "hash" : hashvalue, "get_pass" : "Get Pass" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r"Password - <b>[^<]*</b>", html) if match: return match.group().split('b>')[1][:-2] else: return None class MD5DECRYPTION: name = "md5decryption" url = "http://md5decryption.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = self.url # Build the parameters params = { "hash" : hashvalue, "submit" : "Decrypt It!" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r"Decrypted Text: </b>[^<]*</font>", html) if match: return match.group().split('b>')[1][:-7] else: return None class MD5CRACK: name = "md5crack" url = "http://md5crack.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5crack.com/crackmd5.php" # Build the parameters params = { "term" : hashvalue, "crackbtn" : "Crack that hash baby!" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'Found: md5\("[^"]+"\)', html) if match: return match.group().split('"')[1] else: return None class MD5ONLINE: name = "md5online" url = "http://md5online.net" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = self.url # Build the parameters params = { "pass" : hashvalue, "option" : "hash2text", "send" : "Submit" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<center><p>md5 :<b>\w*</b> <br>pass : <b>[^<]*</b></p></table>', html) if match: return match.group().split('b>')[3][:-2] else: return None class MD5_DECRYPTER: name = "md5-decrypter" url = "http://md5-decrypter.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = self.url # Build the parameters params = { "data[Row][cripted]" : hashvalue } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = findall (r'<b class="res">[^<]*</b>', html) if match: return match[1].split('>')[1][:-3] else: return None class AUTHSECUMD5: name = "authsecu" url = "http://www.authsecu.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://www.authsecu.com/decrypter-dechiffrer-cracker-hash-md5/script-hash-md5.php" # Build the parameters params = { "valeur_bouton" : "dechiffrage", "champ1" : "", "champ2" : hashvalue, "dechiffrer.x" : "78", "dechiffrer.y" : "7" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = findall (r'<td><p class="chapitre---texte-du-tableau-de-niveau-1">[^<]*</p></td>', html) if len(match) > 2: return match[1].split('>')[2][:-3] else: return None class HASHCRACK: name = "hashcrack" url = "http://hashcrack.com" supported_algorithm = [MD5, SHA1, MYSQL, LM, NTLM] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://hashcrack.com/indx.php" hash2 = None if alg in [LM, NTLM] and ':' in hashvalue: if alg == LM: hash2 = hashvalue.split(':')[0] else: hash2 = hashvalue.split(':')[1] else: hash2 = hashvalue # Delete the possible starting '*' if alg == MYSQL and hash2[0] == '*': hash2 = hash2[1:] # Build the parameters params = { "auth" : "8272hgt", "hash" : hash2, "string" : "", "Submit" : "Submit" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<div align=center>"[^"]*" resolves to</div><br><div align=center> <span class=hervorheb2>[^<]*</span></div></TD>', html) if match: return match.group().split('hervorheb2>')[1][:-18] else: return None class OPHCRACK: name = "ophcrack" url = "http://www.objectif-securite.ch" supported_algorithm = [LM, NTLM] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Check if hashvalue has the character ':' if ':' not in hashvalue: return None # Ophcrack doesn't crack NTLM hashes. It needs a valid LM hash and this one is an empty hash. if hashvalue.split(':')[0] == "aad3b435b51404eeaad3b435b51404ee": return None # Build the URL and the headers url = "http://www.objectif-securite.ch/en/products.php?hash=%s" % (hashvalue.replace(':', '%3A')) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<table><tr><td>Hash:</td><td>[^<]*</td></tr><tr><td><b>Password:</b></td><td><b>[^<]*</b></td>', html) if match: return match.group().split('b>')[3][:-2] else: return None class C0LLISION: name = "c0llision" url = "http://www.c0llision.net" supported_algorithm = [MD5, LM, NTLM] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Check if hashvalue has the character ':' if alg in [LM, NTLM] and ':' not in hashvalue: return None # Look for "hash[_csrf_token]" parameter response = do_HTTP_request ( "http://www.c0llision.net/webcrack.php" ) html = None if response: html = response.read() else: return None match = search (r'<input type="hidden" name="hash._csrf_token." value="[^"]*" id="hash__csrf_token" />', html) token = None if match: token = match.group().split('"')[5] # Build the URL url = "http://www.c0llision.net/webcrack/request" # Build the parameters params = { "hash[_input_]" : hashvalue, "hash[_csrf_token]" : token } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = None if alg in [LM, NTLM]: html = html.replace('\n', '') result = "" match = search (r'<table class="pre">.*?</table>', html) if match: try: doc = parseDoc ( match.group() ) except: print "INFO: You need libxml2 to use this plugin." return None lines = doc.xpathEval("//tr") for l in lines: doc = parseDoc ( str(l) ) cols = doc.xpathEval("//td") if len(cols) < 4: return None if cols[2].content: result = " > %s (%s) = %s\n" % ( cols[1].content, cols[2].content, cols[3].content ) #return ( result and "\n" + result or None ) return ( result and result.split()[-1] or None ) else: match = search (r'<td class="plaintext">[^<]*</td>', html) if match: return match.group().split('>')[1][:-4] return None class REDNOIZE: name = "rednoize" url = "http://md5.rednoize.com" supported_algorithm = [MD5, SHA1] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "" if alg == MD5: url = "http://md5.rednoize.com/?p&s=md5&q=%s&_=" % (hashvalue) else: url = "http://md5.rednoize.com/?p&s=sha1&q=%s&_=" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None return html class CMD5: name = "cmd5" url = "http://www.cmd5.org" supported_algorithm = [MD5, NTLM] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Look for hidden parameters response = do_HTTP_request ( "http://www.cmd5.org/" ) html = None if response: html = response.read() else: return None match = search (r'<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="[^"]*" />', html) viewstate = None if match: viewstate = match.group().split('"')[7] match = search (r'<input type="hidden" name="ctl00.ContentPlaceHolder1.HiddenField1" id="ctl00_ContentPlaceHolder1_HiddenField1" value="[^"]*" />', html) ContentPlaceHolder1 = "" if match: ContentPlaceHolder1 = match.group().split('"')[7] match = search (r'<input type="hidden" name="ctl00.ContentPlaceHolder1.HiddenField2" id="ctl00_ContentPlaceHolder1_HiddenField2" value="[^"]*" />', html) ContentPlaceHolder2 = "" if match: ContentPlaceHolder2 = match.group().split('"')[7] # Build the URL url = "http://www.cmd5.org/" hash2 = "" if alg == MD5: hash2 = hashvalue else: if ':' in hashvalue: hash2 = hashvalue.split(':')[1] # Build the parameters params = { "__EVENTTARGET" : "", "__EVENTARGUMENT" : "", "__VIEWSTATE" : viewstate, "ctl00$ContentPlaceHolder1$TextBoxq" : hash2, "ctl00$ContentPlaceHolder1$InputHashType" : alg, "ctl00$ContentPlaceHolder1$Button1" : "decrypt", "ctl00$ContentPlaceHolder1$HiddenField1" : ContentPlaceHolder1, "ctl00$ContentPlaceHolder1$HiddenField2" : ContentPlaceHolder2 } header = { "Referer" : "http://www.cmd5.org/" } # Make the request response = do_HTTP_request ( url, params, header ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<span id="ctl00_ContentPlaceHolder1_LabelResult">[^<]*</span>', html) if match: return match.group().split('>')[1][:-6] else: return None class AUTHSECUCISCO7: name = "authsecu" url = "http://www.authsecu.com" supported_algorithm = [CISCO7] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL and the headers url = "http://www.authsecu.com/decrypter-dechiffrer-cracker-password-cisco-7/script-password-cisco-7-launcher.php" # Build the parameters params = { "valeur_bouton" : "dechiffrage", "champ1" : hashvalue, "dechiffrer.x" : 43, "dechiffrer.y" : 16 } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = findall (r'<td><p class="chapitre---texte-du-tableau-de-niveau-1">[^<]*</p></td>', html) if match: return match[1].split('>')[2][:-3] else: return None class CACIN: name = "cacin" url = "http://cacin.net" supported_algorithm = [CISCO7] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL and the headers url = "http://cacin.net/cgi-bin/decrypt-cisco.pl?cisco_hash=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<tr>Cisco password 7: [^<]*</tr><br><tr><th><br>Decrypted password: .*', html) if match: return match.group().split(':')[2][1:] else: return None class IBEAST: name = "ibeast" url = "http://www.ibeast.com" supported_algorithm = [CISCO7] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL and the headers url = "http://www.ibeast.com/content/tools/CiscoPassword/decrypt.php?txtPassword=%s&submit1=Enviar+consulta" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<font size="\+2">Your Password is [^<]*<br>', html) if match: return match.group().split('is ')[1][:-4] else: return None class PASSWORD_DECRYPT: name = "password-decrypt" url = "http://password-decrypt.com" supported_algorithm = [CISCO7, JUNIPER] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL and the parameters url = "" params = None if alg == CISCO7: url = "http://password-decrypt.com/cisco.cgi" params = { "submit" : "Submit", "cisco_password" : hashvalue, "submit" : "Submit" } else: url = "http://password-decrypt.com/juniper.cgi" params = { "submit" : "Submit", "juniper_password" : hashvalue, "submit" : "Submit" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'Decrypted Password:&nbsp;<B>[^<]*</B> </p>', html) if match: return match.group().split('B>')[1][:-2] else: return None class BIGTRAPEZE: name = "bigtrapeze" url = "http://www.bigtrapeze.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL and the headers url = "http://www.bigtrapeze.com/md5/index.php" # Build the parameters params = { "query" : hashvalue, " Crack " : "Enviar consulta" } # Build the Headers with a random User-Agent headers = { "User-Agent" : USER_AGENTS[randint(0, len(USER_AGENTS))-1] } # Make the request response = do_HTTP_request ( url, params, headers ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'Congratulations!<li>The hash <strong>[^<]*</strong> has been deciphered to: <strong>[^<]*</strong></li>', html) if match: return match.group().split('strong>')[3][:-2] else: return None class HASHCHECKER: name = "hashchecker" url = "http://www.hashchecker.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL and the headers url = "http://www.hashchecker.com/index.php" # Build the parameters params = { "search_field" : hashvalue, "Submit" : "search" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<td><li>Your md5 hash is :<br><li>[^\s]* is <b>[^<]*</b> used charlist :2</td>', html) if match: return match.group().split('b>')[1][:-2] else: return None class MD5HASHCRACKER: name = "md5hashcracker" url = "http://md5hashcracker.appspot.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5hashcracker.appspot.com/crack" # Build the parameters params = { "query" : hashvalue, "submit" : "Crack" } # Make the firt request response = do_HTTP_request ( url, params ) # Build the second URL url = "http://md5hashcracker.appspot.com/status" # Make the second request response = do_HTTP_request ( url ) # Analyze the response if response: html = response.read() else: return None match = search (r'<td id="cra[^"]*">not cracked</td>', html) if not match: match = search (r'<td id="cra[^"]*">cracked</td>', html) regexp = r'<td id="pla_' + match.group().split('"')[1][4:] + '">[^<]*</td>' match2 = search (regexp, html) if match2: return match2.group().split('>')[1][:-4] else: return None class PASSCRACKING: name = "passcracking" url = "http://passcracking.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://passcracking.com/index.php" # Build the parameters boundary = "-----------------------------" + str(randint(1000000000000000000000000000,9999999999999999999999999999)) params = [ '--' + boundary, 'Content-Disposition: form-data; name="admin"', '', 'false', '--' + boundary, 'Content-Disposition: form-data; name="admin2"', '', '77.php', '--' + boundary, 'Content-Disposition: form-data; name="datafromuser"', '', '%s' % (hashvalue) , '--' + boundary + '--', '' ] body = '\r\n'.join(params) # Build the headers headers = { "Content-Type" : "multipart/form-data; boundary=%s" % (boundary), "Content-length" : len(body) } # Make the request request = urllib2.Request ( url ) request.add_header ( "Content-Type", "multipart/form-data; boundary=%s" % (boundary) ) request.add_header ( "Content-length", len(body) ) request.add_data(body) try: response = urllib2.urlopen(request) except: return None # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<td>md5 Database</td><td>[^<]*</td><td bgcolor=.FF0000>[^<]*</td>', html) if match: return match.group().split('>')[5][:-4] else: return None class ASKCHECK: name = "askcheck" url = "http://askcheck.com" supported_algorithm = [MD4, MD5, SHA1, SHA256] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://askcheck.com/reverse?reverse=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'Reverse value of [^\s]* hash <a[^<]*</a> is <a[^>]*>[^<]*</a>', html) if match: return match.group().split('>')[3][:-3] else: return None class FOX21: name = "fox21" url = "http://cracker.fox21.at" supported_algorithm = [MD5, LM, NTLM] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None hash2 = None if alg in [LM, NTLM] and ':' in hashvalue: if alg == LM: hash2 = hashvalue.split(':')[0] else: hash2 = hashvalue.split(':')[1] else: hash2 = hashvalue # Build the URL url = "http://cracker.fox21.at/api.php?a=check&h=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response xml = None if response: try: doc = parseDoc ( response.read() ) except: print "INFO: You need libxml2 to use this plugin." return None else: return None result = doc.xpathEval("//hash/@plaintext") if result: return result[0].content else: return None class NICENAMECREW: name = "nicenamecrew" url = "http://crackfoo.nicenamecrew.com" supported_algorithm = [MD5, SHA1, LM] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None hash2 = None if alg in [LM] and ':' in hashvalue: hash2 = hashvalue.split(':')[0] else: hash2 = hashvalue # Build the URL url = "http://crackfoo.nicenamecrew.com/?t=%s" % (alg) # Build the parameters params = { "q" : hash2, "sa" : "Crack" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'The decrypted version of [^\s]* is:<br><strong>[^<]*</strong>', html) if match: return match.group().split('strong>')[1][:-2].strip() else: return None class JOOMLAAA: name = "joomlaaa" url = "http://joomlaaa.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://joomlaaa.com/component/option,com_md5/Itemid,31/" # Build the parameters params = { "md5" : hashvalue, "decode" : "Submit" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r"<td class='title1'>not available</td>", html) if not match: match2 = findall (r"<td class='title1'>[^<]*</td>", html) return match2[1].split('>')[1][:-4] else: return None class MD5_LOOKUP: name = "md5-lookup" url = "http://md5-lookup.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5-lookup.com/livesearch.php?q=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<td width="250">[^<]*</td>', html) if match: return match.group().split('>')[1][:-4] else: return None class SHA1_LOOKUP: name = "sha1-lookup" url = "http://sha1-lookup.com" supported_algorithm = [SHA1] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://sha1-lookup.com/livesearch.php?q=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<td width="250">[^<]*</td>', html) if match: return match.group().split('>')[1][:-4] else: return None class SHA256_LOOKUP: name = "sha256-lookup" url = "http://sha-256.sha1-lookup.com" supported_algorithm = [SHA256] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://sha-256.sha1-lookup.com/livesearch.php?q=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<td width="250">[^<]*</td>', html) if match: return match.group().split('>')[1][:-4] else: return None class RIPEMD160_LOOKUP: name = "ripemd-lookup" url = "http://www.ripemd-lookup.com" supported_algorithm = [RIPEMD] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://www.ripemd-lookup.com/livesearch.php?q=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<td width="250">[^<]*</td>', html) if match: return match.group().split('>')[1][:-4] else: return None class MD5_COM_CN: name = "md5.com.cn" url = "http://md5.com.cn" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5.com.cn/md5reverse" # Build the parameters params = { "md" : hashvalue, "submit" : "MD5 Crack" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<b style="color:red;">[^<]*</b><br/><span', html) if match: return match.group().split('>')[1][:-3] else: return None class DIGITALSUN: name = "digitalsun.pl" url = "http://md5.digitalsun.pl" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5.digitalsun.pl/" # Build the parameters params = { "hash" : hashvalue } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<b>[^<]*</b> == [^<]*<br>\s*<br>', html) if match: return match.group().split('b>')[1][:-2] else: return None class DRASEN: name = "drasen.net" url = "http://md5.drasen.net" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5.drasen.net/search.php?query=%s" % (hashvalue) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'Hash: [^<]*<br />Plain: [^<]*<br />', html) if match: return match.group().split('<br />')[1][7:] else: return None class MYINFOSEC: name = "myinfosec" url = "http://md5.myinfosec.net" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5.myinfosec.net/md5.php" # Build the parameters params = { "md5hash" : hashvalue } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<center></center>[^<]*<font color=green>[^<]*</font><br></center>', html) if match: return match.group().split('>')[3][:-6] else: return None class MD5_NET: name = "md5.net" url = "http://md5.net" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://www.md5.net/cracker.php" # Build the parameters params = { "hash" : hashvalue } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<input type="text" id="hash" size="32" value="[^"]*"/>', html) if match: return match.group().split('"')[7] else: return None class NOISETTE: name = "noisette.ch" url = "http://md5.noisette.ch" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5.noisette.ch/index.php" # Build the parameters params = { "hash" : hashvalue } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<p>String to hash : <input name="text" value="[^"]+"/>', html) if match: return match.group().split('"')[3] else: return None class MD5HOOD: name = "md5hood" url = "http://md5hood.com" supported_algorithm = [MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://md5hood.com/index.php/cracker/crack" # Build the parameters params = { "md5" : hashvalue, "submit" : "Go" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<div class="result_true">[^<]*</div>', html) if match: return match.group().split('>')[1][:-5] else: return None class STRINGFUNCTION: name = "stringfunction" url = "http://www.stringfunction.com" supported_algorithm = [MD5, SHA1] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "" if alg == MD5: url = "http://www.stringfunction.com/md5-decrypter.html" else: url = "http://www.stringfunction.com/sha1-decrypter.html" # Build the parameters params = { "string" : hashvalue, "submit" : "Decrypt", "result" : "" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<textarea class="textarea-input-tool-b" rows="10" cols="50" name="result"[^>]*>[^<]+</textarea>', html) if match: return match.group().split('>')[1][:-10] else: return None class XANADREL: name = "99k.org" url = "http://xanadrel.99k.org" supported_algorithm = [MD4, MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://xanadrel.99k.org/hashes/index.php?k=search" # Build the parameters params = { "hash" : hashvalue, "search" : "ok" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<p>Hash : [^<]*<br />Type : [^<]*<br />Plain : "[^"]*"<br />', html) if match: return match.group().split('"')[1] else: return None class SANS: name = "sans" url = "http://isc.sans.edu" supported_algorithm = [MD5, SHA1] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://isc.sans.edu/tools/reversehash.html" # Build the Headers with a random User-Agent headers = { "User-Agent" : USER_AGENTS[randint(0, len(USER_AGENTS))-1] } # Build the parameters response = do_HTTP_request ( url, httpheaders=headers ) html = None if response: html = response.read() else: return None match = search (r'<input type="hidden" name="token" value="[^"]*" />', html) token = "" if match: token = match.group().split('"')[5] else: return None params = { "token" : token, "text" : hashvalue, "word" : "", "submit" : "Submit" } # Build the Headers with the Referer header headers["Referer"] = "http://isc.sans.edu/tools/reversehash.html" # Make the request response = do_HTTP_request ( url, params, headers ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'... hash [^\s]* = [^\s]*\s*</p><br />', html) if match: print "hola mundo" return match.group().split('=')[1][:-10].strip() else: return None class BOKEHMAN: name = "bokehman" url = "http://bokehman.com" supported_algorithm = [MD4, MD5] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None # Build the URL url = "http://bokehman.com/cracker/" # Build the parameters from the main page response = do_HTTP_request ( url ) html = None if response: html = response.read() else: return None match = search (r'<input type="hidden" name="PHPSESSID" id="PHPSESSID" value="[^"]*" />', html) phpsessnid = "" if match: phpsessnid = match.group().split('"')[7] else: return None match = search (r'<input type="hidden" name="key" id="key" value="[^"]*" />', html) key = "" if match: key = match.group().split('"')[7] else: return None params = { "md5" : hashvalue, "PHPSESSID" : phpsessnid, "key" : key, "crack" : "Try to crack it" } # Make the request response = do_HTTP_request ( url, params ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<tr><td>[^<]*</td><td>[^<]*</td><td>[^s]*seconds</td></tr>', html) if match: return match.group().split('td>')[1][:-2] else: return None class GOOG_LI: name = "goog.li" url = "http://goog.li" supported_algorithm = [MD5, MYSQL, SHA1, SHA224, SHA384, SHA256, SHA512, RIPEMD, NTLM, GOST, WHIRLPOOL, LDAP_MD5, LDAP_SHA1] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None hash2 = None if alg in [NTLM] and ':' in hashvalue: hash2 = hashvalue.split(':')[1] else: hash2 = hashvalue # Confirm the initial '*' character if alg == MYSQL and hash2[0] != '*': hash2 = '*' + hash2 # Build the URL url = "http://goog.li/?q=%s" % (hash2) # Make the request response = do_HTTP_request ( url ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<br />cleartext[^:]*: [^<]*<br />', html) if match: return match.group().split(':')[1].strip()[:-6] else: return None class WHREPORITORY: name = "Windows Hashes Repository" url = "http://nediam.com.mx" supported_algorithm = [LM, NTLM] def isSupported (self, alg): """Return True if HASHCRACK can crack this type of algorithm and False if it cannot.""" if alg in self.supported_algorithm: return True else: return False def crack (self, hashvalue, alg): """Try to crack the hash. @param hashvalue Hash to crack. @param alg Algorithm to crack.""" # Check if the cracker can crack this kind of algorithm if not self.isSupported (alg): return None hash2 = None if ':' in hashvalue: if alg == LM: hash2 = hashvalue.split(':')[0] else: hash2 = hashvalue.split(':')[1] else: hash2 = hashvalue # Build the URL, parameters and headers url = "" params = None headers = None if alg == LM: url = "http://nediam.com.mx/winhashes/search_lm_hash.php" params = { "lm" : hash2, "btn_go" : "Search" } headers = { "Referer" : "http://nediam.com.mx/winhashes/search_lm_hash.php" } else: url = "http://nediam.com.mx/winhashes/search_nt_hash.php" params = { "nt" : hash2, "btn_go" : "Search" } headers = { "Referer" : "http://nediam.com.mx/winhashes/search_nt_hash.php" } # Make the request response = do_HTTP_request ( url, params, headers ) # Analyze the response html = None if response: html = response.read() else: return None match = search (r'<tr><td align="right">PASSWORD</td><td>[^<]*</td></tr>', html) if match: return match.group().split(':')[1] else: return None CRAKERS = [ SCHWETT, NETMD5CRACK, MD5_CRACKER, BENRAMSEY, GROMWEB, HASHCRACKING, VICTOROV, THEKAINE, TMTO, REDNOIZE, MD5_DB, MY_ADDR, MD5PASS, MD5DECRYPTION, MD5CRACK, MD5ONLINE, MD5_DECRYPTER, AUTHSECUMD5, HASHCRACK, OPHCRACK, C0LLISION, CMD5, AUTHSECUCISCO7, CACIN, IBEAST, PASSWORD_DECRYPT, BIGTRAPEZE, HASHCHECKER, MD5HASHCRACKER, PASSCRACKING, ASKCHECK, FOX21, NICENAMECREW, JOOMLAAA, MD5_LOOKUP, SHA1_LOOKUP, SHA256_LOOKUP, RIPEMD160_LOOKUP, MD5_COM_CN, DIGITALSUN, DRASEN, MYINFOSEC, MD5_NET, NOISETTE, MD5HOOD, STRINGFUNCTION, XANADREL, SANS, BOKEHMAN, GOOG_LI, WHREPORITORY ] ######################################################################################################## ### GENERAL METHODS ######################################################################################################## def configureCookieProcessor (cookiefile='/tmp/searchmyhash.cookie'): '''Set a Cookie Handler to accept cookies from the different Web sites. @param cookiefile Path of the cookie store.''' cookieHandler = LWPCookieJar() if cookieHandler is not None: if path.isfile (cookiefile): cookieHandler.load (cookiefile) opener = urllib2.build_opener ( urllib2.HTTPCookieProcessor(cookieHandler) ) urllib2.install_opener (opener) def do_HTTP_request (url, params={}, httpheaders={}): ''' Send a GET or POST HTTP Request. @return: HTTP Response ''' data = {} request = None # If there is parameters, they are been encoded if params: data = urlencode(params) request = urllib2.Request ( url, data, headers=httpheaders ) else: request = urllib2.Request ( url, headers=httpheaders ) # Send the request try: response = urllib2.urlopen (request) except: return "" return response def printSyntax (): """Print application syntax.""" print """%s 1.1.2 ( http://code.google.com/p/findmyhash/ ) Usage: ------ python %s <algorithm> OPTIONS Accepted algorithms are: ------------------------ MD4 - RFC 1320 MD5 - RFC 1321 SHA1 - RFC 3174 (FIPS 180-3) SHA224 - RFC 3874 (FIPS 180-3) SHA256 - FIPS 180-3 SHA384 - FIPS 180-3 SHA512 - FIPS 180-3 RMD160 - RFC 2857 GOST - RFC 5831 WHIRLPOOL - ISO/IEC 10118-3:2004 LM - Microsoft Windows hash NTLM - Microsoft Windows hash MYSQL - MySQL 3, 4, 5 hash CISCO7 - Cisco IOS type 7 encrypted passwords JUNIPER - Juniper Networks $9$ encrypted passwords LDAP_MD5 - MD5 Base64 encoded LDAP_SHA1 - SHA1 Base64 encoded NOTE: for LM / NTLM it is recommended to introduce both values with this format: python %s LM -h 9a5760252b7455deaad3b435b51404ee:0d7f1f2bdeac6e574d6e18ca85fb58a7 python %s NTLM -h 9a5760252b7455deaad3b435b51404ee:0d7f1f2bdeac6e574d6e18ca85fb58a7 Valid OPTIONS are: ------------------ -h <hash_value> If you only want to crack one hash, specify its value with this option. -f <file> If you have several hashes, you can specify a file with one hash per line. NOTE: All of them have to be the same type. -g If your hash cannot be cracked, search it in Google and show all the results. NOTE: This option ONLY works with -h (one hash input) option. Examples: --------- -> Try to crack only one hash. python %s MD5 -h 098f6bcd4621d373cade4e832627b4f6 -> Try to crack a JUNIPER encrypted password escaping special characters. python %s JUNIPER -h "\$9\$LbHX-wg4Z" -> If the hash cannot be cracked, it will be searched in Google. python %s LDAP_SHA1 -h "{SHA}cRDtpNCeBiql5KOQsKVyrA0sAiA=" -g -> Try to crack multiple hashes using a file (one hash per line). python %s MYSQL -f mysqlhashesfile.txt Contact: -------- [Web] http://laxmarcaellugar.blogspot.com/ [Mail/Google+] bloglaxmarcaellugar@gmail.com [twitter] @laXmarcaellugar """ % ( (sys.argv[0],) * 8 ) def crackHash (algorithm, hashvalue=None, hashfile=None): """Crack a hash or all the hashes of a file. @param alg Algorithm of the hash (MD5, SHA1...). @param hashvalue Hash value to be cracked. @param hashfile Path of the hash file. @return If the hash has been cracked or not.""" global CRAKERS # Cracked hashes will be stored here crackedhashes = [] # Is the hash cracked? cracked = False # Only one of the two possible inputs can be setted. if (not hashvalue and not hashfile) or (hashvalue and hashfile): return False # hashestocrack depends on the input value hashestocrack = None if hashvalue: hashestocrack = [ hashvalue ] else: try: hashestocrack = open (hashfile, "r") except: print "\nIt is not possible to read input file (%s)\n" % (hashfile) return cracked # Try to crack all the hashes... for activehash in hashestocrack: hashresults = [] # Standarize the hash activehash = activehash.strip() if algorithm not in [JUNIPER, LDAP_MD5, LDAP_SHA1]: activehash = activehash.lower() # Initial message print "\nCracking hash: %s\n" % (activehash) # Each loop starts for a different start point to try to avoid IP filtered begin = randint(0, len(CRAKERS)-1) for i in range(len(CRAKERS)): # Select the cracker cr = CRAKERS[ (i+begin)%len(CRAKERS) ]() # Check if the cracker support the algorithm if not cr.isSupported ( algorithm ): continue # Analyze the hash print "Analyzing with %s (%s)..." % (cr.name, cr.url) # Crack the hash result = None try: result = cr.crack ( activehash, algorithm ) # If it was some trouble, exit except: print "\nSomething was wrong. Please, contact with us to report the bug:\n\nbloglaxmarcaellugar@gmail.com\n" if hashfile: try: hashestocrack.close() except: pass return False # If there is any result... cracked = 0 if result: # If it is a hashlib supported algorithm... if algorithm in [MD4, MD5, SHA1, SHA224, SHA384, SHA256, SHA512, RIPEMD]: # Hash value is calculated to compare with cracker result h = hashlib.new (algorithm) h.update (result) # If the calculated hash is the same to cracker result, the result is correct (finish!) if h.hexdigest() == activehash: hashresults.append (result) cracked = 2 # If it is a half-supported hashlib algorithm elif algorithm in [LDAP_MD5, LDAP_SHA1]: alg = algorithm.split('_')[1] ahash = decodestring ( activehash.split('}')[1] ) # Hash value is calculated to compare with cracker result h = hashlib.new (alg) h.update (result) # If the calculated hash is the same to cracker result, the result is correct (finish!) if h.digest() == ahash: hashresults.append (result) cracked = 2 # If it is a NTLM hash elif algorithm == NTLM or (algorithm == LM and ':' in activehash): # NTLM Hash value is calculated to compare with cracker result candidate = hashlib.new('md4', result.split()[-1].encode('utf-16le')).hexdigest() # It's a LM:NTLM combination or a single NTLM hash if (':' in activehash and candidate == activehash.split(':')[1]) or (':' not in activehash and candidate == activehash): hashresults.append (result) cracked = 2 # If it is another algorithm, we search in all the crackers else: hashresults.append (result) cracked = 1 # Had the hash cracked? if cracked: print "\n***** HASH CRACKED!! *****\nThe original string is: %s\n" % (result) # If result was verified, break if cracked == 2: break else: print "... hash not found in %s\n" % (cr.name) # Store the result/s for later... if hashresults: # With some hash types, it is possible to have more than one result, # Repited results are deleted and a single string is constructed. resultlist = [] for r in hashresults: if r not in resultlist: resultlist.append (r) finalresult = "" if len(resultlist) > 1: finalresult = ', '.join (resultlist) else: finalresult = resultlist[0] # Valid results are stored crackedhashes.append ( (activehash, finalresult) ) # Loop is finished. File can need to be closed if hashfile: try: hashestocrack.close () except: pass # Show a resume of all the cracked hashes print "\nThe following hashes were cracked:\n----------------------------------\n" print crackedhashes and "\n".join ("%s -> %s" % (hashvalue, result.strip()) for hashvalue, result in crackedhashes) or "NO HASH WAS CRACKED." print return cracked def searchHash (hashvalue): '''Google the hash value looking for any result which could give some clue... @param hashvalue The hash is been looking for.''' start = 0 finished = False results = [] sys.stdout.write("\nThe hash wasn't found in any database. Maybe Google has any idea...\nLooking for results...") sys.stdout.flush() while not finished: sys.stdout.write('.') sys.stdout.flush() # Build the URL url = "http://www.google.com/search?hl=en&q=%s&filter=0" % (hashvalue) if start: url += "&start=%d" % (start) # Build the Headers with a random User-Agent headers = { "User-Agent" : USER_AGENTS[randint(0, len(USER_AGENTS))-1] } # Send the request response = do_HTTP_request ( url, httpheaders=headers ) # Extract the results ... html = None if response: html = response.read() else: continue resultlist = findall (r'<a href="[^"]*?" class=l', html) # ... saving only new ones new = False for r in resultlist: url_r = r.split('"')[1] if not url_r in results: results.append (url_r) new = True start += len(resultlist) # If there is no a new result, finish if not new: finished = True # Show the results if results: print "\n\nGoogle has some results. Maybe you would like to check them manually:\n" results.sort() for r in results: print " *> %s" % (r) print else: print "\n\nGoogle doesn't have any result. Sorry!\n" ######################################################################################################## ### MAIN CODE ######################################################################################################## def main(): """Main method.""" ################################################### # Syntax check if len (sys.argv) < 4: printSyntax() sys.exit(1) else: try: opts, args = getopt.getopt (sys.argv[2:], "gh:f:") except: printSyntax() sys.exit(1) ################################################### # Load input parameters algorithm = sys.argv[1].lower() hashvalue = None hashfile = None googlesearch = False for opt, arg in opts: if opt == '-h': hashvalue = arg elif opt == '-f': hashfile = arg else: googlesearch = True ################################################### # Configure the Cookie Handler configureCookieProcessor() # Initialize PRNG seed seed() cracked = 0 ################################################### # Crack the hash/es cracked = crackHash (algorithm, hashvalue, hashfile) ################################################### # Look for the hash in Google if it was not cracked if not cracked and googlesearch and not hashfile: searchHash (hashvalue) # App is finished sys.exit() if __name__ == "__main__": main()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- #License: GPL #Copyright(C)Bill Lee #Modified By(C) Finalx #To veiw the weather of a different city, go to www.weather.com.cn to search your city. Then replace "101220501" below with the number in the URL of weather of your city. import os os.system(r"w3m -no-cookie -no-graph http://wap.weather.com.cn/wap/weather/101190101.shtml > /tmp/.weather.com.cn-data") fin = open("/tmp/.weather.com.cn-data") fin.readline() fin.readline() line = fin.readline() location = line.strip() fin.readline() line = fin.readline() issuetime = line[0:16] line = fin.readline() line = fin.readline() date = line[0:12] date = date.strip() line = fin.readline() line = fin.readline() weather = line.strip() line = fin.readline() wind = line.strip() print "${color0}${voffset -20}" + location +"${color} " print "发布时间:${color0}" + issuetime + "${color}" print date + "预报:${color2}" + weather + " " + wind + "${color}"
Python
import sys import os.path # This is a tiny script to help you creating a CSV file from a face # database with a similar hierarchie: # # philipp@mango:~/facerec/data/at$ tree # . # |-- README # |-- s1 # | |-- 1.pgm # | |-- ... # | |-- 10.pgm # |-- s2 # | |-- 1.pgm # | |-- ... # | |-- 10.pgm # ... # |-- s40 # | |-- 1.pgm # | |-- ... # | |-- 10.pgm # if __name__ == "__main__": if len(sys.argv) != 2: print "usage: create_csv <base_path>" sys.exit(1) BASE_PATH=sys.argv[1] CWD=os.getcwd() SEPARATOR=";" label = 0 for dirname, dirnames, filenames in os.walk(BASE_PATH): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) for filename in os.listdir(subject_path): abs_path = "%s/%s" % (subject_path, filename) print "%s/%s%s%d" % (CWD, abs_path, SEPARATOR, label) label = label + 1
Python
#!/usr/bin/env python import os import subprocess import pygtk pygtk.require('2.0') import gtk import time import threading import gobject gobject.threads_init() class LogViewer(threading.Thread): mInFile = "" mTextBuffer = None mOldStrings = "" mStoped = False def close_application(self, widget): gtk.main_quit() self.mStoped = True def __init__(self, pathFile): threading.Thread.__init__(self) self.mInFile = pathFile window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_resizable(True) window.set_title(self.mInFile) window.set_border_width(10) window.set_default_size(800, 600) window.set_position(gtk.WIN_POS_CENTER_ALWAYS) window.connect("destroy", self.close_application) box1 = gtk.VBox(False, 10) window.add(box1) #box2 = gtk.VBox(False, 10) #box2.set_border_width(10) #box1.pack_start(box2, True, True, 0) #box2.show() sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) textview = gtk.TextView() textview.set_editable(False) textview.set_cursor_visible(False) textview.set_wrap_mode(gtk.WRAP_NONE) self.mTextBuffer = textview.get_buffer() sw.add(textview) sw.show() box1.pack_start(sw) #box2.pack_start(sw) textview.show() box1.show() window.show() def refreshFile(self): # Load the file into the text window infile = open(self.mInFile, "r") if infile: string = infile.read() infile.close() if cmp(string, self.mOldStrings) != 0: self.mTextBuffer.set_text(string) self.mOldStrings = string def run(self): while not self.mStoped: gobject.idle_add(self.refreshFile) time.sleep(1) def main(): subprocess.Popen('mkdir -p /tmp/logs', shell=True) # selected = os.environ.get('NAUTILUS_SCRIPT_SELECTED_URIS', '') selected = os.environ.get('NAUTILUS_SCRIPT_SELECTED_FILE_PATHS', '') curdir = os.environ.get('NAUTILUS_SCRIPT_CURRENT_URI', os.curdir) if selected: orig_targets = selected.splitlines() else: orig_targets = [curdir] converted = "" for target in orig_targets: if target.startswith('file:///'): target = target[7:] converted += (target + " ") foutput = "/tmp/logs/nautilus_fg3." + time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time())) f = open(foutput, "w"); # Using pygtk # p = subprocess.Popen("/home/finalx/mybin/myflash.sh --oneshot " + converted, shell=True, stdout=f) # app = LogViewer(foutput) # app.start() # Or using gnome-terminal subprocess.Popen('gnome-terminal -e "/home/finalx/mybin/myflash.sh ' + converted + '"', shell=True, stdout=f) if __name__ == "__main__": main() #gtk.main()
Python
#! /usr/bin/env python import sys import xml.etree.ElementTree as ET def getpath(elem, path): if len(list(elem)): path = path + "." + elem.attrib['name'] for child in elem: getpath(child, path) else: print path + "." + elem.attrib['name'] tree = ET.parse(sys.argv[1]) root = tree.getroot() getpath(root, "")
Python
#!/usr/bin/env python import sys def check_arg(): if (sys.argv.__len__() != 3): print "usage:" + sys.argv[0] + " source_file dest_file" exit() check_arg() origfile = open(sys.argv[1], 'r') reached = False size_count = 0 while (not reached): if (origfile.read(1) == '\n'): reached = True writeto = open(sys.argv[2], 'w') while (True): a_byte = origfile.read(1) if(a_byte == ""): break else: writeto.write(a_byte) print "Done"
Python
#!/usr/bin/env python import sys,os,FetchMail def copyfile(src,dest): fsrc=file(src,"rb") fdest=file(dest,"wb") fdest.write(fsrc.read()) fsrc.close() fdest.close() list=["aPhoneLocate_Windows,py","mail_address","mail_passwd","maproad","14","path.png"] if(len(sys.argv)<=2 or sys.argv[1]=="help"): print("Usage: \n aPhoneLocate_Windows.py mail_address mail_passwd maptype(roadmap or satellite or hybrid default:\"maproad\") zoom( default:14) map_name(default: \"path.jpg\")\n example:\n aPhoneLocate_Windows.py someone@gmail.com someonepasswd satellite 13 mypath.png") exit() for i in range(1,len(sys.argv)): list[i]=sys.argv[i] src = FetchMail.FetchMail(list[1],list[2],list[3],int(list[4])) _localDir = os.path.dirname(__file__) curpath = os.path.normpath(os.path.join(os.getcwd(),_localDir)) dest = os.path.join(curpath,list[5]) print("copying file...") copyfile(src,dest)
Python
#!/usr/bin/env python import imaplib,getpass,time,os,sys,urllib2 def FetchMail(user,passwd,maptyp="roadmap",zoom=14): if(user.endswith("gmail.com")): M=imaplib.IMAP4_SSL("imap.gmail.com") elif(user.endswith("163.com")): M=imaplib.IMAP4_SSL("imap.163.com",993) else: print("email not supported!") try: M.login(user,passwd) except: print("login failed") return "false" count=M.select() if(count==0): return "false" typ,data=M.search(None,'Subject','"location changed"') idset= data[0].split() num=len(data[0].split()) #print data[0] print("search mails and the number is :"+str(num)) location="l,l" #url0="http://maps.google.com/maps/api/staticmap?center=" #url1="&zoom=16&size=512x512&maptype=satellite" marks="&markers=size:mid|color:red|label:S|" path="&path=color:0x0000ff|weight:2" urlend="&sensor=false" mrks="" if(num < 10): rg=-1 else: rg=num-11 for i in range(num-1,rg,-1): print("now processing mail NO:"+str(idset[i])) typ,data=M.fetch(idset[i],'RFC822') fulltext=data[0][1].split("\r\n") #print len(fulltext) for i in range(0,len(fulltext),1): text=fulltext[i] #print text if(text.startswith("longitude,latitude: ")): strr=text[20:] loc=strr.split(",") location=loc[1]+","+loc[0] print("latitude,longitude: "+location) path+="|" path+=location #url=url0 #url+=location #url+=url1+marks #url+=location #url+=urlend mrks+=marks+location #print url #pic=urllib2.urlopen(url).read() #fpath="/home/niuniu/program/" #fpath+=str(i) #f=file(fpath,"wb") #f.write(pic) #f.close() #time.sleep(2) break; url="http://maps.google.com/maps/api/staticmap?&zoom="+str(zoom)+"&size=640x640&maptype="+maptyp+path+mrks+urlend print("\ngoogle map api url generated===============>") print(url) print("") print("now invoking the google map api to get map\n") pic=urllib2.urlopen(url).read() _localDir=os.path.dirname(__file__) curpath=os.path.normpath(os.path.join(os.getcwd(),_localDir)) fpath=os.path.normpath(os.path.join(os.getcwd(),_localDir)) fpath=os.path.join(fpath,"path"+str(idset[num-1])+maptyp+str(zoom)+".png") print("get map and map path is :"+fpath) f=file(fpath,"wb") f.write(pic) f.close() M.close() M.logout() print("done.") return fpath
Python
#!/usr/bin/env python import os,sys,FetchMail,time,threading try: import pygtk pygtk.require("2.0") except: pass try: import gtk import gtk.glade except: print("This program need to be run in graphical environment!") sys.exit(1) result="false" class FMthread(threading.Thread): def __init__(self,user,passwd,maptyp,zoom): threading.Thread.__init__(self) self.user=user self.passwd=passwd self.maptyp=maptyp self.zoom=zoom def run(self): global result result=FetchMail.FetchMail(self.user,self.passwd,self.maptyp,self.zoom) class HelloWorldGTK: """This is an Hello World GTK application""" def __init__(self): #Set the Glade file _localDir=os.path.dirname(__file__) curpath=os.path.normpath(os.path.join(os.getcwd(),_localDir)) self.gladefile=os.path.join(curpath, "frame.glade") print(self.gladefile) self.wTree = gtk.glade.XML(self.gladefile) self.rat="satellite" #Get the Main Window, and connect the "destroy" event self.dia = self.wTree.get_widget("window2") self.pro = self.wTree.get_widget("window3") self.window = self.wTree.get_widget("window1") self.image=self.wTree.get_widget("image1") self.image.set_from_file(os.path.join(curpath,"path")) self.label=self.wTree.get_widget("label7") self.label.set_label("") self.window.show() if (self.window): self.window.connect("destroy", gtk.main_quit) dic = {"on_button1_clicked":self.rat4, "on_button2_clicked" : self.btnHelloWorld_clicked,"on_radiobutton1_clicked":self.rat1,"on_radiobutton2_clicked":self.rat2,"on_radiobutton3_clicked":self.rat3} self.wTree.signal_autoconnect(dic) def rat1(self,widget): self.rat="roadmap" def rat2(self,widget): self.rat="satellite" def rat3(self,widget): self.rat="hybrid" def rat4(self,widget): self.dia.hide() def btnHelloWorld_clicked(self, widget): user=self.wTree.get_widget("entry1").get_text() passwd=self.wTree.get_widget("entry2").get_text() zoom = self.wTree.get_widget("spinbutton1").get_value() #self.pro.show(); print("email adress : "+user) print ("zoom : "+str(int(zoom))) print ("map type : "+self.rat+"\n") result=FetchMail.FetchMail(user,passwd,self.rat,int(zoom)) #thread = FMthread(user,passwd,self.rat,int(zoom)) #thread.start() #self.label.set_label("processing...") #thread.join() if(result=="false"): self.dia.show() else: self.image.set_from_file(result) if __name__=="__main__": hwg=HelloWorldGTK() gtk.main()
Python
#!/usr/bin/env python import sys,os,FetchMail def copyfile(src,dest): fsrc=file(src,"rb") fdest=file(dest,"wb") fdest.write(fsrc.read()) fsrc.close() fdest.close() list=["aPhoneLocate_Windows,py","mail_address","mail_passwd","maproad","14","path.png"] if(len(sys.argv)<=2 or sys.argv[1]=="help"): print("Usage: \n aPhoneLocate_Windows.py mail_address mail_passwd maptype(roadmap or satellite or hybrid default:\"maproad\") zoom( default:14) map_name(default: \"path.jpg\")\n example:\n aPhoneLocate_Windows.py someone@gmail.com someonepasswd satellite 13 mypath.png") exit() for i in range(1,len(sys.argv)): list[i]=sys.argv[i] src = FetchMail.FetchMail(list[1],list[2],list[3],int(list[4])) _localDir = os.path.dirname(__file__) curpath = os.path.normpath(os.path.join(os.getcwd(),_localDir)) dest = os.path.join(curpath,list[5]) print("copying file...") copyfile(src,dest)
Python
#!/usr/bin/env python import imaplib,getpass,time,os,sys,urllib2 def FetchMail(user,passwd,maptyp="roadmap",zoom=14): if(user.endswith("gmail.com")): M=imaplib.IMAP4_SSL("imap.gmail.com") elif(user.endswith("163.com")): M=imaplib.IMAP4_SSL("imap.163.com",993) else: print("email not supported!") try: M.login(user,passwd) except: print("login failed") return "false" count=M.select() if(count==0): return "false" typ,data=M.search(None,'Subject','"location changed"') idset= data[0].split() num=len(data[0].split()) #print data[0] print("search mails and the number is :"+str(num)) location="l,l" #url0="http://maps.google.com/maps/api/staticmap?center=" #url1="&zoom=16&size=512x512&maptype=satellite" marks="&markers=size:mid|color:red|label:S|" path="&path=color:0x0000ff|weight:2" urlend="&sensor=false" mrks="" if(num < 10): rg=-1 else: rg=num-11 for i in range(num-1,rg,-1): print("now processing mail NO:"+str(idset[i])) typ,data=M.fetch(idset[i],'RFC822') fulltext=data[0][1].split("\r\n") #print len(fulltext) for i in range(0,len(fulltext),1): text=fulltext[i] #print text if(text.startswith("longitude,latitude: ")): strr=text[20:] loc=strr.split(",") location=loc[1]+","+loc[0] print("latitude,longitude: "+location) path+="|" path+=location #url=url0 #url+=location #url+=url1+marks #url+=location #url+=urlend mrks+=marks+location #print url #pic=urllib2.urlopen(url).read() #fpath="/home/niuniu/program/" #fpath+=str(i) #f=file(fpath,"wb") #f.write(pic) #f.close() #time.sleep(2) break; url="http://maps.google.com/maps/api/staticmap?&zoom="+str(zoom)+"&size=640x640&maptype="+maptyp+path+mrks+urlend print("\ngoogle map api url generated===============>") print(url) print("") print("now invoking the google map api to get map\n") pic=urllib2.urlopen(url).read() _localDir=os.path.dirname(__file__) curpath=os.path.normpath(os.path.join(os.getcwd(),_localDir)) fpath=os.path.normpath(os.path.join(os.getcwd(),_localDir)) fpath=os.path.join(fpath,"path"+str(idset[num-1])+maptyp+str(zoom)+".png") print("get map and map path is :"+fpath) f=file(fpath,"wb") f.write(pic) f.close() M.close() M.logout() print("done.") return fpath
Python
#!/usr/bin/env python import os,sys,FetchMail,time,threading try: import pygtk pygtk.require("2.0") except: pass try: import gtk import gtk.glade except: print("This program need to be run in graphical environment!") sys.exit(1) result="false" class FMthread(threading.Thread): def __init__(self,user,passwd,maptyp,zoom): threading.Thread.__init__(self) self.user=user self.passwd=passwd self.maptyp=maptyp self.zoom=zoom def run(self): global result result=FetchMail.FetchMail(self.user,self.passwd,self.maptyp,self.zoom) class HelloWorldGTK: """This is an Hello World GTK application""" def __init__(self): #Set the Glade file _localDir=os.path.dirname(__file__) curpath=os.path.normpath(os.path.join(os.getcwd(),_localDir)) self.gladefile=os.path.join(curpath, "frame.glade") print(self.gladefile) self.wTree = gtk.glade.XML(self.gladefile) self.rat="satellite" #Get the Main Window, and connect the "destroy" event self.dia = self.wTree.get_widget("window2") self.pro = self.wTree.get_widget("window3") self.window = self.wTree.get_widget("window1") self.image=self.wTree.get_widget("image1") self.image.set_from_file(os.path.join(curpath,"path")) self.label=self.wTree.get_widget("label7") self.label.set_label("") self.window.show() if (self.window): self.window.connect("destroy", gtk.main_quit) dic = {"on_button1_clicked":self.rat4, "on_button2_clicked" : self.btnHelloWorld_clicked,"on_radiobutton1_clicked":self.rat1,"on_radiobutton2_clicked":self.rat2,"on_radiobutton3_clicked":self.rat3} self.wTree.signal_autoconnect(dic) def rat1(self,widget): self.rat="roadmap" def rat2(self,widget): self.rat="satellite" def rat3(self,widget): self.rat="hybrid" def rat4(self,widget): self.dia.hide() def btnHelloWorld_clicked(self, widget): user=self.wTree.get_widget("entry1").get_text() passwd=self.wTree.get_widget("entry2").get_text() zoom = self.wTree.get_widget("spinbutton1").get_value() #self.pro.show(); print("email adress : "+user) print ("zoom : "+str(int(zoom))) print ("map type : "+self.rat+"\n") result=FetchMail.FetchMail(user,passwd,self.rat,int(zoom)) #thread = FMthread(user,passwd,self.rat,int(zoom)) #thread.start() #self.label.set_label("processing...") #thread.join() if(result=="false"): self.dia.show() else: self.image.set_from_file(result) if __name__=="__main__": hwg=HelloWorldGTK() gtk.main()
Python
import os import re import sys from System.Diagnostics import Process def Main(): asmFileName, vcsDirectory = HandleArguments() revNr = QueryRevNr(vcsDirectory) underTeamCity, buildNr = DetectTeamCityAndBuildNr() asvFileName = InsertVerInfix(asmFileName) PatchAssemblyInfo(asmFileName, asvFileName, revNr, buildNr, lambda x: PrintVersionNr(underTeamCity,x)) exit(0) def HandleArguments(): if len(sys.argv) != 3: print "Usage: " print "%s assembly-info svn-dir" % sys.argv[0] exit(-1) ### Check arguments asmFileName = sys.argv[1] vcsDirectory = sys.argv[2] if not os.access(asmFileName, os.F_OK): print "Assembly file: \"%s\" doesn't exist." % asmFileName exit(-2) if not os.access(asmFileName, os.R_OK): print "Could not access assembly file: \"%s\"" % asmFileName exit(-2) #if not os.access(vcsDirectory, os.F_OK): # print "The \"%s\" seems not a directory." % vcsDirectory # exit(-3) return (asmFileName, vcsDirectory) def QueryRevNr(vcsDirectory): ### Query the revision number proc = Process() proc.StartInfo.UseShellExecute = False proc.StartInfo.RedirectStandardInput = False proc.StartInfo.RedirectStandardOutput = True proc.StartInfo.RedirectStandardError = False proc.StartInfo.FileName = "svn.exe" proc.StartInfo.Arguments = "info " + vcsDirectory proc.Start() proc.WaitForExit() vcsOut = proc.StandardOutput.ReadToEnd() revLinePattern = re.compile(r"^Last.*Rev:\s*(\d+)\s*$", re.I|re.M) revMatched = revLinePattern.search(vcsOut) if revMatched: revNr = revMatched.group(1) else: revNr = 0 return revNr def DetectTeamCityAndBuildNr(): underTeamCity = os.environ.get('TEAMCITY_VERSION',"") != "" if underTeamCity: buildNr = os.environ.get('BUILD_NUMBER','0') else: buildNr = '0' return (underTeamCity, buildNr) def InsertVerInfix(asmFileName): asvFileName = re.compile(r"^(.+)\.cs$",re.I).sub(r"\1Ver.cs",asmFileName,1) return asvFileName def PrintVersionNr(underTeamCity, fullVersion): print fullVersion if underTeamCity: print "##teamcity[buildNumber '%s']" % fullVersion def PatchAssemblyInfo(asmFileName, asvFileName, revNr, buildNr, handler): ### Make the assembly info version_line_pattern = re.compile(r"\[assembly:.*(Assembly.*Version)\D*(\d+.\d+.)(\d+).(\d+).*") etalon_f = open(asmFileName, "r", 1) patched_f = open(asvFileName, "w") for line in etalon_f: matched = version_line_pattern.match(line) if matched: fullVersion = matched.group(2) + revNr + "." + buildNr if matched.group(1) == "AssemblyVersion": handler(fullVersion) patched_line = line[:matched.start(2)] + fullVersion + line[matched.end(4):] patched_f.write(patched_line) else: patched_f.write(line) patched_f.close() etalon_f.close() Main()
Python
import re import sys ccf = open("CC_base.cs", "r", 1) cc0 = open("CC0_forward.cs", "w") cc1 = open("CC1_forward.cs", "w") ############################################################################# def transform_headline (headline): pattern = re.compile(r"int\s+firstIndex\,?\s*") changed_headline = pattern.sub("", headline) return changed_headline def generate_forward (mtitle, margs): pattern = re.compile(r" \w+(\s*<[\w ,]+>)?\s*\(") matched = pattern.search(mtitle) if matched: print "\t\t" + mtitle[matched.start():matched.end()-1] + " ("+", ".join(margs)+")" f_exp = " return CC." \ + mtitle[matched.start()+1:matched.end()] \ + "%%%, " + ", ".join(margs) \ + "); \n" else: raise Exception, "Failed to analyze method line: " + mtitle return f_exp def out_lines (lines): lines0 = lines.replace("%%%", "0") lines1 = lines.replace("%%%", "1") cc0.write(lines0) cc1.write(lines1) ############################################################################# state = -1 depth = 0 mhead = "" margs = [] mtitle = "" for line in ccf: line1 = line.strip() if state == -1: # before class if line1.find("partial") > 0: state = 0 out_lines (line.replace("CC","CC%%%")) else: out_lines (line) elif state == 0: # in class if line1.startswith("#"): out_lines (line) elif line1.startswith("///"): state = 1 margs = [] mhead = '\n' + line elif line1.startswith("{"): out_lines (line) elif line1.startswith("}"): state = 9 out_lines (line) elif line1 == "": out_lines ("") else: state = 8 depth = 0 elif state == 1: # in method-head comments if line1.startswith("///") and line1.find("firstIndex") > 0: xyz = 0 # really - do nothing elif line1.startswith("///") and line1.find("<param name") > 0: q1 = line1.find('"') q2 = line1.find('"', q1+1) arg = line1[q1+1:q2] margs += [arg] elif line1.startswith("/") or line1 == "": mhead += line elif line1.find("public") >= 0 and line1.find("static") >= 0: state = 2 depth = 0 mhead += transform_headline(line) mtitle = line1 elif state == 2: # inside the method if line1.startswith("{"): if depth == 0: mhead += line depth += 1 if depth == 1: mhead += generate_forward(mtitle, margs) elif line1.startswith("}"): depth -= 1 if depth == 0: mhead += line mhead += '\n' out_lines (mhead) state = 0 else: if depth == 0: mhead += line elif state == 8: # private method if line1.startswith("{"): depth += 1 elif line1.startswith("}"): depth -= 1 if depth == 0: state = 0 elif line1.startswith("///"): state = 1 mhead = '\n' + line elif state == 9: # behind the class out_lines (line) ccf.close() cc0.close() cc1.close() exit(0)
Python
import os import re import sys from System.Diagnostics import Process def Main(): asmFileName, vcsDirectory = HandleArguments() revNr = QueryRevNr(vcsDirectory) underTeamCity, buildNr = DetectTeamCityAndBuildNr() asvFileName = InsertVerInfix(asmFileName) PatchAssemblyInfo(asmFileName, asvFileName, revNr, buildNr, lambda x: PrintVersionNr(underTeamCity,x)) exit(0) def HandleArguments(): if len(sys.argv) != 3: print "Usage: " print "%s assembly-info svn-dir" % sys.argv[0] exit(-1) ### Check arguments asmFileName = sys.argv[1] vcsDirectory = sys.argv[2] if not os.access(asmFileName, os.F_OK): print "Assembly file: \"%s\" doesn't exist." % asmFileName exit(-2) if not os.access(asmFileName, os.R_OK): print "Could not access assembly file: \"%s\"" % asmFileName exit(-2) #if not os.access(vcsDirectory, os.F_OK): # print "The \"%s\" seems not a directory." % vcsDirectory # exit(-3) return (asmFileName, vcsDirectory) def QueryRevNr(vcsDirectory): ### Query the revision number proc = Process() proc.StartInfo.UseShellExecute = False proc.StartInfo.RedirectStandardInput = False proc.StartInfo.RedirectStandardOutput = True proc.StartInfo.RedirectStandardError = False proc.StartInfo.FileName = "svn.exe" proc.StartInfo.Arguments = "info " + vcsDirectory proc.Start() proc.WaitForExit() vcsOut = proc.StandardOutput.ReadToEnd() revLinePattern = re.compile(r"^Last.*Rev:\s*(\d+)\s*$", re.I|re.M) revMatched = revLinePattern.search(vcsOut) if revMatched: revNr = revMatched.group(1) else: revNr = 0 return revNr def DetectTeamCityAndBuildNr(): underTeamCity = os.environ.get('TEAMCITY_VERSION',"") != "" if underTeamCity: buildNr = os.environ.get('BUILD_NUMBER','0') else: buildNr = '0' return (underTeamCity, buildNr) def InsertVerInfix(asmFileName): asvFileName = re.compile(r"^(.+)\.cs$",re.I).sub(r"\1Ver.cs",asmFileName,1) return asvFileName def PrintVersionNr(underTeamCity, fullVersion): print fullVersion if underTeamCity: print "##teamcity[buildNumber '%s']" % fullVersion def PatchAssemblyInfo(asmFileName, asvFileName, revNr, buildNr, handler): ### Make the assembly info version_line_pattern = re.compile(r"\[assembly:.*(Assembly.*Version)\D*(\d+.\d+.)(\d+).(\d+).*") etalon_f = open(asmFileName, "r", 1) patched_f = open(asvFileName, "w") for line in etalon_f: matched = version_line_pattern.match(line) if matched: fullVersion = matched.group(2) + revNr + "." + buildNr if matched.group(1) == "AssemblyVersion": handler(fullVersion) patched_line = line[:matched.start(2)] + fullVersion + line[matched.end(4):] patched_f.write(patched_line) else: patched_f.write(line) patched_f.close() etalon_f.close() Main()
Python
import re import sys ccf = open("CC_base.cs", "r", 1) cc0 = open("CC0_forward.cs", "w") cc1 = open("CC1_forward.cs", "w") ############################################################################# def transform_headline (headline): pattern = re.compile(r"int\s+firstIndex\,?\s*") changed_headline = pattern.sub("", headline) return changed_headline def generate_forward (mtitle, margs): pattern = re.compile(r" \w+(\s*<[\w ,]+>)?\s*\(") matched = pattern.search(mtitle) if matched: print "\t\t" + mtitle[matched.start():matched.end()-1] + " ("+", ".join(margs)+")" f_exp = " return CC." \ + mtitle[matched.start()+1:matched.end()] \ + "%%%, " + ", ".join(margs) \ + "); \n" else: raise Exception, "Failed to analyze method line: " + mtitle return f_exp def out_lines (lines): lines0 = lines.replace("%%%", "0") lines1 = lines.replace("%%%", "1") cc0.write(lines0) cc1.write(lines1) ############################################################################# state = -1 depth = 0 mhead = "" margs = [] mtitle = "" for line in ccf: line1 = line.strip() if state == -1: # before class if line1.find("partial") > 0: state = 0 out_lines (line.replace("CC","CC%%%")) else: out_lines (line) elif state == 0: # in class if line1.startswith("#"): out_lines (line) elif line1.startswith("///"): state = 1 margs = [] mhead = '\n' + line elif line1.startswith("{"): out_lines (line) elif line1.startswith("}"): state = 9 out_lines (line) elif line1 == "": out_lines ("") else: state = 8 depth = 0 elif state == 1: # in method-head comments if line1.startswith("///") and line1.find("firstIndex") > 0: xyz = 0 # really - do nothing elif line1.startswith("///") and line1.find("<param name") > 0: q1 = line1.find('"') q2 = line1.find('"', q1+1) arg = line1[q1+1:q2] margs += [arg] elif line1.startswith("/") or line1 == "": mhead += line elif line1.find("public") >= 0 and line1.find("static") >= 0: state = 2 depth = 0 mhead += transform_headline(line) mtitle = line1 elif state == 2: # inside the method if line1.startswith("{"): if depth == 0: mhead += line depth += 1 if depth == 1: mhead += generate_forward(mtitle, margs) elif line1.startswith("}"): depth -= 1 if depth == 0: mhead += line mhead += '\n' out_lines (mhead) state = 0 else: if depth == 0: mhead += line elif state == 8: # private method if line1.startswith("{"): depth += 1 elif line1.startswith("}"): depth -= 1 if depth == 0: state = 0 elif line1.startswith("///"): state = 1 mhead = '\n' + line elif state == 9: # behind the class out_lines (line) ccf.close() cc0.close() cc1.close() exit(0)
Python
import os import re os.system("svn info .. > svn-info.txt") revision = "" revision_pattern = re.compile(r"Revision:\s*(\d+)\D*") revision_found = False version_line_pattern = re.compile(r".*Assembly.*Version\D*\d+.\d+.(\d+).(\d+).*") info_f = open("svn-info.txt", "r", 1) for line in info_f: matched = revision_pattern.match(line) if matched: revision = matched.group(1) revision_found = True print revision break info_f.close() if not revision_found: print "Could not obtain SVN revison info." exit(-1) etalon_f = open("properties/AssemblyInfo.cs", "r", 1) patched_f = open("properties/AssemblyInfoVer.cs", "w") for line in etalon_f: matched = version_line_pattern.match(line) if matched: patched_line = line[:matched.start(1)] + revision + line[matched.end(1):] patched_f.write(patched_line) else: patched_f.write(line) patched_f.close() etalon_f.close() exit(0)
Python
import os import re import sys from System.Diagnostics import Process def Main(): asmFileName, vcsDirectory = HandleArguments() revNr = QueryRevNr(vcsDirectory) underTeamCity, buildNr = DetectTeamCityAndBuildNr() asvFileName = InsertVerInfix(asmFileName) PatchAssemblyInfo(asmFileName, asvFileName, revNr, buildNr, lambda x: PrintVersionNr(underTeamCity,x)) exit(0) def HandleArguments(): if len(sys.argv) != 3: print "Usage: " print "%s assembly-info svn-dir" % sys.argv[0] exit(-1) ### Check arguments asmFileName = sys.argv[1] vcsDirectory = sys.argv[2] if not os.access(asmFileName, os.F_OK): print "Assembly file: \"%s\" doesn't exist." % asmFileName exit(-2) if not os.access(asmFileName, os.R_OK): print "Could not access assembly file: \"%s\"" % asmFileName exit(-2) #if not os.access(vcsDirectory, os.F_OK): # print "The \"%s\" seems not a directory." % vcsDirectory # exit(-3) return (asmFileName, vcsDirectory) def QueryRevNr(vcsDirectory): ### Query the revision number proc = Process() proc.StartInfo.UseShellExecute = False proc.StartInfo.RedirectStandardInput = False proc.StartInfo.RedirectStandardOutput = True proc.StartInfo.RedirectStandardError = False proc.StartInfo.FileName = "svn.exe" proc.StartInfo.Arguments = "info " + vcsDirectory proc.Start() proc.WaitForExit() vcsOut = proc.StandardOutput.ReadToEnd() revLinePattern = re.compile(r"^Last.*Rev:\s*(\d+)\s*$", re.I|re.M) revMatched = revLinePattern.search(vcsOut) if revMatched: revNr = revMatched.group(1) else: revNr = 0 return revNr def DetectTeamCityAndBuildNr(): underTeamCity = os.environ.get('TEAMCITY_VERSION',"") != "" if underTeamCity: buildNr = os.environ.get('BUILD_NUMBER','0') else: buildNr = '0' return (underTeamCity, buildNr) def InsertVerInfix(asmFileName): asvFileName = re.compile(r"^(.+)\.cs$",re.I).sub(r"\1Ver.cs",asmFileName,1) return asvFileName def PrintVersionNr(underTeamCity, fullVersion): print fullVersion if underTeamCity: print "##teamcity[buildNumber '%s']" % fullVersion def PatchAssemblyInfo(asmFileName, asvFileName, revNr, buildNr, handler): ### Make the assembly info version_line_pattern = re.compile(r"\[assembly:.*(Assembly.*Version)\D*(\d+.\d+.)(\d+).(\d+).*") etalon_f = open(asmFileName, "r", 1) patched_f = open(asvFileName, "w") for line in etalon_f: matched = version_line_pattern.match(line) if matched: fullVersion = matched.group(2) + revNr + "." + buildNr if matched.group(1) == "AssemblyVersion": handler(fullVersion) patched_line = line[:matched.start(2)] + fullVersion + line[matched.end(4):] patched_f.write(patched_line) else: patched_f.write(line) patched_f.close() etalon_f.close() Main()
Python
import re import sys ccf = open("CC_base.cs", "r", 1) cc0 = open("CC0_forward.cs", "w") cc1 = open("CC1_forward.cs", "w") ############################################################################# def transform_headline (headline): pattern = re.compile(r"int\s+firstIndex\,?\s*") changed_headline = pattern.sub("", headline) return changed_headline def generate_forward (mtitle, margs): pattern = re.compile(r" \w+(\s*<[\w ,]+>)?\s*\(") matched = pattern.search(mtitle) if matched: print "\t\t" + mtitle[matched.start():matched.end()-1] + " ("+", ".join(margs)+")" f_exp = " return CC." \ + mtitle[matched.start()+1:matched.end()] \ + "%%%, " + ", ".join(margs) \ + "); \n" else: raise Exception, "Failed to analyze method line: " + mtitle return f_exp def out_lines (lines): lines0 = lines.replace("%%%", "0") lines1 = lines.replace("%%%", "1") cc0.write(lines0) cc1.write(lines1) ############################################################################# state = -1 depth = 0 mhead = "" margs = [] mtitle = "" for line in ccf: line1 = line.strip() if state == -1: # before class if line1.find("partial") > 0: state = 0 out_lines (line.replace("CC","CC%%%")) else: out_lines (line) elif state == 0: # in class if line1.startswith("#"): out_lines (line) elif line1.startswith("///"): state = 1 margs = [] mhead = '\n' + line elif line1.startswith("{"): out_lines (line) elif line1.startswith("}"): state = 9 out_lines (line) elif line1 == "": out_lines ("") else: state = 8 depth = 0 elif state == 1: # in method-head comments if line1.startswith("///") and line1.find("firstIndex") > 0: xyz = 0 # really - do nothing elif line1.startswith("///") and line1.find("<param name") > 0: q1 = line1.find('"') q2 = line1.find('"', q1+1) arg = line1[q1+1:q2] margs += [arg] elif line1.startswith("/") or line1 == "": mhead += line elif line1.find("public") >= 0 and line1.find("static") >= 0: state = 2 depth = 0 mhead += transform_headline(line) mtitle = line1 elif state == 2: # inside the method if line1.startswith("{"): if depth == 0: mhead += line depth += 1 if depth == 1: mhead += generate_forward(mtitle, margs) elif line1.startswith("}"): depth -= 1 if depth == 0: mhead += line mhead += '\n' out_lines (mhead) state = 0 else: if depth == 0: mhead += line elif state == 8: # private method if line1.startswith("{"): depth += 1 elif line1.startswith("}"): depth -= 1 if depth == 0: state = 0 elif line1.startswith("///"): state = 1 mhead = '\n' + line elif state == 9: # behind the class out_lines (line) ccf.close() cc0.close() cc1.close() exit(0)
Python
import os import re import sys from System.Diagnostics import Process def Main(): versionTemplate, fileNames = HandleArguments() revNr = QueryRevNr(".") underTeamCity, buildNr = DetectTeamCityAndBuildNr() versionStr = HandleVersion(versionTemplate, revNr, buildNr, underTeamCity) for fileName in fileNames: PatchKnownFile(fileName, versionStr) def HandleArguments(): if len(sys.argv) < 3: print "Usage: " print "%s version-template assembly-info-1 assembly-info-2 ..." % sys.argv[0] exit(-1) ### Check arguments versionTemplate = sys.argv[1] names = sys.argv[2:] for name in names: if not os.access(name, os.F_OK): print "File: \"%s\" doesn't exist." % name exit(-2) if not os.access(name, os.R_OK): print "Could not access file: \"%s\"" % name exit(-2) return (versionTemplate, names) def HandleVersion(template, rev, build, underTC): version = template version = re.sub(r'R#', rev.ToString(), version) version = re.sub(r'B#', build.ToString(), version) print "Version=%s" % version if underTC: print "##teamcity[buildNumber '%s']" % version return version def QueryRevNr(vcsDirectory): ### Query the revision number proc = Process() proc.StartInfo.UseShellExecute = False proc.StartInfo.RedirectStandardInput = False proc.StartInfo.RedirectStandardOutput = True proc.StartInfo.RedirectStandardError = False proc.StartInfo.FileName = "svn.exe" proc.StartInfo.Arguments = "info " + vcsDirectory proc.Start() proc.WaitForExit() vcsOut = proc.StandardOutput.ReadToEnd() revLinePattern = re.compile(r"^Last.*Rev:\s*(\d+)\s*$", re.I|re.M) revMatched = revLinePattern.search(vcsOut) if revMatched: revNr = revMatched.group(1) else: revNr = 0 return revNr def DetectTeamCityAndBuildNr(): underTeamCity = os.environ.get('TEAMCITY_VERSION',"") != "" if underTeamCity: buildNr = os.environ.get('BUILD_NUMBER','0') else: buildNr = '0' return (underTeamCity, buildNr) def PatchKnownFile(fileName, version): origCopyFileName = fileName + ".orig" RenameFile(fileName, origCopyFileName) fnamePattern = re.compile(r"^(\S+)\.([^\.\s]+)$") m = fnamePattern.match(fileName) ok = False if m: suffix = m.group(2) newFileName = m.group(1) + "Ver." + suffix if suffix == 'cs': verPattern = r"\[assembly:.*(Assembly.*Version)\D*(\d+.\d+.\d+.\d+)\D*.*" PatchTextFile(origCopyFileName, fileName, verPattern, 2, version) ok = True if suffix == 'nuspec': verPattern = r".*<version>\D*(\d+.\d+.\d+.\d+)\D*</version>.*" PatchTextFile(origCopyFileName, fileName, verPattern, 1, version) ok = True if not ok: print "\tunknown file type: %s" % fileName def RenameFile(src, dst): if os.access(dst, os.F_OK): os.remove(dst) os.rename(src, dst) if not os.access(dst, os.F_OK): print "Could not rename %s to %s" % (src,dst) exit(-4) def PatchTextFile(srcFileName, dstFileName, pattern, grp, subst): compiledPattern = re.compile(pattern) etalon_f = open(srcFileName, "r", 1) patched_f = open(dstFileName, "w") changes = 0 for line in etalon_f: matched = compiledPattern.match(line) if matched: patched_line = line[:matched.start(grp)] + subst + line[matched.end(grp):] patched_f.write(patched_line) changes += 1 else: patched_f.write(line) patched_f.close() etalon_f.close() changesStr = ("%d changes" % changes) if changes >= 2 else "1 change" if changes == 1 else "no changes" print "\t%s patched (%s)" % (dstFileName, changesStr) print "==== Patch version: start ====" Main() print "==== Patch version: finished ===="
Python
import re ccf = open("CC_base.cs", "r", 1) cc0 = open("CC0_forward.cs", "w") cc1 = open("CC1_forward.cs", "w") ############################################################################# def transform_headline (headline): pattern = re.compile(r"int\s+firstIndex\,?\s*") changed_headline = pattern.sub("", headline) return changed_headline def generate_forward (mtitle, margs): pattern = re.compile(r" \w+(\s*<[\w ,]+>)?\s*\(") matched = pattern.search(mtitle) if matched: print "\t\t" + mtitle[matched.start():matched.end()-1] + " ("+", ".join(margs)+")" f_exp = " return CC." \ + mtitle[matched.start()+1:matched.end()] \ + "%%%, " + ", ".join(margs) \ + "); \n" else: raise Exception, "Failed to analyze method line: " + mtitle return f_exp def out_lines (lines): lines0 = lines.replace("%%%", "0") lines1 = lines.replace("%%%", "1") cc0.write(lines0) cc1.write(lines1) ############################################################################# print "==== CCx forwards: starting generate ====" state = -1 depth = 0 mhead = "" margs = [] mtitle = "" for line in ccf: line1 = line.strip() if state == -1: # before class if line1.find("partial") > 0: state = 0 out_lines (line.replace("CC","CC%%%")) else: out_lines (line) elif state == 0: # in class if line1.startswith("#"): out_lines (line) elif line1.startswith("///"): state = 1 margs = [] mhead = '\n' + line elif line1.startswith("{"): out_lines (line) elif line1.startswith("}"): state = 9 out_lines (line) elif line1 == "": out_lines ("") else: state = 8 depth = 0 elif state == 1: # in method-head comments if line1.startswith("///") and line1.find("firstIndex") > 0: xyz = 0 # really - do nothing elif line1.startswith("///") and line1.find("<param name") > 0: q1 = line1.find('"') q2 = line1.find('"', q1+1) arg = line1[q1+1:q2] margs += [arg] elif line1.startswith("["): mhead += line elif line1.startswith("/") or line1 == "": mhead += line elif line1.find("public") >= 0 and line1.find("static") >= 0: state = 2 depth = 0 mhead += transform_headline(line) mtitle = line1 elif state == 2: # inside the method if line1.startswith("{"): if depth == 0: mhead += line depth += 1 if depth == 1: mhead += generate_forward(mtitle, margs) elif line1.startswith("}"): depth -= 1 if depth == 0: mhead += line mhead += '\n' out_lines (mhead) state = 0 else: if depth == 0: mhead += line elif state == 8: # private method if line1.startswith("{"): depth += 1 elif line1.startswith("}"): depth -= 1 if depth == 0: state = 0 elif line1.startswith("///"): state = 1 mhead = '\n' + line elif state == 9: # behind the class out_lines (line) ccf.close() cc0.close() cc1.close() print "==== CCx forwards: generating finished ====" exit(0)
Python
#!/usr/bin/env python """ EVENNIA SERVER STARTUP SCRIPT This is the start point for running Evennia. Sets the appropriate environmental variables and launches the server and portal through the runner. Run without arguments to get a menu. Run the script with the -h flag to see usage information. """ import os import sys, signal from optparse import OptionParser from subprocess import Popen, call # Set the Python path up so we can get to settings.py from here. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) os.environ['DJANGO_SETTINGS_MODULE'] = 'game.settings' # i18n from django.utils.translation import ugettext as _ SIG = signal.SIGINT HELPENTRY = \ _(""" (version %s) This program launches Evennia with various options. You can access all this functionality directly from the command line; for example option five (restart server) would be "evennia.py restart server". Use "evennia.py -h" for command line options. Evennia consists of two separate programs that both must be running for the game to work as it should: Portal - the connection to the outside world (via telnet, web, ssh etc). This is normally running as a daemon and don't need to be reloaded unless you are debugging a new connection protocol. As long as this is running, players won't loose their connection to your game. Only one instance of Portal will be started, more will be ignored. Server - the game server itself. This will often need to be reloaded as you develop your game. The Portal will auto-connect to the Server whenever the Server activates. We will also make sure to automatically restart this whenever it is shut down (from here or from inside the game or via task manager etc). Only one instance of Server will be started, more will be ignored. In a production environment you will want to run with the default option (1), which runs as much as possible as a background process. When developing your game it is however convenient to directly see tracebacks on standard output, so starting with options 2-4 may be a good bet. As you make changes to your code, reload the server (option 5) to make it available to users. Reload and stop is not well supported in Windows. If you have issues, log into the game to stop or restart the server instead. """) MENU = \ _(""" +---------------------------------------------------------------------------+ | | | Welcome to the Evennia launcher! | | | | Pick an option below. Use 'h' to get help. | | | +--- Starting (will not restart already running processes) -----------------+ | | | 1) (default): Start Server and Portal. Portal starts in daemon mode.| | All output is to logfiles. | | 2) (game debug): Start Server and Portal. Portal starts in daemon mode.| | Server outputs to stdout instead of logfile. | | 3) (portal debug): Start Server and Portal. Portal starts in non-daemon | | mode (can be reloaded) and logs to stdout. | | 4) (full debug): Start Server and Portal. Portal starts in non-daemon | | mode (can be reloaded). Both log to stdout. | | | +--- Restarting (must first be started) ------------------------------------+ | | | 5) Reload the Server | | 6) Reload the Portal (only works in non-daemon mode. If running | | in daemon mode, Portal needs to be restarted manually (option 1-4)) | | | +--- Stopping (must first be started) --------------------------------------+ | | | 7) Stopping both Portal and Server. Server will not restart. | | 8) Stopping only Server. Server will not restart. | | 9) Stopping only Portal. | | | +---------------------------------------------------------------------------+ | h) Help | | q) Quit | +---------------------------------------------------------------------------+ """) # # System Configuration and setup # SERVER_PIDFILE = "server.pid" PORTAL_PIDFILE = "portal.pid" SERVER_RESTART = "server.restart" PORTAL_RESTART = "portal.restart" if not os.path.exists('settings.py'): # make sure we have a settings.py file. print _(" No settings.py file found. launching manage.py ...") import game.manage print _(""" ... A new settings file was created. Edit this file to configure Evennia as desired by copy&pasting options from src/settings_default.py. You should then also create/configure the database using python manage.py syncdb Make sure to create a new admin user when prompted -- this will be user #1 in-game. If you use django-south, you'll see mentions of migrating things in the above run. You then also have to run python manage.py migrate If you use default sqlite3 database, you will find a file evennia.db appearing. This is the database file. Just delete this and repeat the above manage.py steps to start with a fresh database. When you are set up, run evennia.py again to start the server.""") sys.exit() # Get the settings from django.conf import settings from src.utils.utils import get_evennia_version EVENNIA_VERSION = get_evennia_version() # Setup access of the evennia server itself SERVER_PY_FILE = os.path.join(settings.SRC_DIR, 'server/server.py') PORTAL_PY_FILE = os.path.join(settings.SRC_DIR, 'server/portal.py') # Get logfile names SERVER_LOGFILE = settings.SERVER_LOG_FILE PORTAL_LOGFILE = settings.PORTAL_LOG_FILE # Check so a database exists and is accessible from django.db import DatabaseError from src.objects.models import ObjectDB try: test = ObjectDB.objects.get(id=1) except ObjectDB.DoesNotExist: pass # this is fine at this point except DatabaseError: print _(""" Your database does not seem to be set up correctly. Please run: python manage.py syncdb (make sure to create an admin user when prompted). If you use pyhon-south you will get mentions of migrating in the above run. You then need to also run python manage.py migrate When you have a database set up, rerun evennia.py. """) sys.exit() # Add this to the environmental variable for the 'twistd' command. currpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if 'PYTHONPATH' in os.environ: os.environ['PYTHONPATH'] += (":%s" % currpath) else: os.environ['PYTHONPATH'] = currpath TWISTED_BINARY = 'twistd' if os.name == 'nt': # Windows needs more work to get the correct binary try: # Test for for win32api import win32api except ImportError: print _(""" ERROR: Unable to import win32api, which Twisted requires to run. You may download it from: http://sourceforge.net/projects/pywin32 or http://starship.python.net/crew/mhammond/win32/Downloads.html""") sys.exit() if not os.path.exists('twistd.bat'): # Test for executable twisted batch file. This calls the twistd.py # executable that is usually not found on the path in Windows. # It's not enough to locate scripts.twistd, what we want is the # executable script C:\PythonXX/Scripts/twistd.py. Alas we cannot # hardcode this location since we don't know if user has Python # in a non-standard location, so we try to figure it out. from twisted.scripts import twistd twistd_path = os.path.abspath( os.path.join(os.path.dirname(twistd.__file__), os.pardir, os.pardir, os.pardir, os.pardir, 'scripts', 'twistd.py')) bat_file = open('twistd.bat','w') bat_file.write("@\"%s\" \"%s\" %%*" % (sys.executable, twistd_path)) bat_file.close() print _(""" INFO: Since you are running Windows, a file 'twistd.bat' was created for you. This is a simple batch file that tries to call the twisted executable. Evennia determined this to be: %{twistd_path}s If you run into errors at startup you might need to edit twistd.bat to point to the actual location of the Twisted executable (usually called twistd.py) on your machine. This procedure is only done once. Run evennia.py again when you are ready to start the server. """) % {'twistd_path': twistd_path} sys.exit() TWISTED_BINARY = 'twistd.bat' # Functions def get_pid(pidfile): """ Get the PID (Process ID) by trying to access an PID file. """ pid = None if os.path.exists(pidfile): f = open(pidfile, 'r') pid = f.read() return pid def del_pid(pidfile): """ The pidfile should normally be removed after a process has finished, but when sending certain signals they remain, so we need to clean them manually. """ if os.path.exists(pidfile): os.remove(pidfile) def kill(pidfile, signal=SIG, succmsg="", errmsg="", restart_file=SERVER_RESTART, restart=True): """ Send a kill signal to a process based on PID. A customized success/error message will be returned. If clean=True, the system will attempt to manually remove the pid file. """ pid = get_pid(pidfile) if pid: if os.name == 'nt': if sys.version < "2.7": print _("Windows requires Python 2.7 or higher for this operation.") return os.remove(pidfile) # set restart/norestart flag f = open(restart_file, 'w') f.write(str(restart)) f.close() try: os.kill(int(pid), signal) except OSError: print _("Process %(pid)s could not be signalled. The PID file '%(pidfile)s' seems stale. Try removing it.") % {'pid': pid, 'pidfile': pidfile} return print "Evennia:", succmsg return print "Evennia:", errmsg def run_menu(): """ This launches an interactive menu. """ cmdstr = ["python", "runner.py"] while True: # menu loop print MENU inp = raw_input(_(" option > ")) # quitting and help if inp.lower() == 'q': sys.exit() elif inp.lower() == 'h': print HELPENTRY % EVENNIA_VERSION raw_input(_("press <return> to continue ...")) continue # options try: inp = int(inp) except ValueError: print _("Not a valid option.") continue errmsg = _("The %s does not seem to be running.") if inp < 5: if inp == 1: pass # default operation elif inp == 2: cmdstr.extend(['--iserver']) elif inp == 3: cmdstr.extend(['--iportal']) elif inp == 4: cmdstr.extend(['--iserver', '--iportal']) return cmdstr elif inp < 10: if inp == 5: if os.name == 'nt': print _("This operation is not supported under Windows. Log into the game to restart/reload the server.") return kill(SERVER_PIDFILE, SIG, _("Server reloaded."), errmsg % "Server") elif inp == 6: if os.name == 'nt': print _("This operation is not supported under Windows.") return kill(PORTAL_PIDFILE, SIG, _("Portal reloaded (or stopped if in daemon mode)."), errmsg % "Portal") elif inp == 7: kill(SERVER_PIDFILE, SIG, _("Stopped Portal."), errmsg % "Portal", PORTAL_RESTART, restart=False) kill(PORTAL_PIDFILE, SIG, _("Stopped Server."), errmsg % "Server", restart=False) elif inp == 8: kill(PORTAL_PIDFILE, SIG, _("Stopped Server."), errmsg % "Server", restart=False) elif inp == 9: kill(SERVER_PIDFILE, SIG, _("Stopped Portal."), errmsg % "Portal", PORTAL_RESTART, restart=False) return else: print _("Not a valid option.") return None def handle_args(options, mode, service): """ Handle argument options given on the command line. options - parsed object for command line mode - str; start/stop etc service - str; server, portal or all """ inter = options.interactive cmdstr = ["python", "runner.py"] errmsg = _("The %s does not seem to be running.") if mode == 'start': # launch the error checker. Best to catch the errors already here. error_check_python_modules() # starting one or many services if service == 'server': if inter: cmdstr.append('--iserver') cmdstr.append('--noportal') elif service == 'portal': if inter: cmdstr.append('--iportal') cmdstr.append('--noserver') else: # all # for convenience we don't start logging of portal, only of server with this command. if inter: cmdstr.extend(['--iserver']) return cmdstr elif mode == 'reload': # restarting services if os.name == 'nt': print _("Restarting from command line is not supported under Windows. Log into the game to restart.") return if service == 'server': kill(SERVER_PIDFILE, SIG, _("Server reloaded."), errmsg % 'Server') elif service == 'portal': print _("Note: Portal usually don't need to be reloaded unless you are debugging in interactive mode.") print _("If Portal was running in default Daemon mode, it cannot be restarted. In that case you have ") print _("to restart it manually with 'evennia.py start portal'") kill(PORTAL_PIDFILE, SIG, _("Portal reloaded (or stopped, if it was in daemon mode)."), errmsg % 'Portal', PORTAL_RESTART) else: # all # default mode, only restart server kill(SERVER_PIDFILE, SIG, _("Server reload."), errmsg % 'Server') elif mode == 'stop': # stop processes, avoiding reload if service == 'server': kill(SERVER_PIDFILE, SIG, _("Server stopped."), errmsg % 'Server', restart=False) elif service == 'portal': kill(PORTAL_PIDFILE, SIG, _("Portal stopped."), errmsg % 'Portal', PORTAL_RESTART, restart=False) else: kill(PORTAL_PIDFILE, SIG, _("Portal stopped."), errmsg % 'Portal', PORTAL_RESTART, restart=False) kill(SERVER_PIDFILE, SIG, _("Server stopped."), errmsg % 'Server', restart=False) return None def error_check_python_modules(): """ Import settings modules in settings. This will raise exceptions on pure python-syntax issues which are hard to catch gracefully with exceptions in the engine (since they are formatting errors in the python source files themselves). Best they fail already here before we get any further. """ def imp(path, split=True): mod, fromlist = path, "None" if split: mod, fromlist = path.rsplit('.', 1) __import__(mod, fromlist=[fromlist]) # core modules imp(settings.COMMAND_PARSER) imp(settings.SEARCH_AT_RESULT) imp(settings.SEARCH_AT_MULTIMATCH_INPUT) imp(settings.CONNECTION_SCREEN_MODULE, split=False) #imp(settings.AT_INITIAL_SETUP_HOOK_MODULE, split=False) for path in settings.LOCK_FUNC_MODULES: imp(path, split=False) # cmdsets from src.commands import cmdsethandler cmdsethandler.import_cmdset(settings.CMDSET_UNLOGGEDIN, None) cmdsethandler.import_cmdset(settings.CMDSET_DEFAULT, None) cmdsethandler.import_cmdset(settings.CMDSET_OOC, None) # typeclasses imp(settings.BASE_PLAYER_TYPECLASS) imp(settings.BASE_OBJECT_TYPECLASS) imp(settings.BASE_CHARACTER_TYPECLASS) imp(settings.BASE_ROOM_TYPECLASS) imp(settings.BASE_EXIT_TYPECLASS) imp(settings.BASE_SCRIPT_TYPECLASS) def main(): """ This handles command line input. """ parser = OptionParser(usage="%prog [-i] [menu|start|reload|stop [server|portal|all]]", description=_("""This is the main Evennia launcher. It handles the Portal and Server, the two services making up Evennia. Default is to operate on both services. Use --interactive together with start to launch services as 'interactive'. Note that when launching 'all' services with the --interactive flag, both services will be started, but only Server will actually be started in interactive mode. This is simply because this is the most commonly useful state. To activate interactive mode also for Portal, launch the two services explicitly as two separate calls to this program. You can also use the menu.""")) parser.add_option('-i', '--interactive', action='store_true', dest='interactive', default=False, help=_("Start given processes in interactive mode (log to stdout, don't start as a daemon).")) options, args = parser.parse_args() inter = options.interactive if not args: mode = "menu" service = 'all' if args: mode = args[0] service = "all" if len(args) > 1: service = args[1] if mode not in ['menu', 'start', 'reload', 'stop']: print _("mode should be none or one of 'menu', 'start', 'reload' or 'stop'.") sys.exit() if service not in ['server', 'portal', 'all']: print _("service should be none or 'server', 'portal' or 'all'.") sys.exit() if mode == 'menu': # launch menu cmdstr = run_menu() else: # handle command-line arguments cmdstr = handle_args(options, mode, service) if cmdstr: # call the runner. cmdstr.append('start') Popen(cmdstr) if __name__ == '__main__': from src.utils.utils import check_evennia_dependencies if check_evennia_dependencies(): main()
Python
""" This defines the cmdset for the red_button. Here we have defined the commands and the cmdset in the same module, but if you have many different commands to merge it is often better to define the cmdset separately, picking and choosing from among the available commands as to what should be included in the cmdset - this way you can often re-use the commands too. """ import random from src.commands.cmdset import CmdSet from game.gamesrc.commands.basecommand import Command # Some simple commands for the red button #------------------------------------------------------------ # Commands defined on the red button #------------------------------------------------------------ class CmdNudge(Command): """ Try to nudge the button's lid Usage: nudge lid This command will have you try to push the lid of the button away. """ key = "nudge lid" # two-word command name! aliases = ["nudge"] locks = "cmd:all()" def func(self): """ nudge the lid. Random chance of success to open it. """ rand = random.random() if rand < 0.5: self.caller.msg("You nudge at the lid. It seems stuck.") elif 0.5 <= rand < 0.7: self.caller.msg("You move the lid back and forth. It won't budge.") else: self.caller.msg("You manage to get a nail under the lid.") self.caller.execute_cmd("open lid") class CmdPush(Command): """ Push the red button Usage: push button """ key = "push button" aliases = ["push", "press button", "press"] locks = "cmd:all()" def func(self): """ Note that we choose to implement this with checking for if the lid is open/closed. This is because this command is likely to be tried regardless of the state of the lid. An alternative would be to make two versions of this command and tuck them into the cmdset linked to the Open and Closed lid-state respectively. """ if self.obj.db.lid_open: string = "You reach out to press the big red button ..." string += "\n\nA BOOM! A bright light blinds you!" string += "\nThe world goes dark ..." self.caller.msg(string) self.caller.location.msg_contents("%s presses the button. BOOM! %s is blinded by a flash!" % (self.caller.name, self.caller.name), exclude=self.caller) # the button's method will handle all setup of scripts etc. self.obj.press_button(self.caller) else: string = "You cannot push the button - there is a glass lid covering it." self.caller.msg(string) class CmdSmashGlass(Command): """ smash glass Usage: smash glass Try to smash the glass of the button. """ key = "smash glass" aliases = ["smash lid", "break lid", "smash"] locks = "cmd:all()" def func(self): """ The lid won't open, but there is a small chance of causing the lamp to break. """ rand = random.random() if rand < 0.2: string = "You smash your hand against the glass" string += " with all your might. The lid won't budge" string += " but you cause quite the tremor through the button's mount." string += "\nIt looks like the button's lamp stopped working for the time being." self.obj.lamp_works = False elif rand < 0.6: string = "You hit the lid hard. It doesn't move an inch." else: string = "You place a well-aimed fist against the glass of the lid." string += " Unfortunately all you get is a pain in your hand. Maybe" string += " you should just try to open the lid instead?" self.caller.msg(string) self.caller.location.msg_contents("%s tries to smash the glass of the button." % (self.caller.name), exclude=self.caller) class CmdOpenLid(Command): """ open lid Usage: open lid """ key = "open lid" aliases = ["open button", 'open'] locks = "cmd:all()" def func(self): "simply call the right function." if self.obj.db.lid_locked: self.caller.msg("This lid seems locked in place for the moment.") return string = "\nA ticking sound is heard, like a winding mechanism. Seems " string += "the lid will soon close again." self.caller.msg(string) self.caller.location.msg_contents("%s opens the lid of the button." % (self.caller.name), exclude=self.caller) # add the relevant cmdsets to button self.obj.cmdset.add(LidClosedCmdSet) # call object method self.obj.open_lid() class CmdCloseLid(Command): """ close the lid Usage: close lid Closes the lid of the red button. """ key = "close lid" aliases = ["close"] locks = "cmd:all()" def func(self): "Close the lid" self.obj.close_lid() # this will clean out scripts dependent on lid being open. self.caller.msg("You close the button's lid. It clicks back into place.") self.caller.location.msg_contents("%s closes the button's lid." % (self.caller.name), exclude=self.caller) class CmdBlindLook(Command): """ Looking around in darkness Usage: look <obj> ... not that there's much to see in the dark. """ key = "look" aliases = ["l", "get", "examine", "ex", "feel", "listen"] locks = "cmd:all()" def func(self): "This replaces all the senses when blinded." # we decide what to reply based on which command was # actually tried if self.cmdstring == "get": string = "You fumble around blindly without finding anything." elif self.cmdstring == "examine": string = "You try to examine your surroundings, but can't see a thing." elif self.cmdstring == "listen": string = "You are deafened by the boom." elif self.cmdstring == "feel": string = "You fumble around, hands outstretched. You bump your knee." else: # trying to look string = "You are temporarily blinded by the flash. " string += "Until it wears off, all you can do is feel around blindly." self.caller.msg(string) self.caller.location.msg_contents("%s stumbles around, blinded." % (self.caller.name), exclude=self.caller) class CmdBlindHelp(Command): """ Help function while in the blinded state Usage: help """ key = "help" aliases = "h" locks = "cmd:all()" def func(self): "Give a message." self.caller.msg("You are beyond help ... until you can see again.") #--------------------------------------------------------------- # Command sets for the red button #--------------------------------------------------------------- # We next tuck these commands into their respective command sets. # (note that we are overdoing the cdmset separation a bit here # to show how it works). class DefaultCmdSet(CmdSet): """ The default cmdset always sits on the button object and whereas other command sets may be added/merge onto it and hide it, removing them will always bring it back. It's added to the object using obj.cmdset.add_default(). """ key = "RedButtonDefault" mergetype = "Union" # this is default, we don't really need to put it here. def at_cmdset_creation(self): "Init the cmdset" self.add(CmdPush()) class LidClosedCmdSet(CmdSet): """ A simple cmdset tied to the redbutton object. It contains the commands that launches the other command sets, making the red button a self-contained item (i.e. you don't have to manually add any scripts etc to it when creating it). """ key = "LidClosedCmdSet" # default Union is used *except* if we are adding to a # cmdset named LidOpenCmdSet - this one we replace # completely. key_mergetype = {"LidOpenCmdSet": "Replace"} def at_cmdset_creation(self): "Populates the cmdset when it is instantiated." self.add(CmdNudge()) self.add(CmdSmashGlass()) self.add(CmdOpenLid()) class LidOpenCmdSet(CmdSet): """ This is the opposite of the Closed cmdset. """ key = "LidOpenCmdSet" # default Union is used *except* if we are adding to a # cmdset named LidClosedCmdSet - this one we replace # completely. key_mergetype = {"LidClosedCmdSet": "Replace"} def at_cmdset_creation(self): "setup the cmdset (just one command)" self.add(CmdCloseLid()) class BlindCmdSet(CmdSet): """ This is the cmdset added to the *player* when the button is pushed. """ key = "BlindCmdSet" # we want it to completely replace all normal commands # until the timed script removes it again. mergetype = "Replace" # we want to stop the player from walking around # in this blinded state, so we hide all exits too. # (channel commands will still work). no_exits = True # keep player in the same room no_objs = True # don't allow object commands def at_cmdset_creation(self): "Setup the blind cmdset" from src.commands.default.general import CmdSay from src.commands.default.general import CmdPose self.add(CmdSay()) self.add(CmdPose()) self.add(CmdBlindLook()) self.add(CmdBlindHelp())
Python
""" This is the second component of using a Command in your game - a command set. A cmdset groups any number of commands together. CmdSets are stored on character and objects and all available cmdsets are searched when Evennia tries to determine if a command is available. Sets can be merged and combined in many different ways (see the docs). You can use the classes below as templates for extending the game with new command sets; you can also import the default Evennia cmdset and extend/overload that. To change default cmdset (the one all character start the game with), Create your custom commands in other modules (inheriting from game.gamesrc.commands.basecommand), add them to a cmdset class, then set your settings.CMDSET_DEFAULT to point to this new cmdset class. """ from src.commands.cmdset import CmdSet from src.commands.default import cmdset_default, cmdset_unloggedin, cmdset_ooc from game.gamesrc.commands.basecommand import Command #from contrib import menusystem, lineeditor #from contrib import misc_commands #from contrib import chargen class DefaultCmdSet(cmdset_default.DefaultCmdSet): """ This is an example of how to overload the default command set defined in src/commands/default/cmdset_default.py. Here we copy everything by calling the parent, but you can copy&paste any combination of the default command to customize your default set. Next you change settings.CMDSET_DEFAULT to point to this class. """ key = "DefaultMUX" def at_cmdset_creation(self): """ Populates the cmdset """ # calling setup in src.commands.default.cmdset_default super(DefaultCmdSet, self).at_cmdset_creation() # # any commands you add below will overload the default ones. # #self.add(menusystem.CmdMenuTest()) #self.add(lineeditor.CmdEditor()) #self.add(misc_commands.CmdQuell()) class UnloggedinCmdSet(cmdset_unloggedin.UnloggedinCmdSet): """ This is an example of how to overload the command set of the unlogged in commands, defined in src/commands/default/cmdset_unloggedin.py. Here we copy everything by calling the parent, but you can copy&paste any combination of the default command to customize your default set. Next you change settings.CMDSET_UNLOGGEDIN to point to this class. """ key = "Unloggedin" def at_cmdset_creation(self): """ Populates the cmdset """ # calling setup in src.commands.default.cmdset_unloggedin super(UnloggedinCmdSet, self).at_cmdset_creation() # # any commands you add below will overload the default ones. # class OOCCmdSet(cmdset_ooc.OOCCmdSet): """ This is set is available to the player when they have no character connected to them (i.e. they are out-of-character, ooc). """ key = "OOC" def at_cmdset_creation(self): """ Populates the cmdset """ # calling setup in src.commands.default.cmdset_ooc super(OOCCmdSet, self).at_cmdset_creation() # # any commands you add below will overload the default ones. # class BaseCmdSet(CmdSet): """ Implements an empty, example cmdset. """ key = "ExampleSet" def at_cmdset_creation(self): """ This is the only method defined in a cmdset, called during its creation. It should populate the set with command instances. Here we just add the base Command object. """ self.add(Command())
Python
""" Inherit from this and overload the member functions to define your own commands. See src/commands/default/muxcommand.py for an example. """ from src.commands.command import Command as BaseCommand from src.commands.default.muxcommand import MuxCommand as BaseMuxCommand from src.utils import utils class MuxCommand(BaseMuxCommand): """ This sets up the basis for a Evennia's 'MUX-like' command style. The idea is that most other Mux-related commands should just inherit from this and don't have to implement much parsing of their own unless they do something particularly advanced. Note that the class's __doc__ string (this text) is used by Evennia to create the automatic help entry for the command, so make sure to document consistently here. Most of the time your child classes should not need to implement parse() at all, but only the main func() method for doing useful things. See examples in src/commands/default. """ def parse(self): """ This method is called by the cmdhandler once the command name has been identified. It creates a new set of member variables that can be later accessed from self.func() (see below) The following variables are available for our use when entering this method (from the command definition, and assigned on the fly by the cmdhandler): self.key - the name of this command ('look') self.aliases - the aliases of this cmd ('l') self.locks - lock definition for this command, usually cmd:<func> self.help_category - overall category of command self.caller - the object calling this command self.cmdstring - the actual command name used to call this (this allows you to know which alias was used, for example) self.args - the raw input; everything following self.cmdstring. self.cmdset - the cmdset from which this command was picked. Not often used (useful for commands like 'help' or to list all available commands etc) self.obj - the object on which this command was defined. It is often the same as self.caller. A MUX command has the following possible syntax: name[ with several words][/switch[/switch..]] arg1[,arg2,...] [[=|,] arg[,..]] The 'name[ with several words]' part is already dealt with by the cmdhandler at this point, and stored in self.cmdname (we don't use it here). The rest of the command is stored in self.args, which can start with the switch indicator /. This parser breaks self.args into its constituents and stores them in the following variables: self.switches = [list of /switches (without the /)] self.raw = This is the raw argument input, including switches self.args = This is re-defined to be everything *except* the switches self.lhs = Everything to the left of = (lhs:'left-hand side'). If no = is found, this is identical to self.args. self.rhs: Everything to the right of = (rhs:'right-hand side'). If no '=' is found, this is None. self.lhslist - [self.lhs split into a list by comma] self.rhslist - [list of self.rhs split into a list by comma] self.arglist = [list of space-separated args (stripped, including '=' if it exists)] All args and list members are stripped of excess whitespace around the strings, but case is preserved. """ # parse all that makes it a MUX command (don't remove this) super(MuxCommand, self).parse() def func(self): """ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein. """ # this can be removed in your child class, it's just # printing the ingoing variables as a demo super(MuxCommand, self).func() class Command(BaseCommand): """ This is the basic command class (MuxCommand is a child of this). Inherit from this if you want to create your own command styles. Note that the class's __doc__ string (this text) is used by Evennia to create the automatic help entry for the command, so make sure to document consistently here. """ def access(self, srcobj, access_type="cmd", default=False): """ This is called by the cmdhandler to determine if srcobj is allowed to execute this command. This also determines if the command appears in help etc. By default, We use checks of the 'cmd' type of lock to determine if the command should be run. """ return super(Command, self).access(srcobj, access_type=access_type, default=default) def at_pre_cmd(self): """ This hook is called before self.parse() on all commands """ pass def at_post_cmd(self): """ This hook is called after the command has finished executing (after self.func()). """ pass def parse(self): """ This method is called by the cmdhandler once the command name has been identified. It creates a new set of member variables that can be later accessed from self.func() (see below) The following variables are available for our use when entering this method (from the command definition, and assigned on the fly by the cmdhandler): self.key - the name of this command ('look') self.aliases - the aliases of this cmd ('l') self.permissions - permission string for this command self.help_category - overall category of command self.caller - the object calling this command self.cmdstring - the actual command name used to call this (this allows you to know which alias was used, for example) self.args - the raw input; everything following self.cmdstring. self.cmdset - the cmdset from which this command was picked. Not often used (useful for commands like 'help' or to list all available commands etc) self.obj - the object on which this command was defined. It is often the same as self.caller. """ pass def func(self): """ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein. """ # this can be removed in your child class, it's just # printing the ingoing variables as a demo super(MuxCommand, self).func()
Python
""" Custom at_initial_setup method. This allows you to hook special modifications to the initial server startup process. Note that this will only be run once - when the server starts up for the very first time! It is called last in the startup process and can thus be used to overload things that happened before it. The module must contain a global function at_initial_setup(). This will be called without arguments. Note that tracebacks in this module will be QUIETLY ignored, so make sure to check it well to make sure it does what you expect it to. This module is selected by settings.AT_INITIAL_SETUP_HOOK_MODULE. """ def at_initial_setup(): pass
Python
# # MSSP (Mud Server Status Protocol) meta information # # MUD website listings (that you have registered with) can use this # information to keep up-to-date with your game stats as you change # them. Also number of currently active players and uptime will # automatically be reported. You don't have to fill in everything # (and most are not used by all crawlers); leave the default # if so needed. You need to @reload the game before updated # information is made available to crawlers (reloading does not # affect uptime). # MSSPTable = { # Required fieldss "NAME": "Evennia", # Generic "CRAWL DELAY": "-1", # limit how often crawler updates the listing. -1 for no limit "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": "", # 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 or 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"}
Python
""" This is an example module for holding custom lock funcs, used in in-game locks. The modules available to use as lockfuncs are defined in the tuple settings.LOCK_FUNC_MODULES. All functions defined globally in this module are assumed to be available for use in lockstrings to determine access. See http://code.google.com/p/evennia/wiki/Locks A lock function is always called with two arguments, accessing_obj and accessed_obj, followed by any number of arguments. All possible arguments should be handled (excess ones calling magic (*args, **kwargs) to avoid errors). The lock function should handle all eventual tracebacks by logging the error and returning False. See many more examples of lock functions in src.locks.lockfuncs. """ def myfalse(accessing_obj, accessed_obj, *args, **kwargs): """ called in lockstring with myfalse(). A simple logger that always returns false. Prints to stdout for simplicity, should use utils.logger for real operation. """ print "%s tried to access %s. Access denied." % (accessing_obj, accessed_obj) return False
Python
# # This module holds textual connection screen definitions. All global # string variables (only) in this module are read by Evennia and # assumed to define a Connection screen. You can change which module is # used with settings.CONNECTION_SCREEN_MODULE. # # The names of the string variables doesn't matter (except they # shouldn't start with _), but each should hold a string defining a # connection screen - as seen when first connecting to the game # (before having logged in). # # OBS - If there are more than one string variable viable in this # module, a random one is picked! # # After adding new connection screens to this module you must either # reboot or reload the server to make them available. # from src.utils import utils from src.commands.connection_screen import DEFAULT_SCREEN # # CUSTOM_SCREEN = \ # """{b=============================================================={n # Welcome to {gEvennia{n, version %s! # # If you have an existing account, connect to it by typing: # {wconnect <email> <password>{n # If you need to create an account, type (without the <>'s): # {wcreate \"<username>\" <email> <password>{n # # Enter {whelp{n for more info. {wlook{n will re-load this screen. #{b=============================================================={n""" % utils.get_evennia_version() # # A suggested alternative screen for the Menu login system # MENU_SCREEN = \ # """{b=============================================================={n # Welcome to {gEvennnia{n, version %s! # {b=============================================================={n""" % utils.get_evennia_version()
Python
# # Example module holding functions for out-of-band protocols to # import and map to given commands from the client. This module # is selected by settings.OOB_FUNC_MODULE. # # All functions defined global in this module will be available # for the oob system to call. They will be called with a session/character # as first argument (depending on if the session is logged in or not), # following by any number of extra arguments. The return value will # be packed and returned to the oob protocol and can be on any form. # def testoob(character, *args, **kwargs): "Simple test function" print "Called testoob: %s" % val return "testoob did stuff to the input string '%s'!" % val
Python
""" These are the base object typeclasses, a convenient shortcut to the objects in src/objects/objects.py. You can start building your game from these bases if you want. To change these defaults to point to some other object, change some or all of these variables in settings.py: BASE_OBJECT_TYPECLASS BASE_CHARACTER_TYPECLASS BASE_ROOM_TYPECLASS BASE_EXIT_TYPECLASS BASE_PLAYER_TYPECLASS Some of the main uses for these settings are not hard-coded in Evennia, rather they are convenient defaults for in-game commands (which you may change) Example would be build commands like '@dig' knowing to create a particular room-type object). New instances of Objects (inheriting from these typeclasses) are created with src.utils.create.create_object(typeclass, ...) where typeclass is the python path to the class you want to use. """ from src.objects.objects import Object as BaseObject from src.objects.objects import Character as BaseCharacter from src.objects.objects import Room as BaseRoom from src.objects.objects import Exit as BaseExit from src.players.player import Player as BasePlayer class Object(BaseObject): """ This is the root typeclass object, implementing an in-game Evennia game object, such as having a location, being able to be manipulated or looked at, etc. If you create a new typeclass, it must always inherit from this object (or any of the other objects in this file, since they all actually inherit from BaseObject, as seen in src.object.objects). The BaseObject class implements several hooks tying into the game engine. By re-implementing these hooks you can control the system. You should never need to re-implement special Python methods, such as __init__ and especially never __getattribute__ and __setattr__ since these are used heavily by the typeclass system of Evennia and messing with them might well break things for you. Hooks (these are class methods, so their arguments should also start with self): at_object_creation() - only called once, when object is first created. Almost all object customizations go here. at_first_login() - only called once, the very first time user logs in. at_pre_login() - called every time the user connects, after they have identified, just before the system actually logs them in. at_post_login() - called at the end of login, just before setting the player loose in the world. at_disconnect() - called just before the use is disconnected (this is also called if the system determines the player lost their link) at_object_delete() - called just before the database object is permanently deleted from the database with obj.delete(). Note that cleaning out contents and deleting connected exits is not needed, this is handled automatically when doing obj.delete(). If this method returns False, deletion is aborted. at_before_move(destination) - called by obj.move_to() just before moving object to the destination. If this method returns False, move is cancelled. announce_move_from(destination) - called while still standing in the old location, if obj.move_to() has argument quiet=False. announce_move_to(source_location) - called after move, while standing in the new location if obj.move_to() has argument quiet=False. at_after_move(source_location) - always called after a move has been performed. at_object_leave(obj, target_location) - called when this object loose an object (e.g. someone leaving the room, an object is given away etc) at_object_receive(obj, source_location) - called when this object receives another object (e.g. a room being entered, an object moved into inventory) return_appearance(looker) - by default, this is used by the 'look' command to request this object to describe itself. Looker is the object requesting to get the information. at_desc(looker=None) - by default called whenever the appearance is requested. at_msg_receive(self, msg, from_obj=None, data=None) - called whenever someone sends a message to this object. message aborted if hook returns False. at_msg_send(self, msg, to_obj=None, data=None) - called when this objects sends a message. This can only be called if from_obj is specified in the call to msg(). at_object_delete() - calleed when this object is to be deleted. If returns False, deletion is aborted. at_get(getter) - called after object has been picked up. Does not stop pickup. at_drop(dropper) - called when this object has been dropped. at_say(speaker, message) - by default, called if an object inside this object speaks at_server_reload() - called when server is reloading at_server_shutdown() - called when server is resetting/shutting down """ pass class Character(BaseCharacter): """ This is the default object created for a new user connecting - the in-game player character representation. The basetype_setup always assigns the default_cmdset as a fallback to objects of this type. The default hooks also hide the character object away (by moving it to a Null location whenever the player logs off (otherwise the character would remain in the world, "headless" so to say). """ pass class Room(BaseRoom): """ Rooms are like any object, except their location is None (which is default). Usually this object should be assigned to room-building commands by use of the settings.BASE_ROOM_TYPECLASS variable. """ pass class Exit(BaseExit): """ Exits are connectors between rooms. Exits defines the 'destination' property and sets up a command on itself with the same name as the Exit object - this command allows the player to traverse the exit to the destination just by writing the name of the object on the command line. Relevant hooks: at_before_traverse(traveller) - called just before traversing at_after_traverse(traveller, source_loc) - called just after traversing at_failed_traverse(traveller) - called if traversal failed for some reason. Will not be called if the attribute 'err_traverse' is defined, in which case that will simply be echoed. """ pass class Player(BasePlayer): """ This class describes the actual OOC player (i.e. the user connecting to the MUD). It does NOT have visual appearance in the game world (that is handled by the character which is connected to this). Comm channels are attended/joined using this object. It can be useful e.g. for storing configuration options for your game, but should generally not hold any character-related info (that's best handled on the character level). Can be set using BASE_PLAYER_TYPECLASS. The following hooks are called by the engine. Note that all of the following are called on the character object too, and mostly at the same time. at_player_creation() - 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. at_pre_login() - called every time the user connects, after they have identified, just before the system actually logs them in. at_post_login() - called at the end of login, just before setting the player loose in the world. at_disconnect() - called just before the use is disconnected (this is also called if the system determines the player lost their link) """ pass
Python
""" This is a more advanced example object. It combines functions from script.examples as well as commands.examples to make an interactive button typeclass. Create this button with @create/drop examples.red_button.RedButton Note that if you must drop the button before you can see its messages! """ import random from game.gamesrc.objects.baseobjects import Object from game.gamesrc.scripts.examples import red_button_scripts as scriptexamples from game.gamesrc.commands.examples import cmdset_red_button as cmdsetexamples # # Definition of the object itself # class RedButton(Object): """ This class describes an evil red button. It will use the script definition in game/gamesrc/events/example.py to blink at regular intervals. It also uses a series of script and commands to handle pushing the button and causing effects when doing so. The following attributes can be set on the button: desc_lid_open - description when lid is open desc_lid_closed - description when lid is closed desc_lamp_broken - description when lamp is broken """ def at_object_creation(self): """ This function is called when object is created. Use this instead of e.g. __init__. """ # store desc (default, you can change this at creation time) desc = "This is a large red button, inviting yet evil-looking. " desc += "A closed glass lid protects it." self.db.desc = desc # We have to define all the variables the scripts # are checking/using *before* adding the scripts or # they might be deactivated before even starting! self.db.lid_open = False self.db.lamp_works = True self.db.lid_locked = False self.cmdset.add_default(cmdsetexamples.DefaultCmdSet, permanent=True) # since the cmdsets relevant to the button are added 'on the fly', # we need to setup custom scripts to do this for us (also, these scripts # check so they are valid (i.e. the lid is actually still closed)). # The AddClosedCmdSet script makes sure to add the Closed-cmdset. self.scripts.add(scriptexamples.ClosedLidState) # the script EventBlinkButton makes the button blink regularly. self.scripts.add(scriptexamples.BlinkButtonEvent) # state-changing methods def open_lid(self): """ Opens the glass lid and start the timer so it will soon close again. """ if self.db.lid_open: return desc = self.db.desc_lid_open if not desc: desc = "This is a large red button, inviting yet evil-looking. " desc += "Its glass cover is open and the button exposed." self.db.desc = desc self.db.lid_open = True # with the lid open, we validate scripts; this will clean out # scripts that depend on the lid to be closed. self.scripts.validate() # now add new scripts that define the open-lid state self.scripts.add(scriptexamples.OpenLidState) # we also add a scripted event that will close the lid after a while. # (this one cleans itself after being called once) self.scripts.add(scriptexamples.CloseLidEvent) def close_lid(self): """ Close the glass lid. This validates all scripts on the button, which means that scripts only being valid when the lid is open will go away automatically. """ if not self.db.lid_open: return desc = self.db.desc_lid_closed if not desc: desc = "This is a large red button, inviting yet evil-looking. " desc += "Its glass cover is closed, protecting it." self.db.desc = desc self.db.lid_open = False # clean out scripts depending on lid to be open self.scripts.validate() # add scripts related to the closed state self.scripts.add(scriptexamples.ClosedLidState) def break_lamp(self, feedback=True): """ Breaks the lamp in the button, stopping it from blinking. """ self.db.lamp_works = False desc = self.db.desc_lamp_broken if not desc: self.db.desc += "\nThe big red button has stopped blinking for the time being." else: self.db.desc = desc if feedback and self.location: self.location.msg_contents("The lamp flickers, the button going dark.") self.scripts.validate() def press_button(self, pobject): """ Someone was foolish enough to press the button! pobject - the person pressing the button """ # deactivate the button so it won't flash/close lid etc. self.scripts.add(scriptexamples.DeactivateButtonEvent) # blind the person pressing the button. Note that this # script is set on the *character* pressing the button! pobject.scripts.add(scriptexamples.BlindedState) # script-related methods def blink(self): """ The script system will regularly call this function to make the button blink. Now and then it won't blink at all though, to add some randomness to how often the message is echoed. """ loc = self.location if loc: rand = random.random() if rand < 0.2: string = "The red button flashes briefly." elif rand < 0.4: string = "The red button blinks invitingly." elif rand < 0.6: string = "The red button flashes. You know you wanna push it!" else: # no blink return loc.msg_contents(string)
Python
# # Batchcode script # # # The Batch-code processor accepts full python modules (e.g. "batch.py") that # looks identical to normal Python files with a few exceptions that allows them # to the executed in blocks. This way of working assures a sequential execution # of the file and allows for features like stepping from block to block # (without executing those coming before), as well as automatic deletion # of created objects etc. You can however also run a batch-code python file # directly using Python (and can also be de). # Code blocks are separated by python comments starting with special code words. # #HEADER - this denotes commands global to the entire file, such as # import statements and global variables. They will # automatically be made available for each block. Observe # that changes to these variables made in one block is not # preserved between blocks!) # #CODE (infotext) [objname, objname, ...] - This designates a code block that will be executed like a # stand-alone piece of code together with any #HEADER # defined. # infotext is a describing text about what goes in in this block. It will be # shown by the batchprocessing command. # <objname>s mark the (variable-)names of objects created in the code, # and which may be auto-deleted by the processor if desired (such as when # debugging the script). E.g., if the code contains the command # myobj = create.create_object(...), you could put 'myobj' in the #CODE header # regardless of what the created object is actually called in-game. # The following variable is automatically made available for the script: # caller - the object executing the script # #HEADER # everything in this block will be appended to the beginning of # all other #CODE blocks when they are executed. from src.utils import create, search from game.gamesrc.objects.examples import red_button from game.gamesrc.objects import baseobjects limbo = search.objects(caller, 'Limbo', global_search=True)[0] #CODE (create red button) # This is the first code block. Within each block, python # code works as normal. Note how we make use if imports and # 'limbo' defined in the #HEADER block. This block's header # offers no information about red_button variable, so it # won't be able to be deleted in debug mode. # create a red button in limbo red_button = create.create_object(red_button.RedButton, key="Red button", location=limbo, aliases=["button"]) # we take a look at what we created caller.msg("A %s was created." % red_button.key) #CODE (create table and chair) table, chair # this code block has 'table' and 'chair' set as deletable # objects. This means that when the batchcode processor runs in # testing mode, objects created in these variables will be deleted # again (so as to avoid duplicate objects when testing the script many # times). # the python variables we assign to must match the ones given in the # header for the system to be able to delete them afterwards during a # debugging run. table = create.create_object(baseobjects.Object, key="Table", location=limbo) chair = create.create_object(baseobjects.Object, key="Chair", location=limbo) string = "A %s and %s were created. If debug was active, they were deleted again." caller.msg(string % (table, chair))
Python
""" The base object to inherit from when implementing new Scripts. Scripts are objects that handle everything in the game having a time-component (i.e. that may change with time, with or without a player being involved in the change). Scripts can work like "events", in that they are triggered at regular intervals to do a certain script, but an Script set on an object can also be responsible for silently checking if its state changes, so as to update it. Evennia use several in-built scripts to keep track of things like time, to clean out dropped connections etc. New Script objects (from these classes) are created using the src.utils.create.create_script(scriptclass, ...) where scriptclass is the python path to the specific class of script you want to use. """ from src.scripts.scripts import Script as BaseScript class Script(BaseScript): """ All scripts should inherit from this class and implement some or all of its hook functions and variables. Important variables controlling the script object: self.key - the name of all scripts inheriting from this class (defaults to <unnamed>), used in lists and searches. self.desc - a description of the script, used in lists self.interval (seconds) - How often the event is triggered and calls self.at_repeat() (see below) Defaults to 0 - that is, never calls at_repeat(). self.start_delay (True/False). If True, will wait self.interval seconds befor calling self.at_repeat() for the first time. Defaults to False. self.repeats - The number of times at_repeat() should be called before automatically stopping the script. Default is 0, which means infinitely many repeats. self.persistent (True/False). If True, the script will survive a server restart (defaults to False). self.obj (game Object)- this ties this script to a particular object. It is usually not needed to set this parameter explicitly; it's set in the create methods. Hook methods (should also include self as the first argument): at_script_creation() - called only once, when an object of this class is first created. is_valid() - is called to check if the script is valid to be running at the current time. If is_valid() returns False, the running script is stopped and removed from the game. You can use this to check state changes (i.e. an script tracking some combat stats at regular intervals is only valid to run while there is actual combat going on). at_start() - Called every time the script is started, which for persistent scripts is at least once every server start. Note that this is unaffected by self.delay_start, which only delays the first call to at_repeat(). at_repeat() - Called every self.interval seconds. It will be called immediately upon launch unless self.delay_start is True, which will delay the first call of this method by self.interval seconds. If self.interval==0, this method will never be called. at_stop() - Called as the script object is stopped and is about to be removed from the game, e.g. because is_valid() returned False. """ pass
Python
""" Example of scripts. These are scripts intended for a particular object - the red_button object type in gamesrc/types/examples. A few variations on uses of scripts are included. """ from game.gamesrc.scripts.basescript import Script from game.gamesrc.commands.examples import cmdset_red_button as cmdsetexamples # # Scripts as state-managers # # Scripts have many uses, one of which is to statically # make changes when a particular state of an object changes. # There is no "timer" involved in this case (although there could be), # whenever the script determines it is "invalid", it simply shuts down # along with all the things it controls. # # To show as many features as possible of the script and cmdset systems, # we will use three scripts controlling one state each of the red_button, # each with its own set of commands, handled by cmdsets - one for when # the button has its lid open, and one for when it is closed and a # last one for when the player pushed the button and gets blinded by # a bright light. The last one also has a timer component that allows it # to remove itself after a while (and the player recovers their eyesight). class ClosedLidState(Script): """ This manages the cmdset for the "closed" button state. What this means is that while this script is valid, we add the RedButtonClosed cmdset to it (with commands like open, nudge lid etc) """ def at_script_creation(self): "Called when script first created." self.desc = "Script that manages the closed-state cmdsets for red button." self.persistent = True def at_start(self): """ This is called once every server restart, so we want to add the (memory-resident) cmdset to the object here. is_valid is automatically checked so we don't need to worry about adding the script to an open lid. """ #All we do is add the cmdset for the closed state. self.obj.cmdset.add(cmdsetexamples.LidClosedCmdSet) def is_valid(self): """ The script is only valid while the lid is closed. self.obj is the red_button on which this script is defined. """ return not self.obj.db.lid_open def at_stop(self): """ When the script stops we must make sure to clean up after us. """ self.obj.cmdset.delete(cmdsetexamples.LidClosedCmdSet) class OpenLidState(Script): """ This manages the cmdset for the "open" button state. This will add the RedButtonOpen """ def at_script_creation(self): "Called when script first created." self.desc = "Script that manages the opened-state cmdsets for red button." self.persistent = True def at_start(self): """ This is called once every server restart, so we want to add the (memory-resident) cmdset to the object here. is_valid is automatically checked, so we don't need to worry about adding the cmdset to a closed lid-button. """ #print "In Open at_start (should add cmdset)" self.obj.cmdset.add(cmdsetexamples.LidOpenCmdSet) def is_valid(self): """ The script is only valid while the lid is open. self.obj is the red_button on which this script is defined. """ return self.obj.db.lid_open def at_stop(self): """ When the script stops (like if the lid is closed again) we must make sure to clean up after us. """ self.obj.cmdset.delete(cmdsetexamples.LidOpenCmdSet) class BlindedState(Script): """ This is a timed state. This adds a (very limited) cmdset TO THE PLAYER, during a certain time, after which the script will close and all functions are restored. It's up to the function starting the script to actually set it on the right player object. """ def at_script_creation(self): """ We set up the script here. """ self.key = "temporary_blinder" self.desc = "Temporarily blinds the player for a little while." self.interval = 20 # seconds self.start_delay = True # we don't want it to stop until after 20s. self.repeats = 1 # this will go away after interval seconds. self.persistent = False # we will ditch this if server goes down def at_start(self): """ We want to add the cmdset to the linked object. Note that the RedButtonBlind cmdset is defined to completly replace the other cmdsets on the stack while it is active (this means that while blinded, only operations in this cmdset will be possible for the player to perform). It is however not persistent, so should there be a bug in it, we just need to restart the server to clear out of it during development. """ self.obj.cmdset.add(cmdsetexamples.BlindCmdSet) def at_stop(self): """ It's important that we clear out that blinded cmdset when we are done! """ self.obj.msg("You blink feverishly as your eyesight slowly returns.") self.obj.location.msg_contents("%s seems to be recovering their eyesight." % self.obj.name, exclude=self.obj) self.obj.cmdset.delete() # this will clear the latest added cmdset, # (which is the blinded one). # # Timer/Event-like Scripts # # Scripts can also work like timers, or "events". Below we # define three such timed events that makes the button a little # more "alive" - one that makes the button blink menacingly, another # that makes the lid covering the button slide back after a while. # class CloseLidEvent(Script): """ This event closes the glass lid over the button some time after it was opened. It's a one-off script that should be started/created when the lid is opened. """ def at_script_creation(self): """ Called when script object is first created. Sets things up. We want to have a lid on the button that the user can pull aside in order to make the button 'pressable'. But after a set time that lid should auto-close again, making the button safe from pressing (and deleting this command). """ self.key = "lid_closer" self.desc = "Closes lid on a red buttons" self.interval = 20 # seconds self.start_delay = True # we want to pospone the launch. self.repeats = 1 # we only close the lid once self.persistent = True # even if the server crashes in those 20 seconds, # the lid will still close once the game restarts. def is_valid(self): """ This script can only operate if the lid is open; if it is already closed, the script is clearly invalid. Note that we are here relying on an self.obj being defined (and being a RedButton object) - this we should be able to expect since this type of script is always tied to one individual red button object and not having it would be an error. """ return self.obj.db.lid_open def at_repeat(self): """ Called after self.interval seconds. It closes the lid. Before this method is called, self.is_valid() is automatically checked, so there is no need to check this manually. """ self.obj.close_lid() class BlinkButtonEvent(Script): """ This timed script lets the button flash at regular intervals. """ def at_script_creation(self): """ Sets things up. We want the button's lamp to blink at regular intervals, unless it's broken (can happen if you try to smash the glass, say). """ self.key = "blink_button" self.desc = "Blinks red buttons" self.interval = 35 #seconds self.start_delay = False #blink right away self.persistent = True #keep blinking also after server reboot def is_valid(self): """ Button will keep blinking unless it is broken. """ #print "self.obj.db.lamp_works:", self.obj.db.lamp_works return self.obj.db.lamp_works def at_repeat(self): """ Called every self.interval seconds. Makes the lamp in the button blink. """ self.obj.blink() class DeactivateButtonEvent(Script): """ This deactivates the button for a short while (it won't blink, won't close its lid etc). It is meant to be called when the button is pushed and run as long as the blinded effect lasts. We cannot put these methods in the AddBlindedCmdSet script since that script is defined on the *player* whereas this one must be defined on the *button*. """ def at_script_creation(self): """ Sets things up. """ self.key = "deactivate_button" self.desc = "Deactivate red button temporarily" self.interval = 21 #seconds self.start_delay = True # wait with the first repeat for self.interval seconds. self.persistent = True self.repeats = 1 # only do this once def at_start(self): """ Deactivate the button. Observe that this method is always called directly, regardless of the value of self.start_delay (that just controls when at_repeat() is called) """ # closing the lid will also add the ClosedState script self.obj.close_lid() # lock the lid so other players can't access it until the # first one's effect has worn off. self.obj.db.lid_locked = True # breaking the lamp also sets a correct desc self.obj.break_lamp(feedback=False) def at_repeat(self): """ When this is called, reset the functionality of the button. """ # restore button's desc. self.obj.db.lamp_works = True desc = "This is a large red button, inviting yet evil-looking. " desc += "Its glass cover is closed, protecting it." self.db.desc = desc # re-activate the blink button event. self.obj.scripts.add(BlinkButtonEvent) # unlock the lid self.obj.db.lid_locked = False self.obj.scripts.validate()
Python
""" Example script for testing. This adds a simple timer that has your character make observations and noices at irregular intervals. To test, use @script me = examples.bodyfunctions.BodyFunctions The script will only send messages to the object it is stored on, so make sure to put it on yourself or you won't see any messages! """ import random from game.gamesrc.scripts.basescript import Script class BodyFunctions(Script): """ This class defines the script itself """ def at_script_creation(self): self.key = "bodyfunction" self.desc = "Adds various timed events to a character." self.interval = 20 # seconds #self.repeats = 5 # repeat only a certain number of times self.start_delay = True # wait self.interval until first call #self.persistent = True def at_repeat(self): """ This gets called every self.interval seconds. We make a random check here so as to only return 33% of the time. """ if random.random() < 0.66: # no message this time return rand = random.random() # return a random message if rand < 0.1: string = "You tap your foot, looking around." elif rand < 0.2: string = "You have an itch. Hard to reach too." elif rand < 0.3: string = "You think you hear someone behind you. ... but when you look there's noone there." elif rand < 0.4: string = "You inspect your fingernails. Nothing to report." elif rand < 0.5: string = "You cough discreetly into your hand." elif rand < 0.6: string = "You scratch your head, looking around." elif rand < 0.7: string = "You blink, forgetting what it was you were going to do." elif rand < 0.8: string = "You feel lonely all of a sudden." elif rand < 0.9: string = "You get a great idea. Of course you won't tell anyone." else: string = "You suddenly realize how much you love Evennia!" # echo the message to the object self.obj.msg(string)
Python
#!/usr/bin/env python """ Set up the evennia system. A first startup consists of giving the command './manage syncdb' to setup the system and create the database. """ import sys import os # Tack on the root evennia directory to the python path. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #------------------------------------------------------------ # Get Evennia version #------------------------------------------------------------ try: VERSION = open("%s%s%s" % (os.pardir, os.sep, 'VERSION')).readline().strip() except IOError: VERSION = "Unknown version" #------------------------------------------------------------ # Check so session file exists in the current dir- if not, create it. #------------------------------------------------------------ _CREATED_SETTINGS = False if not os.path.exists('settings.py'): # If settings.py doesn't already exist, create it and populate it with some # basic stuff. settings_file = open('settings.py', 'w') _CREATED_SETTINGS = True string = \ """# # Evennia MU* server configuration file # # You may customize your setup by copy&pasting the variables you want # to change from the master config file src/settings_default.py to # this file. Try to *only* copy over things you really need to customize # and do *not* make any changes to src/settings_default.py directly. # This way you'll always have a sane default to fall back on # (also, the master config file may change with server updates). # from src.settings_default import * ################################################### # Evennia base server config ################################################### ################################################### # Evennia Database config ################################################### ################################################### # Evennia in-game parsers ################################################### ################################################### # Default command sets ################################################### ################################################### # Typeclasses ################################################### ################################################### # Batch processors ################################################### ################################################### # Game Time setup ################################################### ################################################### # In-game access ################################################### ################################################### # In-game Channels created from server start ################################################### ################################################### # External Channel connections ################################################### ################################################### # Config for Django web features ################################################### ################################################### # Evennia components ################################################### """ settings_file.write(string) settings_file.close() # obs - this string cannot be under i18n since settings didn't exist yet. print """ Welcome to Evennia (version %(version)s)! We created a fresh settings.py file for you.""" % {'version': VERSION} #------------------------------------------------------------ # Test the import of the settings file #------------------------------------------------------------ try: # i18n from django.utils.translation import ugettext as _ from game import settings except Exception: import traceback string = "\n" + traceback.format_exc() string += _("""\n Error: Couldn't import the file 'settings.py' in the directory containing %(file)r. There are usually two reasons for this: 1) You moved your settings.py elsewhere. In that case move it back or create a link to it from this folder. 2) The settings module is where it's supposed to be, but contains errors. Review the traceback above to resolve the problem, then try again. 3) If you get errors on finding DJANGO_SETTINGS_MODULE you might have set up django wrong in some way. If you run a virtual machine, it might be worth to restart it to see if this resolves the issue. Evennia should not require you to define any environment variables manually. """) % {'file': __file__} print string sys.exit(1) os.environ['DJANGO_SETTINGS_MODULE'] = 'game.settings' #------------------------------------------------------------ # This is run only if the module is called as a program #------------------------------------------------------------ if __name__ == "__main__": # checks if the settings file was created this run if _CREATED_SETTINGS: print _(""" Edit your new settings.py file as needed, then run 'python manage syncdb' and follow the prompts to create the database and your superuser account. """) sys.exit() # run the standard django manager, if dependencies match from src.utils.utils import check_evennia_dependencies if check_evennia_dependencies(): from django.core.management import execute_manager execute_manager(settings)
Python
#!/usr/bin/env python """ This runner is controlled by evennia.py and should normally not be launched directly. It manages the two main Evennia processes (Server and Portal) and most importanly runs a passive, threaded loop that makes sure to restart Server whenever it shuts down. Since twistd does not allow for returning an optional exit code we need to handle the current reload state for server and portal with flag-files instead. The files, one each for server and portal either contains True or False indicating if the process should be restarted upon returning, or not. A process returning != 0 will always stop, no matter the value of this file. """ import os import sys from optparse import OptionParser from subprocess import Popen, call import Queue, thread, subprocess # # System Configuration # SERVER_PIDFILE = "server.pid" PORTAL_PIDFILE = "portal.pid" SERVER_RESTART = "server.restart" PORTAL_RESTART = "portal.restart" # Set the Python path up so we can get to settings.py from here. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) os.environ['DJANGO_SETTINGS_MODULE'] = 'game.settings' # i18n from django.utils.translation import ugettext as _ if not os.path.exists('settings.py'): print _("No settings.py file found. Run evennia.py to create it.") sys.exit() # Get the settings from django.conf import settings # Setup access of the evennia server itself SERVER_PY_FILE = os.path.join(settings.SRC_DIR, 'server/server.py') PORTAL_PY_FILE = os.path.join(settings.SRC_DIR, 'server/portal.py') # Get logfile names SERVER_LOGFILE = settings.SERVER_LOG_FILE PORTAL_LOGFILE = settings.PORTAL_LOG_FILE # Add this to the environmental variable for the 'twistd' command. currpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if 'PYTHONPATH' in os.environ: os.environ['PYTHONPATH'] += (":%s" % currpath) else: os.environ['PYTHONPATH'] = currpath TWISTED_BINARY = 'twistd' if os.name == 'nt': TWISTED_BINARY = 'twistd.bat' err = False try: import win32api # Test for for win32api except ImportError: err = True if not os.path.exists(TWISTED_BINARY): err = True if err: print _("Twisted binary for Windows is not ready to use. Please run evennia.py.") sys.exit() # Functions def set_restart_mode(restart_file, flag=True): """ This sets a flag file for the restart mode. """ f = open(restart_file, 'w') f.write(str(flag)) f.close() 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 def get_pid(pidfile): """ Get the PID (Process ID) by trying to access an PID file. """ pid = None if os.path.exists(pidfile): f = open(pidfile, 'r') pid = f.read() return pid def cycle_logfile(logfile): """ Move the old log files to <filename>.old """ logfile_old = logfile + '.old' if os.path.exists(logfile): # Cycle the old logfiles to *.old if os.path.exists(logfile_old): # E.g. Windows don't support rename-replace os.remove(logfile_old) os.rename(logfile, logfile_old) logfile = settings.HTTP_LOG_FILE.strip() logfile_old = logfile + '.old' if os.path.exists(logfile): # Cycle the old logfiles to *.old if os.path.exists(logfile_old): # E.g. Windows don't support rename-replace os.remove(logfile_old) os.rename(logfile, logfile_old) # Start program management SERVER = None PORTAL = None def start_services(server_argv, portal_argv): """ This calls a threaded loop that launces the Portal and Server and then restarts them when they finish. """ global SERVER, PORTAL processes = Queue.Queue() def server_waiter(queue): try: rc = Popen(server_argv).wait() except Exception, e: print _("Server process error: %(e)s") % {'e': e} queue.put(("server_stopped", rc)) # this signals the controller that the program finished def portal_waiter(queue): try: rc = Popen(portal_argv).wait() except Exception, e: print _("Portal process error: %(e)s") % {'e': e} queue.put(("portal_stopped", rc)) # this signals the controller that the program finished if server_argv: # start server as a reloadable thread SERVER = thread.start_new_thread(server_waiter, (processes, )) if portal_argv: if get_restart_mode(PORTAL_RESTART): # start portal as interactive, reloadable thread PORTAL = thread.start_new_thread(portal_waiter, (processes, )) else: # normal operation: start portal as a daemon; we don't care to monitor it for restart PORTAL = Popen(portal_argv) if not SERVER: # if portal is daemon and no server is running, we have no reason to continue to the loop. return # Reload loop while True: # this blocks until something is actually returned. message, rc = processes.get() # restart only if process stopped cleanly if message == "server_stopped" and int(rc) == 0 and get_restart_mode(SERVER_RESTART): print _("Evennia Server stopped. Restarting ...") SERVER = thread.start_new_thread(server_waiter, (processes, )) continue # normally the portal is not reloaded since it's run as a daemon. if message == "portal_stopped" and int(rc) == 0 and get_restart_mode(PORTAL_RESTART): print _("Evennia Portal stopped in interactive mode. Restarting ...") PORTAL = thread.start_new_thread(portal_waiter, (processes, )) continue break # Setup signal handling def main(): """ This handles the command line input of the runner (it's most often called by evennia.py) """ parser = OptionParser(usage="%prog [options] start", description=_("This runner should normally *not* be called directly - it is called automatically from the evennia.py main program. It manages the Evennia game server and portal processes an hosts a threaded loop to restart the Server whenever it is stopped (this constitues Evennia's reload mechanism).")) parser.add_option('-s', '--noserver', action='store_true', dest='noserver', default=False, help=_('Do not start Server process')) parser.add_option('-p', '--noportal', action='store_true', dest='noportal', default=False, help=_('Do not start Portal process')) parser.add_option('-i', '--iserver', action='store_true', dest='iserver', default=False, help=_('output server log to stdout instead of logfile')) parser.add_option('-d', '--iportal', action='store_true', dest='iportal', default=False, help=_('output portal log to stdout. Does not make portal a daemon.')) parser.add_option('-S', '--profile-server', action='store_true', dest='sprof', default=False, help='run server under cProfile') parser.add_option('-P', '--profile-portal', action='store_true', dest='pprof', default=False, help='run portal under cProfile') options, args = parser.parse_args() if not args or args[0] != 'start': # this is so as to not be accidentally launched. parser.print_help() sys.exit() # set up default project calls server_argv = [TWISTED_BINARY, '--nodaemon', '--logfile=%s' % SERVER_LOGFILE, '--pidfile=%s' % SERVER_PIDFILE, '--python=%s' % SERVER_PY_FILE] portal_argv = [TWISTED_BINARY, '--logfile=%s' % PORTAL_LOGFILE, '--pidfile=%s' % PORTAL_PIDFILE, '--python=%s' % PORTAL_PY_FILE] # Profiling settings (read file from python shell e.g with # p = pstats.Stats('server.prof') sprof_argv = ['--savestats', '--profiler=cprofile', '--profile=server.prof'] pprof_argv = ['--savestats', '--profiler=cprofile', '--profile=portal.prof'] # Server pid = get_pid(SERVER_PIDFILE) if pid and not options.noserver: print _("\nEvennia Server is already running as process %(pid)s. Not restarted.") % {'pid': pid} options.noserver = True if options.noserver: server_argv = None else: set_restart_mode(SERVER_RESTART, True) if options.iserver: # don't log to server logfile del server_argv[2] print _("\nStarting Evennia Server (output to stdout).") else: print _("\nStarting Evennia Server (output to server logfile).") if options.sprof: server_argv.extend(sprof_argv) print "\nRunning Evennia Server under cProfile." cycle_logfile(SERVER_LOGFILE) # Portal pid = get_pid(PORTAL_PIDFILE) if pid and not options.noportal: print _("\nEvennia Portal is already running as process %(pid)s. Not restarted.") % {'pid': pid} options.noportal = True if options.noportal: portal_argv = None else: if options.iportal: # make portal interactive portal_argv[1] = '--nodaemon' PORTAL_INTERACTIVE = True set_restart_mode(PORTAL_RESTART, True) print _("\nStarting Evennia Portal in non-Daemon mode (output to stdout).") else: set_restart_mode(PORTAL_RESTART, False) print _("\nStarting Evennia Portal in Daemon mode (output to portal logfile).") if options.pprof: server_argv.extend(pprof_argv) print "\nRunning Evennia Portal under cProfile." cycle_logfile(PORTAL_LOGFILE) # Windows fixes (Windows don't support pidfiles natively) if os.name == 'nt': if server_argv: del server_argv[-2] if portal_argv: del portal_argv[-2] # Start processes start_services(server_argv, portal_argv) if __name__ == '__main__': from src.utils.utils import check_evennia_dependencies if check_evennia_dependencies(): main()
Python
""" ANSI -> html converter Credit for original idea and implementation goes to Muhammad Alkarouri and his snippet #577349 on http://code.activestate.com. (extensively modified by Griatch 2010) """ import re import cgi from src.utils import ansi class TextToHTMLparser(object): """ This class describes a parser for converting from ansi to html. """ # mapping html color name <-> ansi code. # Obs order matters - longer ansi codes are replaced first. colorcodes = [('white', '\033[1m\033[37m'), ('cyan', '\033[1m\033[36m'), ('blue', '\033[1m\033[34m'), ('red', '\033[1m\033[31m'), ('magenta', '\033[1m\033[35m'), ('lime', '\033[1m\033[32m'), ('yellow', '\033[1m\033[33m'), ('gray', '\033[37m'), ('teal', '\033[36m'), ('navy', '\033[34m'), ('maroon', '\033[31m'), ('purple', '\033[35m'), ('green', '\033[32m'), ('olive', '\033[33m')] normalcode = '\033[0m' tabstop = 4 re_string = re.compile(r'(?P<htmlchars>[<&>])|(?P<space>^[ \t]+)|(?P<lineend>\r\n|\r|\n)|(?P<protocol>(^|\s)((http|ftp)://.*?))(\s|$)', re.S|re.M|re.I) def re_color(self, text): "Replace ansi colors with html color tags" for colorname, code in self.colorcodes: regexp = "(?:%s)(.*?)(?:%s)" % (code, self.normalcode) regexp = regexp.replace('[', r'\[') text = re.sub(regexp, r'''<span style="color: %s">\1</span>''' % colorname, text) return text def re_bold(self, text): "Replace ansi hilight with bold text" regexp = "(?:%s)(.*?)(?:%s)" % ('\033[1m', self.normalcode) regexp = regexp.replace('[', r'\[') return re.sub(regexp, r'<span style="font-weight:bold">\1</span>', text) def re_underline(self, text): "Replace ansi underline with html equivalent" regexp = "(?:%s)(.*?)(?:%s)" % ('\033[4m', self.normalcode) regexp = regexp.replace('[', r'\[') return re.sub(regexp, r'<span style="text-decoration: underline">\1</span>', text) def remove_bells(self, text): "Remove ansi specials" return text.replace('\07', '') def remove_backspaces(self, text): "Removes special escape sequences" backspace_or_eol = r'(.\010)|(\033\[K)' n = 1 while n > 0: text, n = re.subn(backspace_or_eol, '', text, 1) return text def convert_linebreaks(self, text): "Extra method for cleaning linebreaks" return text.replace(r'\n', r'<br>') def convert_urls(self, text): "Replace urls (http://...) by valid HTML" regexp = r"((ftp|www|http)(\W+\S+[^).,:;?\]\}(\<span\>) \r\n$]+))" return re.sub(regexp, r'<a href="\1">\1</a>', text) def do_sub(self, m): "Helper method to be passed to re.sub." c = m.groupdict() if c['htmlchars']: return cgi.escape(c['htmlchars']) if c['lineend']: return '<br>' elif c['space']: t = m.group().replace('\t', '&nbsp;'*self.tabstop) t = t.replace(' ', '&nbsp;') return t elif c['space'] == '\t': return ' '*self.tabstop else: url = m.group('protocol') if url.startswith(' '): prefix = ' ' url = url[1:] else: prefix = '' last = m.groups()[-1] if last in ['\n', '\r', '\r\n']: last = '<br>' return '%s%s' % (prefix, url) def parse(self, text): """ Main access function, converts a text containing ansi codes into html statements. """ # parse everything to ansi first text = ansi.parse_ansi(text) # convert all ansi to html result = re.sub(self.re_string, self.do_sub, text) result = self.re_color(result) result = self.re_bold(result) result = self.re_underline(result) result = self.remove_bells(result) result = self.convert_linebreaks(result) result = self.remove_backspaces(result) result = self.convert_urls(result) # clean out eventual ansi that was missed result = ansi.parse_ansi(result, strip_ansi=True) return result HTML_PARSER = TextToHTMLparser() # # Access function # def parse_html(string, parser=HTML_PARSER): """ Parses a string, replace ansi markup with html """ return parser.parse(string)
Python
""" General helper functions that don't fit neatly under any given category. They provide some useful string and conversion methods that might be of use when designing your own game. """ import os, sys, imp import textwrap import datetime import random from twisted.internet import threads from django.conf import settings ENCODINGS = settings.ENCODINGS def is_iter(iterable): """ Checks if an object behaves iterably. However, strings are not accepted as iterable (although they are actually iterable), since string iterations are usually not what we want to do with a string. """ return hasattr(iterable, '__iter__') def fill(text, width=78, indent=0): """ Safely wrap text to a certain number of characters. text: (str) The text to wrap. width: (int) The number of characters to wrap to. indent: (int) How much to indent new lines (the first line will not be indented) """ if not text: return "" indent = " " * indent return textwrap.fill(str(text), width, subsequent_indent=indent) def crop(text, width=78, suffix="[...]"): """ Crop text to a certain width, adding suffix to show the line continues. Cropping will be done so that the suffix will also fit within the given width. """ ltext = len(to_str(text)) if ltext <= width: return text else: lsuffix = len(suffix) return "%s%s" % (text[:width-lsuffix], suffix) def dedent(text): """ Safely clean all whitespace at the left of a paragraph. This is useful for preserving triple-quoted string indentation while still shifting it all to be next to the left edge of the display. """ if not text: return "" return textwrap.dedent(text) def wildcard_to_regexp(instring): """ Converts a player-supplied string that may have wildcards in it to regular expressions. This is useful for name matching. instring: (string) A string that may potentially contain wildcards (* or ?). """ regexp_string = "" # If the string starts with an asterisk, we can't impose the beginning of # string (^) limiter. if instring[0] != "*": regexp_string += "^" # Replace any occurances of * or ? with the appropriate groups. regexp_string += instring.replace("*","(.*)").replace("?", "(.{1})") # If there's an asterisk at the end of the string, we can't impose the # end of string ($) limiter. if instring[-1] != "*": regexp_string += "$" return regexp_string def time_format(seconds, style=0): """ Function to return a 'prettified' version of a value in seconds. Style 0: 1d 08:30 Style 1: 1d Style 2: 1 day, 8 hours, 30 minutes, 10 seconds """ if seconds < 0: seconds = 0 else: # We'll just use integer math, no need for decimal precision. seconds = int(seconds) days = seconds / 86400 seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 if style is 0: """ Standard colon-style output. """ if days > 0: retval = '%id %02i:%02i' % (days, hours, minutes,) else: retval = '%02i:%02i' % (hours, minutes,) return retval elif style is 1: """ Simple, abbreviated form that only shows the highest time amount. """ if days > 0: return '%id' % (days,) elif hours > 0: return '%ih' % (hours,) elif minutes > 0: return '%im' % (minutes,) else: return '%is' % (seconds,) elif style is 2: """ Full-detailed, long-winded format. We ignore seconds. """ days_str = hours_str = minutes_str = seconds_str = '' if days > 0: if days == 1: days_str = '%i day, ' % days else: days_str = '%i days, ' % days if days or hours > 0: if hours == 1: hours_str = '%i hour, ' % hours else: hours_str = '%i hours, ' % hours if hours or minutes > 0: if minutes == 1: minutes_str = '%i minute ' % minutes else: minutes_str = '%i minutes ' % minutes retval = '%s%s%s' % (days_str, hours_str, minutes_str) elif style is 3: """ Full-detailed, long-winded format. Includes seconds. """ days_str = hours_str = minutes_str = seconds_str = '' if days > 0: if days == 1: days_str = '%i day, ' % days else: days_str = '%i days, ' % days if days or hours > 0: if hours == 1: hours_str = '%i hour, ' % hours else: hours_str = '%i hours, ' % hours if hours or minutes > 0: if minutes == 1: minutes_str = '%i minute ' % minutes else: minutes_str = '%i minutes ' % minutes if minutes or seconds > 0: if seconds == 1: seconds_str = '%i second ' % seconds else: seconds_str = '%i seconds ' % seconds retval = '%s%s%s%s' % (days_str, hours_str, minutes_str, seconds_str) return retval def datetime_format(dtobj): """ Takes a datetime object instance (e.g. from django's DateTimeField) and returns a string describing how long ago that date was. """ year, month, day = dtobj.year, dtobj.month, dtobj.day hour, minute, second = dtobj.hour, dtobj.minute, dtobj.second now = datetime.datetime.now() if year < now.year: # another year timestring = str(dtobj.date()) elif dtobj.date() < now.date(): # another date, same year timestring = "%02i-%02i" % (day, month) elif hour < now.hour - 1: # same day, more than 1 hour ago timestring = "%02i:%02i" % (hour, minute) else: # same day, less than 1 hour ago timestring = "%02i:%02i:%02i" % (hour, minute, second) return timestring def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_evennia_version(): """ Check for the evennia version info. """ version_file_path = "%s%s%s" % (settings.BASE_PATH, os.sep, "VERSION") try: return open(version_file_path).readline().strip('\n').strip() except IOError: return "Unknown version" def pypath_to_realpath(python_path, file_ending='.py'): """ Converts a path on dot python form (e.g. 'src.objects.models') to a system path ($BASE_PATH/src/objects/models.py). Calculates all paths as absoulte paths starting from the evennia main directory. """ pathsplit = python_path.strip().split('.') if not pathsplit: return python_path path = settings.BASE_PATH for directory in pathsplit: path = os.path.join(path, directory) if file_ending: return "%s%s" % (path, file_ending) return path def dbref(dbref): """ Converts/checks if input is a valid 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: dbref = int(dbref) if dbref < 1: return None except Exception: return None return dbref return None def to_unicode(obj, encoding='utf-8', force_string=False): """ This decodes a suitable object to the unicode format. Note that one needs to encode it back to utf-8 before writing to disk or printing. Note that non-string objects are let through without conversion - this is important for e.g. Attributes. Use force_string to enforce conversion of objects to string. . """ if force_string and not isinstance(obj, basestring): # some sort of other object. Try to # convert it to a string representation. if hasattr(obj, '__str__'): obj = obj.__str__() elif hasattr(obj, '__unicode__'): obj = obj.__unicode__() else: # last resort obj = str(obj) if isinstance(obj, basestring) and not isinstance(obj, unicode): try: obj = unicode(obj, encoding) return obj except UnicodeDecodeError: for alt_encoding in ENCODINGS: try: obj = unicode(obj, alt_encoding) return obj except UnicodeDecodeError: pass raise Exception("Error: '%s' contains invalid character(s) not in %s." % (obj, encoding)) return obj def to_str(obj, encoding='utf-8', force_string=False): """ This encodes a unicode string back to byte-representation, for printing, writing to disk etc. Note that non-string objects are let through without modification - this is required e.g. for Attributes. Use force_string to force conversion of objects to strings. """ if force_string and not isinstance(obj, basestring): # some sort of other object. Try to # convert it to a string representation. if hasattr(obj, '__str__'): obj = obj.__str__() elif hasattr(obj, '__unicode__'): obj = obj.__unicode__() else: # last resort obj = str(obj) if isinstance(obj, basestring) and isinstance(obj, unicode): try: obj = obj.encode(encoding) return obj except UnicodeEncodeError: for alt_encoding in ENCODINGS: try: obj = obj.encode(encoding) return obj except UnicodeEncodeError: pass raise Exception("Error: Unicode could not encode unicode string '%s'(%s) to a bytestring. " % (obj, encoding)) return obj def validate_email_address(emailaddress): """ Checks if an email address is syntactically correct. (This snippet was adapted from http://commandline.org.uk/python/email-syntax-check.) """ emailaddress = r"%s" % emailaddress domains = ("aero", "asia", "biz", "cat", "com", "coop", "edu", "gov", "info", "int", "jobs", "mil", "mobi", "museum", "name", "net", "org", "pro", "tel", "travel") # Email address must be more than 7 characters in total. if len(emailaddress) < 7: return False # Address too short. # Split up email address into parts. try: localpart, domainname = emailaddress.rsplit('@', 1) host, toplevel = domainname.rsplit('.', 1) except ValueError: return False # Address does not have enough parts. # Check for Country code or Generic Domain. if len(toplevel) != 2 and toplevel not in domains: return False # Not a domain name. for i in '-_.%+.': localpart = localpart.replace(i, "") for i in '-_.': host = host.replace(i, "") if localpart.isalnum() and host.isalnum(): return True # Email address is fine. else: return False # Email address has funny characters. def inherits_from(obj, parent): """ Takes an object and tries to determine if it inherits at any distance from parent. What differs this function from e.g. isinstance() is that obj may be both an instance and a class, and parent < may be an instance, a class, or the python path to a class (counting from the evennia root directory). """ if callable(obj): # this is a class obj_paths = ["%s.%s" % (mod.__module__, mod.__name__) for mod in obj.mro()] else: obj_paths = ["%s.%s" % (mod.__module__, mod.__name__) for mod in obj.__class__.mro()] if isinstance(parent, basestring): # a given string path, for direct matching parent_path = parent elif callable(parent): # this is a class parent_path = "%s.%s" % (parent.__module__, parent.__name__) else: parent_path = "%s.%s" % (parent.__class__.__module__, parent.__class__.__name__) return any(1 for obj_path in obj_paths if obj_path == parent_path) def format_table(table, extra_space=1): """ Takes a table of collumns: [[val,val,val,...], [val,val,val,...], ...] where each val will be placed on a separate row in the column. All collumns must have the same number of rows (some positions may be empty though). The function formats the columns to be as wide as the widest member of each column. extra_space defines how much extra padding should minimum be left between collumns. print the resulting list e.g. with for ir, row in enumarate(ftable): if ir == 0: # make first row white string += "\n{w" + ""join(row) + "{n" else: string += "\n" + "".join(row) print string """ if not table: return [[]] max_widths = [max([len(str(val)) for val in col]) for col in table] ftable = [] for irow in range(len(table[0])): ftable.append([str(col[irow]).ljust(max_widths[icol]) + " " * extra_space for icol, col in enumerate(table)]) return ftable def run_async(async_func, at_return=None, at_err=None): """ This wrapper will use Twisted's asynchronous features to run a slow function using a separate reactor thread. In effect this means that the server will not be blocked while the slow process finish. Use this function with restrain and only for features/commands that you know has no influence on the cause-and-effect order of your game (commands given after the async function might be executed before it has finished). async_func() - function that should be run asynchroneously at_return(r) - if given, this function will be called when async_func returns value r at the end of a successful execution at_err(e) - if given, this function is called if async_func fails with an exception e. use e.trap(ExceptionType1, ExceptionType2) """ # create deferred object deferred = threads.deferToThread(async_func) if at_return: deferred.addCallback(at_return) if at_err: deferred.addErrback(at_err) # always add a logging errback as a last catch def default_errback(e): from src.utils import logger logger.log_trace(e) deferred.addErrback(default_errback) def check_evennia_dependencies(): """ Checks the versions of Evennia's dependencies. Returns False if a show-stopping version mismatch is found. """ # defining the requirements python_min = '2.5' twisted_min = '10.0' django_min = '1.2' south_min = '0.7' nt_stop_python_min = '2.7' errstring = "" no_error = True # Python pversion = ".".join([str(num) for num in sys.version_info if type(num) == int]) if pversion < python_min: errstring += "\n WARNING: Python %s used. Evennia recommends version %s or higher (but not 3.x)." % (pversion, python_min) if os.name == 'nt' and pversion < nt_stop_python_min: errstring += "\n WARNING: Windows requires Python %s or higher in order to restart/stop the server from the command line." errstring += "\n (You need to restart/stop from inside the game.)" % nt_stop_python_min # Twisted try: import twisted tversion = twisted.version.short() if tversion < twisted_min: errstring += "\n WARNING: Twisted %s found. Evennia recommends version %s or higher." % (twisted.version.short(), twisted_min) except ImportError: errstring += "\n ERROR: Twisted does not seem to be installed." no_error = False # Django try: import django dversion = ".".join([str(num) for num in django.VERSION if type(num) == int]) if dversion < django_min: errstring += "\n ERROR: Django version %s found. Evennia requires version %s or higher." % (dversion, django_min) no_error = False except ImportError: errstring += "\n ERROR: Django does not seem to be installed." no_error = False # South try: import south sversion = south.__version__ if sversion < south_min: errstring += "\n WARNING: South version %s found. Evennia recommends version %s or higher." % (sversion, south_min) except ImportError: pass # IRC support if settings.IRC_ENABLED: try: import twisted.words except ImportError: errstring += "\n ERROR: IRC is enabled, but twisted.words is not installed. Please install it." errstring += "\n Linux Debian/Ubuntu users should install package 'python-twisted-words', others" errstring += "\n can get it from http://twistedmatrix.com/trac/wiki/TwistedWords." no_error = False errstring = errstring.strip() if errstring: print "%s\n %s\n%s" % ("-"*78, errstring, '-'*78) return no_error def has_parent(basepath, obj): "Checks if basepath is somewhere in objs parent tree." try: return any(cls for cls in obj.__class__.mro() if basepath == "%s.%s" % (cls.__module__, cls.__name__)) except (TypeError, AttributeError): # this can occur if we tried to store a class object, not an # instance. Not sure if one should defend against this. return False def mod_import(mod_path, propname=None): """ Takes filename of a module (a python path or a full pathname) and imports it. If property is given, return the named property from this module instead of the module itself. """ def log_trace(errmsg=None): """ Log a traceback to the log. This should be called from within an exception. errmsg is optional and adds an extra line with added info. """ from traceback import format_exc from twisted.python import log print errmsg tracestring = format_exc() if tracestring: for line in tracestring.splitlines(): log.msg('[::] %s' % line) if errmsg: try: errmsg = to_str(errmsg) except Exception, e: errmsg = str(e) for line in errmsg.splitlines(): log.msg('[EE] %s' % line) # first try to import as a python path try: mod = __import__(mod_path, fromlist=["None"]) except ImportError: # try absolute path import instead if not os.path.isabs(mod_path): mod_path = os.path.abspath(mod_path) path, filename = mod_path.rsplit(os.path.sep, 1) modname = filename.rstrip('.py') try: result = imp.find_module(modname, [path]) except ImportError: log_trace("Could not find module '%s' (%s.py) at path '%s'" % (modname, modname, path)) return try: mod = imp.load_module(modname, *result) except ImportError: log_trace("Could not find or import module %s at path '%s'" % (modname, path)) mod = None # we have to close the file handle manually result[0].close() if mod and propname: # we have a module, extract the sought property from it. try: mod_prop = mod.__dict__[to_str(propname)] except KeyError: log_trace("Could not import property '%s' from module %s." % (propname, mod_path)) return None return mod_prop return mod def variable_from_module(modpath, variable, default=None): """ Retrieve a given variable from a module. The variable must be defined globally in the module. This can be used to implement arbitrary plugin imports in the server. If module cannot be imported or variable not found, default is returned. """ try: mod = __import__(modpath, fromlist=["None"]) return mod.__dict__.get(variable, default) except ImportError: return default def string_from_module(modpath, variable=None, default=None): """ This is a variation used primarily to get login screens randomly from a module. This obtains a string from a given module python path. Using a specific variable name will also retrieve non-strings. The variable must be global within that module - that is, defined in the outermost scope of the module. The value of the variable will be returned. If not found, default is returned. If no variable is given, a random string variable is returned. This is useful primarily for storing various game strings in a module and extract them by name or randomly. """ mod = __import__(modpath, fromlist=[None]) if variable: return mod.__dict__.get(variable, default) else: mvars = [val for key, val in mod.__dict__.items() if not key.startswith('_') and isinstance(val, basestring)] if not mvars: return default return mvars[random.randint(0, len(mvars)-1)] def init_new_player(player): """ Helper method to call all hooks, set flags etc on a newly created player (and potentially their character, if it exists already) """ # the FIRST_LOGIN flags are necessary for the system to call # the relevant first-login hooks. if player.character: player.character.db.FIRST_LOGIN = True player.db.FIRST_LOGIN = True
Python
""" Dummy client runner This module implements a stand-alone launcher for stress-testing an Evennia game. It will launch any number of fake clients. These clients will log into the server and start doing random operations. Customizing and weighing these operations differently depends on which type of game is tested. The module contains a testing module for plain Evennia. Please note that you shouldn't run this on a production server! Launch the program without any arguments or options to see a full step-by-step setup help. Basically (for testing default Evennia): - Use an empty/testing database. - set PERMISSION_PLAYERS_DEFAULT = "Builders" - start server, eventually with profiling active - launch this client runner If you want to customize the runner's client actions (because you changed the cmdset or needs to better match your use cases or add more actions), you can change which actions by adding a path to DUMMYRUNNER_ACTIONS_MODULE = <path.to.your.module> in your settings. See utils.dummyrunner_actions.py for instructions on how to define this module. """ import os, sys, time, random from optparse import OptionParser from twisted.conch import telnet from twisted.internet import reactor, protocol # from twisted.application import internet, service # from twisted.web import client from twisted.internet.task import LoopingCall # Tack on the root evennia directory to the python path and initialize django settings sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) from django.core.management import setup_environ from game import settings setup_environ(settings) from django.conf import settings from src.utils import utils HELPTEXT = """ DO NOT RUN THIS ON A PRODUCTION SERVER! USE A CLEAN/TESTING DATABASE! This stand-alone program launches dummy telnet clients against a running Evennia server. The idea is to mimic real players logging in and repeatedly doing resource-heavy commands so as to stress test the game. It uses the default command set to log in and issue commands, so if that was customized, some of the functionality will not be tested (it will not fail, the commands will just not be recognized). The running clients will create new objects and rooms all over the place as part of their running, so using a clean/testing database is strongly recommended. Setup: 1) setup a fresh/clean database (if using sqlite, just safe-copy away your real evennia.db3 file and create a new one with manage.py) 2) in game/settings.py, add PERMISSION_PLAYER_DEFAULT="Builders" 3a) Start Evennia like normal. 3b) If you want profiling, start Evennia like this instead: python runner.py -S start this will start Evennia under cProfiler with output server.prof. 4) run this dummy runner: python dummyclients.py <nr_of_clients> [timestep] [port] Default is to connect one client to port 4000, using a 5 second timestep. Increase the number of clients and shorten the timestep (minimum is 1s) to further stress the game. You can stop the dummy runner with Ctrl-C. 5) Log on and determine if game remains responsive despite the heavier load. Note that if you do profiling, there is an additional overhead from the profiler too! 6) If you use profiling, let the game run long enough to gather data, then stop the server. You can inspect the server.prof file from a python prompt (see Python's manual on cProfiler). """ #------------------------------------------------------------ # Helper functions #------------------------------------------------------------ def idcounter(): "generates subsequent id numbers" idcount = 0 while True: idcount += 1 yield idcount OID = idcounter() CID = idcounter() def makeiter(obj): "makes everything iterable" if not hasattr(obj, '__iter__'): return [obj] return obj #------------------------------------------------------------ # Client classes #------------------------------------------------------------ class DummyClient(telnet.StatefulTelnetProtocol): """ Handles connection to a running Evennia server, mimicking a real player by sending commands on a timer. """ def connectionMade(self): # public properties self.cid = CID.next() self.istep = 0 self.exits = [] # exit names created self.objs = [] # obj names created self._actions = self.factory.actions self._echo_brief = self.factory.verbose == 1 self._echo_all = self.factory.verbose == 2 print " ** client %i connected successfully." % self.cid # start client tick d = LoopingCall(self.step) d.start(self.factory.timestep, now=True).addErrback(self.error) def dataReceived(self, data): "Echo incoming data to stdout" if self._echo_all: print data def connectionLost(self, reason): "loosing the connection" print " ** client %i lost connection." % self.cid def error(self, err): "error callback" print err def counter(self): "produces a unique id, also between clients" return OID.next() def step(self): """ Perform a step. This is called repeatedly by the runner and causes the client to issue commands to the server. This holds all "intelligence" of the dummy client. """ if self.istep == 0: cfunc = self._actions[0] else: # random selection using cumulative probabilities rand = random.random() cfunc = [func for cprob, func in self._actions[1] if cprob >= rand][0] # launch the action (don't hide tracebacks) cmd, report = cfunc(self) # handle the result cmd = "\n".join(makeiter(cmd)) if self._echo_brief or self._echo_all: print "client %i %s" % (self.cid, report) self.sendLine(cmd) self.istep += 1 class DummyFactory(protocol.ClientFactory): protocol = DummyClient def __init__(self, actions, timestep, verbose): "Setup the factory base (shared by all clients)" self.actions = actions self.timestep = timestep self.verbose = verbose #------------------------------------------------------------ # Access method: # Starts clients and connects them to a running server. #------------------------------------------------------------ def start_all_dummy_clients(actions, nclients=1, timestep=5, telnet_port=4000, verbose=0): # validating and preparing the action tuple # make sure the probabilities add up to 1 pratio = 1.0 / sum(tup[0] for tup in actions[1:]) flogin, probs, cfuncs = actions[0], [tup[0] * pratio for tup in actions[1:]], [tup[1] for tup in actions[1:]] # create cumulative probabilies for the random actions cprobs = [sum(v for i,v in enumerate(probs) if i<=k) for k in range(len(probs))] # rebuild a new, optimized action structure actions = (flogin, zip(cprobs, cfuncs)) # setting up all clients (they are automatically started) factory = DummyFactory(actions, timestep, verbose) for i in range(nclients): reactor.connectTCP("localhost", telnet_port, factory) # start reactor reactor.run() #------------------------------------------------------------ # Command line interface #------------------------------------------------------------ if __name__ == '__main__': # parsing command line with default vals parser = OptionParser(usage="%prog [options] <nclients> [timestep, [port]]", description="This program requires some preparations to run properly. Start it without any arguments or options for full help.") parser.add_option('-v', '--verbose', action='store_const', const=1, dest='verbose', default=0,help="echo brief description of what clients do every timestep.") parser.add_option('-V', '--very-verbose', action='store_const',const=2, dest='verbose', default=0,help="echo all client returns to stdout (hint: use only with nclients=1!)") options, args = parser.parse_args() nargs = len(args) nclients = 1 timestep = 5 port = 4000 try: if not args : raise Exception if nargs > 0: nclients = max(1, int(args[0])) if nargs > 1: timestep = max(1, int(args[1])) if nargs > 2: port = int(args[2]) except Exception: print HELPTEXT sys.exit() # import the ACTION tuple from a given module try: action_modpath = settings.DUMMYRUNNER_ACTIONS_MODULE except AttributeError: # use default action_modpath = "src.utils.dummyrunner_actions" actions = utils.mod_import(action_modpath, "ACTIONS") print "Connecting %i dummy client(s) to port %i using a %i second timestep ... " % (nclients, port, timestep) start_all_dummy_clients(actions, nclients, timestep, port, verbose=options.verbose) print "... dummy client runner finished."
Python
""" This file contains the core methods for the Batch-command- and Batch-code-processors respectively. In short, these are two different ways to build a game world using a normal text-editor without having to do so 'on the fly' in-game. They also serve as an automatic backup so you can quickly recreate a world also after a server reset. The functions in this module is meant to form the backbone of a system called and accessed through game commands. The Batch-command processor is the simplest. It simply runs a list of in-game commands in sequence by reading them from a text file. The advantage of this is that the builder only need to remember the normal in-game commands. They are also executing with full permission checks etc, making it relatively safe for builders to use. The drawback is that in-game there is really a builder-character walking around building things, and it can be important to create rooms and objects in the right order, so the character can move between them. Also objects that affects players (such as mobs, dark rooms etc) will affect the building character too, requiring extra care to turn off/on. The Batch-code processor is a more advanced system that accepts full Python code, executing in chunks. The advantage of this is much more power; practically anything imaginable can be coded and handled using the batch-code processor. There is no in-game character that moves and that can be affected by what is being built - the database is populated on the fly. The drawback is safety and entry threshold - the code is executed as would any server code, without mud-specific permission checks and you have full access to modifying objects etc. You also need to know Python and Evennia's API. Hence it's recommended that the batch-code processor is limited only to superusers or highly trusted staff. Batch-command processor file syntax The batch-command processor accepts 'batchcommand files' e.g 'batch.ev', containing a sequence of valid evennia commands in a simple format. The engine runs each command in sequence, as if they had been run at the game prompt. This way entire game worlds can be created and planned offline; it is especially useful in order to create long room descriptions where a real offline text editor is often much better than any online text editor or prompt. Example of batch.ev file: ---------------------------- # batch file # all lines starting with # are comments; they also indicate # that a command definition is over. @create box # this comment ends the @create command. @set box/desc = A large box. Inside are some scattered piles of clothing. It seems the bottom of the box is a bit loose. # Again, this comment indicates the @set command is over. Note how # the description could be freely added. Excess whitespace on a line # is ignored. An empty line in the command definition is parsed as a \n # (so two empty lines becomes a new paragraph). @teleport #221 # (Assuming #221 is a warehouse or something.) # (remember, this comment ends the @teleport command! Don'f forget it) @drop box # Done, the box is in the warehouse! (this last comment is not necessary to # close the @drop command since it's the end of the file) ------------------------- An example batch file is game/gamesrc/commands/examples/batch_example.ev. Batch-code processor file syntax The Batch-code processor accepts full python modules (e.g. "batch.py") that looks identical to normal Python files with a few exceptions that allows them to the executed in blocks. This way of working assures a sequential execution of the file and allows for features like stepping from block to block (without executing those coming before), as well as automatic deletion of created objects etc. You can however also run a batch-code python file directly using Python (and can also be de). Code blocks are separated by python comments starting with special code words. #HEADER - this denotes commands global to the entire file, such as import statements and global variables. They will automatically be pasted at the top of all code blocks. Observe that changes to these variables made in one block is not preserved between blocks! #CODE [objname, objname, ...] - This designates a code block that will be executed like a stand-alone piece of code together with any #HEADER defined. <objname>s mark the (variable-)names of objects created in the code, and which may be auto-deleted by the processor if desired (such as when debugging the script). E.g., if the code contains the command myobj = create.create_object(...), you could put 'myobj' in the #CODE header regardless of what the created object is actually called in-game. The following variables are automatically made available for the script: caller - the object executing the script Example batch.py file ----------------------------------- #HEADER import traceback from django.config import settings from src.utils import create from game.gamesrc.typeclasses import basetypes GOLD = 10 #CODE obj, obj2 obj = create.create_object(basetypes.Object) obj2 = create.create_object(basetypes.Object) obj.location = caller.location obj.db.gold = GOLD caller.msg("The object was created!") #CODE script = create.create_script() """ import re import codecs from traceback import format_exc from django.conf import settings from django.core.management import setup_environ from src.utils import logger from src.utils import utils from game import settings as settings_module ENCODINGS = settings.ENCODINGS #------------------------------------------------------------ # Helper function #------------------------------------------------------------ def read_batchfile(pythonpath, file_ending='.py'): """ This reads the contents of a batch-file. Filename is considered to be the name of the batch file relative the directory specified in settings.py. file_ending specify which batchfile ending should be assumed (.ev or .py). """ # open the file if pythonpath and not (pythonpath.startswith('src.') or pythonpath.startswith('game.') or pythonpath.startswith('contrib.')): abspaths = [] for basepath in settings.BASE_BATCHPROCESS_PATHS: abspaths.append(utils.pypath_to_realpath("%s.%s" % (basepath, pythonpath), file_ending)) else: abspaths = [utils.pypath_to_realpath(pythonpath, file_ending)] fobj, lines, err = None, [], None for file_encoding in ENCODINGS: # try different encodings, in order load_errors = [] for abspath in abspaths: # try different paths, until we get a match try: # we read the file directly into unicode. fobj = codecs.open(abspath, 'r', encoding=file_encoding) except IOError: load_errors.append("Could not open batchfile '%s'." % abspath) continue break if not fobj: continue load_errors = [] err =None # We have successfully found and opened the file. Now actually # try to decode it using the given protocol. try: lines = fobj.readlines() except UnicodeDecodeError: # give the line of failure fobj.seek(0) try: lnum = 0 for lnum, line in enumerate(fobj): pass except UnicodeDecodeError, err: # lnum starts from 0, so we add +1 line, # besides the faulty line is never read # so we add another 1 (thus +2) to get # the actual line number seen in an editor. err.linenum = lnum + 2 fobj.close() # possibly try another encoding continue # if we get here, the encoding worked. Stop iteration. break if load_errors: logger.log_errmsg("\n".join(load_errors)) if err: return err else: return lines #------------------------------------------------------------ # # Batch-command processor # #------------------------------------------------------------ class BatchCommandProcessor(object): """ This class implements a batch-command processor. """ def parse_file(self, pythonpath): """ This parses the lines of a batchfile according to the following rules: 1) # at the beginning of a line marks the end of the command before it. It is also a comment and any number of # can exist on subsequent lines (but not inside comments). 2) Commands are placed alone at the beginning of a line and their arguments are considered to be everything following (on any number of lines) until the next comment line beginning with #. 3) Newlines are ignored in command definitions 4) A completely empty line in a command line definition is condered a newline (so two empty lines is a paragraph). 5) Excess spaces and indents inside arguments are stripped. """ #helper function def identify_line(line): """ Identifies the line type (comment, commanddef or empty) """ try: if line.strip()[0] == '#': return "comment" else: return "commanddef" except IndexError: return "empty" #read the indata, if possible. lines = read_batchfile(pythonpath, file_ending='.ev') #line = utils.to_unicode(line) if not lines: return None commands = [] curr_cmd = "" #purge all superfluous whitespace and newlines from lines reg1 = re.compile(r"\s+") lines = [reg1.sub(" ", l) for l in lines] #parse all command definitions into a list. for line in lines: typ = identify_line(line) if typ == "commanddef": curr_cmd += line elif typ == "empty" and curr_cmd: curr_cmd += "\r\n" else: #comment if curr_cmd: commands.append(curr_cmd.strip()) curr_cmd = "" if curr_cmd: commands.append(curr_cmd.strip()) #second round to clean up now merged line edges etc. reg2 = re.compile(r"[ \t\f\v]+") commands = [reg2.sub(" ", c) for c in commands] #remove eventual newline at the end of commands commands = [c.strip('\r\n') for c in commands] return commands #------------------------------------------------------------ # # Batch-code processor # #------------------------------------------------------------ class BatchCodeProcessor(object): """ This implements a batch-code processor """ def parse_file(self, pythonpath): """ This parses the lines of a batchfile according to the following rules: 1) Lines starting with #HEADER starts a header block (ends other blocks) 2) Lines starting with #CODE begins a code block (ends other blocks) 3) #CODE headers may be of the following form: #CODE (info) objname, objname2, ... 3) All lines outside blocks are stripped. 4) All excess whitespace beginning/ending a block is stripped. """ # helper function def parse_line(line): """ Identifies the line type: block command, comment, empty or normal code. """ line = line.strip() if line.startswith("#HEADER"): return ("header", "", "") elif line.startswith("#CODE"): # parse code command line = line.lstrip("#CODE").strip() objs = [] info = "" if line and '(' in line and ')' in line: # a code description lp = line.find('(') rp = line.find(')') info = line[lp:rp+1] line = line[rp+1:] if line: objs = [obj.strip() for obj in line.split(',')] return ("codeheader", info, objs) elif line.startswith('#'): return ('comment', "", "\n%s" % line) else: #normal line - return it with a line break. return ('line', "", "\n%s" % line) # read indata lines = read_batchfile(pythonpath, file_ending='.py') if not lines: return None # parse file into blocks header = "" codes = [] in_header = False in_code = False for line in lines: # parse line mode, info, line = parse_line(line) # try: # print "::", in_header, in_code, mode, line.strip() # except: # print "::", in_header, in_code, mode, line if mode == 'header': in_header = True in_code = False elif mode == 'codeheader': in_header = False in_code = True # the line is a list of object variable names # (or an empty list) at this point. codedict = {'objs':line, 'info':info, 'code':""} codes.append(codedict) elif mode == 'comment' and in_header: continue else: # another type of line (empty, comment or code) if line and in_header: header += line elif line and in_code: codes[-1]['code'] += line else: # not in a block (e.g. first in file). Ignore. continue # last, we merge the headers with all codes. for codedict in codes: codedict["code"] = "#CODE %s %s\n%s\n\n%s" % (codedict['info'], ", ".join(codedict["objs"]), header.strip(), codedict["code"].strip()) return codes def code_exec(self, codedict, extra_environ=None, debug=False): """ Execute a single code block, including imports and appending global vars extra_environ - dict with environment variables """ # define the execution environment environ = "setup_environ(settings_module)" environdict = {"setup_environ":setup_environ, "settings_module":settings_module} if extra_environ: for key, value in extra_environ.items(): environdict[key] = value # merge all into one block code = "%s\n%s" % (environ, codedict['code']) if debug: # try to delete marked objects for obj in codedict['objs']: code += "\ntry: %s.delete()\nexcept: pass" % obj # execute the block try: exec(code, environdict) except Exception: errlist = format_exc().split('\n') if len(errlist) > 4: errlist = errlist[4:] err = "\n".join(" %s" % line for line in errlist if line) if debug: # try to delete objects again. try: for obj in codedict['objs']: eval("%s.delete()" % obj, environdict) except Exception: pass return err return None BATCHCMD = BatchCommandProcessor() BATCHCODE = BatchCodeProcessor()
Python
""" ANSI - Gives colour to text. Use the codes defined in ANSIPARSER in your text to apply colour to text according to the ANSI standard. Examples: This is %crRed text%cn and this is normal again. This is {rRed text{n and this is normal again. Mostly you should not need to call parse_ansi() explicitly; it is run by Evennia just before returning data to/from the user. """ import re from src.utils import utils # ANSI definitions ANSI_BEEP = "\07" ANSI_ESCAPE = "\033" ANSI_NORMAL = "\033[0m" ANSI_UNDERLINE = "\033[4m" ANSI_HILITE = "\033[1m" ANSI_BLINK = "\033[5m" ANSI_INVERSE = "\033[7m" ANSI_INV_HILITE = "\033[1;7m" ANSI_INV_BLINK = "\033[7;5m" ANSI_BLINK_HILITE = "\033[1;5m" ANSI_INV_BLINK_HILITE = "\033[1;5;7m" # Foreground colors ANSI_BLACK = "\033[30m" ANSI_RED = "\033[31m" ANSI_GREEN = "\033[32m" ANSI_YELLOW = "\033[33m" ANSI_BLUE = "\033[34m" ANSI_MAGENTA = "\033[35m" ANSI_CYAN = "\033[36m" ANSI_WHITE = "\033[37m" # Background colors ANSI_BACK_BLACK = "\033[40m" ANSI_BACK_RED = "\033[41m" ANSI_BACK_GREEN = "\033[42m" ANSI_BACK_YELLOW = "\033[43m" ANSI_BACK_BLUE = "\033[44m" ANSI_BACK_MAGENTA = "\033[45m" ANSI_BACK_CYAN = "\033[46m" ANSI_BACK_WHITE = "\033[47m" # Formatting Characters ANSI_RETURN = "\r\n" ANSI_TAB = "\t" ANSI_SPACE = " " class ANSIParser(object): """ A class that parses ansi markup to ANSI command sequences """ def __init__(self): "Sets the mappings" # MUX-style mappings %cr %cn etc self.mux_ansi_map = [ (r'%r', ANSI_RETURN), (r'%t', ANSI_TAB), (r'%b', ANSI_SPACE), (r'%cf', ANSI_BLINK), (r'%ci', ANSI_INVERSE), (r'%ch', ANSI_HILITE), (r'%cn', ANSI_NORMAL), (r'%cx', ANSI_BLACK), (r'%cX', ANSI_BACK_BLACK), (r'%cr', ANSI_RED), (r'%cR', ANSI_BACK_RED), (r'%cg', ANSI_GREEN), (r'%cG', ANSI_BACK_GREEN), (r'%cy', ANSI_YELLOW), (r'%cY', ANSI_BACK_YELLOW), (r'%cb', ANSI_BLUE), (r'%cB', ANSI_BACK_BLUE), (r'%cm', ANSI_MAGENTA), (r'%cM', ANSI_BACK_MAGENTA), (r'%cc', ANSI_CYAN), (r'%cC', ANSI_BACK_CYAN), (r'%cw', ANSI_WHITE), (r'%cW', ANSI_BACK_WHITE), ] # Expanded mapping {r {n etc hilite = ANSI_HILITE normal = ANSI_NORMAL self.ext_ansi_map = [ (r'{r', hilite + ANSI_RED), (r'{R', normal + ANSI_RED), (r'{g', hilite + ANSI_GREEN), (r'{G', normal + ANSI_GREEN), (r'{y', hilite + ANSI_YELLOW), (r'{Y', normal + ANSI_YELLOW), (r'{b', hilite + ANSI_BLUE), (r'{B', normal + ANSI_BLUE), (r'{m', hilite + ANSI_MAGENTA), (r'{M', normal + ANSI_MAGENTA), (r'{c', hilite + ANSI_CYAN), (r'{C', normal + ANSI_CYAN), (r'{w', hilite + ANSI_WHITE), # pure white (r'{W', normal + ANSI_WHITE), #light grey (r'{x', hilite + ANSI_BLACK), #dark grey (r'{X', normal + ANSI_BLACK), #pure black (r'{n', normal) #reset ] # xterm256 {123, %c134, self.xterm256_map = [ (r'%c([1-5]{3})', self.parse_rgb), # %c123 - foreground colour (r'%c(b[1-5]{3})', self.parse_rgb), # %cb123 - background colour (r'{([1-5]{3})', self.parse_rgb), # {123 - foreground colour (r'{(b[1-5]{3})', self.parse_rgb) # {b123 - background colour ] # obs - order matters here, we want to do the xterms first since # they collide with some of the other mappings otherwise. self.ansi_map = self.xterm256_map + self.mux_ansi_map + self.ext_ansi_map # 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") def parse_rgb(self, rgbmatch): """ This is a replacer method called by re.sub with the matched tag. It must return the correct ansi sequence. It checks self.do_xterm256 to determine if conversion to standard ansi should be done or not. """ if not rgbmatch: return "" rgbtag = rgbmatch.groups()[0] background = rgbtag[0] == 'b' if background: red, green, blue = int(rgbtag[1]), int(rgbtag[2]), int(rgbtag[3]) else: red, green, blue = int(rgbtag[0]), int(rgbtag[1]), int(rgbtag[2]) if self.do_xterm256: colval = 16 + (red * 36) + (green * 6) + blue return "\033[%s8;5;%s%s%sm" % (3 + int(background), colval/100, (colval%100)/10, colval%10) else: # xterm256 not supported, convert the rgb value to ansi instead if red == green and red == blue and red < 2: if background: return ANSI_BACK_BLACK elif red >= 1: return ANSI_HILITE + ANSI_BLACK else: return ANSO_NORMAL + ANSI_BLACK elif red == green and red == blue: if background: return ANSI_BACK_WHITE elif red >= 4: return ANSI_HILITE + ANSI_WHITE else: return ANSI_NORMAL + ANSI_WHITE elif red > green and red > blue: if background: return ANSI_BACK_RED elif red >= 3: return ANSI_HILITE + ANSI_RED else: return ANSI_NORMAL + ANSI_RED elif red == green and red > blue: if background: return ANSI_BACK_YELLOW elif red >= 3: return ANSI_HILITE + ANSI_YELLOW else: return ANSI_NORMAL + ANSI_YELLOW elif red == blue and red > green: if background: return ANSI_BACK_MAGENTA elif red >= 3: return ANSI_HILITE + ANSI_MAGENTA else: return ANSI_NORMAL + ANSI_MAGENTA elif green > blue: if background: return ANSI_BACK_GREEN elif green >= 3: return ANSI_HILITE + ANSI_GREEN else: return ANSI_NORMAL + ANSI_GREEN elif green == blue: if background: return ANSI_BACK_CYAN elif green >= 3: return ANSI_HILITE + ANSI_CYAN else: return ANSI_NORMAL + ANSI_CYAN else: # mostly blue if background: return ANSI_BACK_BLUE elif blue >= 3: return ANSI_HILITE + ANSI_BLUE else: return ANSI_NORMAL + ANSI_BLUE def parse_ansi(self, string, strip_ansi=False, xterm256=False): """ Parses a string, subbing color codes according to the stored mapping. strip_ansi flag instead removes all ansi markup. """ if not string: return '' string = utils.to_str(string) self.do_xterm256 = xterm256 # handle all subs for sub in self.ansi_sub: # go through all available mappings and translate them string = sub[0].sub(sub[1], string) if strip_ansi: # remove all ANSI escape codes string = self.ansi_regex.sub("", string) return string ANSI_PARSER = ANSIParser() # # Access function # def parse_ansi(string, strip_ansi=False, parser=ANSI_PARSER, xterm256=False): """ Parses a string, subbing color codes as needed. """ return parser.parse_ansi(string, strip_ansi=strip_ansi, xterm256=xterm256)
Python
""" Logging facilities This file should have an absolute minimum in imports. If you'd like to layer additional functionality on top of some of the methods below, wrap them in a higher layer module. """ from traceback import format_exc from twisted.python import log from src.utils import utils def log_trace(errmsg=None): """ Log a traceback to the log. This should be called from within an exception. errmsg is optional and adds an extra line with added info. """ tracestring = format_exc() try: if tracestring: for line in tracestring.splitlines(): log.msg('[::] %s' % line) if errmsg: try: errmsg = utils.to_str(errmsg) except Exception, e: errmsg = str(e) for line in errmsg.splitlines(): log.msg('[EE] %s' % line) except Exception: log.msg('[EE] %s' % errmsg ) def log_errmsg(errmsg): """ Prints/logs an error message to the server log. errormsg: (string) The message to be logged. """ try: errmsg = utils.to_str(errmsg) except Exception, e: errmsg = str(e) for line in errmsg.splitlines(): log.msg('[EE] %s' % line) #log.err('ERROR: %s' % (errormsg,)) def log_warnmsg(warnmsg): """ Prints/logs any warnings that aren't critical but should be noted. warnmsg: (string) The message to be logged. """ try: warnmsg = utils.to_str(warnmsg) except Exception, e: warnmsg = str(e) for line in warnmsg.splitlines(): log.msg('[WW] %s' % line) #log.msg('WARNING: %s' % (warnmsg,)) def log_infomsg(infomsg): """ Prints any generic debugging/informative info that should appear in the log. infomsg: (string) The message to be logged. """ try: infomsg = utils.to_str(infomsg) except Exception, e: infomsg = str(e) for line in infomsg.splitlines(): log.msg('[..] %s' % line) def log_depmsg(depmsg): """ Prints a deprecation message """ try: depmsg = utils.to_str(depmsg) except Exception, e: depmsg = str(e) for line in depmsg.splitlines(): log.msg('[DP] %s' % line)
Python
""" Debug mechanisms for easier developing advanced game objects The functions in this module are intended to stress-test various aspects of an in-game entity, notably objects and scripts, during development. This allows to run several automated tests on the entity without having to do the testing by creating/deleting etc in-game. The default Evennia accesses the methods of this module through a special state and cmdset, using the @debug command. """ from traceback import format_exc from src.utils import create def trace(): "Format the traceback." errlist = format_exc().split('\n') if len(errlist) > 4: errlist = errlist[4:] ret = "\n" + "\n".join("<<< {r%s{n" % line for line in errlist if line) return ret # # Testing scripts # def debug_script(script_path, obj=None, auto_delete=True): """ This function takes a script database object (ScriptDB) and tests all its hooks for syntax errors. Note that no run-time errors will be caught, only weird python syntax. script_path - the full path to the script typeclass module and class. """ try: string = "Test-creating a new script of this type ... " scriptobj = create.create_script(script_path, autostart=False) scriptobj.obj = obj scriptobj.save() string += "{gOk{n." except Exception: string += trace() try: scriptobj.delete() except: pass return string string += "\nRunning syntax check ..." try: string += "\nTesting syntax of at_script_creation(self) ... " ret = scriptobj.at_script_creation() string += "{gOk{n." except Exception: string += trace() try: string += "\nTesting syntax of is_valid(self) ... " ret = scriptobj.is_valid() string += "{gOk{n." except Exception: string += trace() try: string += "\nTesting syntax of at_start(self) ... " ret = scriptobj.at_start() string += "{gOk{n." except Exception: string += trace() try: string += "\nTesting syntax of at_repeat(self) ... " ret = scriptobj.at_repeat() string += "{gOk{n." except Exception: string += trace() try: string += "\nTesting syntax of at_stop(self) ... " ret = scriptobj.at_script_creation() string += "{gOk{n." except Exception: string += trace() if auto_delete: try: scriptobj.delete() except: string += trace() return string # # Testing objects # def debug_object(obj_path, caller): """ Auto-test an object's hooks and methods. """ try: string = "\n Test-creating a new object of path {w%s{n ... " % obj_path obj = create.create_object(obj_path) obj.location = caller.location string += "{gOk{n." except Exception: string += trace() try: obj.delete() except: pass return string string += "\nRunning syntax checks ..." try: string += "\nCalling at_first_login(self) ... " ret = obj.at_first_login() string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_pre_login(self) ... " ret = obj.at_pre_login() string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_post_login(self) ... " ret = obj.at_post_login() string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_disconnect(self) ... " ret = obj.at_disconnect() string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_before_move(self, dest) ... " ret = obj.at_before_move(caller.location) string += "{gOk{n: returns %s" % ret except Exception: string += trace() try: string += "\nCalling announce_move_from(self, dest) ... " ret = obj.announce_move_from(caller.location) string += "{gOk{n" except Exception: string += trace() try: string += "\nCalling announce_move_to(self, source_loc) ... " ret = obj.announce_move_from(caller.location) string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_after_move(self, source_loc) ... " ret = obj.at_after_move(caller.location) string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_object_receive(self, caller, source_loc) ... " ret = obj.at_object_receive(caller, caller.location) string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling return_appearance(self, caller) ... " ret = obj.return_appearance(caller) string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_msg_receive(self, msg, from_obj) ... " ret = obj.at_msg_receive("test_message_receive", caller) string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_msg_send(self, msg, to_obj) ... " ret = obj.at_msg_send("test_message_send", caller) string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_desc(self, looker) ... " ret = obj.at_desc(caller) string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_object_delete(self) ... " ret = obj.at_object_delete() string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_get(self, getter) ... " ret = obj.at_get(caller) string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_drop(self, dropper) ... " ret = obj.at_drop(caller) string += "{gOk{n." except Exception: string += trace() try: string += "\nCalling at_say(self, speaker, message) ... " ret = obj.at_say(caller, "test_message_say") string += "{gOk{n." except Exception: string += trace() try: obj.delete() except: string += trace() return string def debug_object_scripts(obj_path, caller): """ Create an object and test all its associated scripts independently. """ try: string = "\n Testing scripts on {w%s{n ... " % obj_path obj = create.create_object(obj_path) obj.location = caller.location obj = obj.dbobj string += "{gOk{n." except Exception: string += trace() try: obj.delete() except: pass return string scripts = obj.scripts.all() if scripts: string += "\n Running tests on %i object scripts ... " % (len(scripts)) for script in scripts: string += "\n {wTesting %s{n ..." % script.key path = script.typeclass_path string += debug_script(path, obj=obj) #string += debug_run_script(path, obj=obj) else: string += "\n No scripts defined on object." try: obj.delete() except: string += trace() return string
Python
import os.path import warnings __version__ = (0, 2) def _get_git_revision(path): revision_file = os.path.join(path, 'refs', 'heads', 'master') if not os.path.exists(revision_file): return None fh = open(revision_file, 'r') try: return fh.read() finally: fh.close() def get_revision(): """ :returns: Revision number of this branch/checkout, if available. None if no revision number can be determined. """ package_dir = os.path.dirname(__file__) checkout_dir = os.path.normpath(os.path.join(package_dir, '..')) path = os.path.join(checkout_dir, '.git') if os.path.exists(path): return _get_git_revision(path) return None __build__ = get_revision() def lazy_object(location): def inner(*args, **kwargs): parts = location.rsplit('.', 1) warnings.warn('`idmapper.%s` is deprecated. Please use `%s` instead.' % (parts[1], location), DeprecationWarning) imp = __import__(parts[0], globals(), locals(), [parts[1]], -1) func = getattr(imp, parts[1]) if callable(func): return func(*args, **kwargs) return func return inner SharedMemoryModel = lazy_object('idmapper.models.SharedMemoryModel')
Python
""" This is mostly unmodified from the original idmapper. Evennia changes: The cache mechanism was changed from a WeakValueDictionary to a normal dictionary. The old way caused very hard-to-diagnose bugs over long periods of time (which Evennia requires) added save() overloading mechanism to update cache added get_all_cached_instances() for convenient access to objects """ from django.db.models.base import Model, ModelBase from manager import SharedMemoryManager class SharedMemoryModelBase(ModelBase): #def __new__(cls, name, bases, attrs): # super_new = super(ModelBase, cls).__new__ # parents = [b for b in bases if isinstance(b, SharedMemoryModelBase)] # if not parents: # # If this isn't a subclass of Model, don't do anything special. # print "not a subclass of Model", name, bases # return super_new(cls, name, bases, attrs) # return super(SharedMemoryModelBase, cls).__new__(cls, name, bases, attrs) def __call__(cls, *args, **kwargs): """ this method will either create an instance (by calling the default implementation) or try to retrieve one from the class-wide cache by infering the pk value from args and kwargs. If instance caching is enabled for this class, the cache is populated whenever possible (ie when it is possible to infer the pk value). """ def new_instance(): return super(SharedMemoryModelBase, cls).__call__(*args, **kwargs) #if _get_full_cache: # return cls.__instance_cache__.values() instance_key = cls._get_cache_key(args, kwargs) # depending on the arguments, we might not be able to infer the PK, so in that case we create a new instance if instance_key is None: return new_instance() cached_instance = cls.get_cached_instance(instance_key) if cached_instance is None: cached_instance = new_instance() cls.cache_instance(cached_instance) return cached_instance def _prepare(cls): # this is the core cache cls.__instance_cache__ = {} #WeakValueDictionary() super(SharedMemoryModelBase, cls)._prepare() class SharedMemoryModel(Model): # XXX: this is creating a model and it shouldn't be.. how do we properly # subclass now? __metaclass__ = SharedMemoryModelBase class Meta: abstract = True def _get_cache_key(cls, args, kwargs): """ This method is used by the caching subsystem to infer the PK value from the constructor arguments. It is used to decide if an instance has to be built or is already in the cache. """ result = None # Quick hack for my composites work for now. if hasattr(cls._meta, 'pks'): pk = cls._meta.pks[0] else: pk = cls._meta.pk # get the index of the pk in the class fields. this should be calculated *once*, but isn't atm pk_position = cls._meta.fields.index(pk) if len(args) > pk_position: # if it's in the args, we can get it easily by index result = args[pk_position] elif pk.attname in kwargs: # retrieve the pk value. Note that we use attname instead of name, to handle the case where the pk is a # a ForeignKey. result = kwargs[pk.attname] elif pk.name != pk.attname and pk.name in kwargs: # ok we couldn't find the value, but maybe it's a FK and we can find the corresponding object instead result = kwargs[pk.name] if result is not None and isinstance(result, Model): # if the pk value happens to be a model instance (which can happen wich a FK), we'd rather use its own pk as the key result = result._get_pk_val() return result _get_cache_key = classmethod(_get_cache_key) def get_cached_instance(cls, id): """ Method to retrieve a cached instance by pk value. Returns None when not found (which will always be the case when caching is disabled for this class). Please note that the lookup will be done even when instance caching is disabled. """ return cls.__instance_cache__.get(id) get_cached_instance = classmethod(get_cached_instance) def cache_instance(cls, instance): """ Method to store an instance in the cache. """ if instance._get_pk_val() is not None: cls.__instance_cache__[instance._get_pk_val()] = instance cache_instance = classmethod(cache_instance) def get_all_cached_instances(cls): "return the objects so far cached by idmapper for this class." return cls.__instance_cache__.values() get_all_cached_instances = classmethod(get_all_cached_instances) def _flush_cached_by_key(cls, key): del cls.__instance_cache__[key] _flush_cached_by_key = classmethod(_flush_cached_by_key) def flush_cached_instance(cls, instance): """ Method to flush an instance from the cache. The instance will always be flushed from the cache, since this is most likely called from delete(), and we want to make sure we don't cache dead objects. """ cls._flush_cached_by_key(instance._get_pk_val()) #key = "%s-%s" % (cls, instance.pk) #print "uncached: %s (%s: %s) (total cached: %s)" % (instance, cls.__name__, len(cls.__instance_cache__), len(TCACHE)) flush_cached_instance = classmethod(flush_cached_instance) def save(self, *args, **kwargs): super(SharedMemoryModel, self).save(*args, **kwargs) self.__class__.cache_instance(self) # TODO: This needs moved to the prepare stage (I believe?) objects = SharedMemoryManager() from django.db.models.signals import pre_delete # Use a signal so we make sure to catch cascades. def flush_singleton_cache(sender, instance, **kwargs): # XXX: Is this the best way to make sure we can flush? if isinstance(instance, SharedMemoryModel): instance.__class__.flush_cached_instance(instance) pre_delete.connect(flush_singleton_cache) # XXX: It's to be determined if we should use this or not. # def update_singleton_cache(sender, instance, **kwargs): # if isinstance(instance.__class__, SharedMemoryModel): # instance.__class__.cache_instance(instance) # post_save.connect(flush_singleton_cache)
Python
from django.db.models.manager import Manager class SharedMemoryManager(Manager): # TODO: improve on this implementation # We need a way to handle reverse lookups so that this model can # still use the singleton cache, but the active model isn't required # to be a SharedMemoryModel. def get(self, **kwargs): items = kwargs.keys() inst = None if len(items) == 1 and items[0] in ('pk', self.model._meta.pk.attname): inst = self.model.get_cached_instance(kwargs[items[0]]) if inst is None: inst = super(SharedMemoryManager, self).get(**kwargs) return inst
Python
from django.db.models import * from base import SharedMemoryModel
Python
from django.test import TestCase from base import SharedMemoryModel from django.db import models class Category(SharedMemoryModel): name = models.CharField(max_length=32) class RegularCategory(models.Model): name = models.CharField(max_length=32) class Article(SharedMemoryModel): name = models.CharField(max_length=32) category = models.ForeignKey(Category) category2 = models.ForeignKey(RegularCategory) class RegularArticle(models.Model): name = models.CharField(max_length=32) category = models.ForeignKey(Category) category2 = models.ForeignKey(RegularCategory) class SharedMemorysTest(TestCase): # TODO: test for cross model relation (singleton to regular) def setUp(self): n = 0 category = Category.objects.create(name="Category %d" % (n,)) regcategory = RegularCategory.objects.create(name="Category %d" % (n,)) for n in xrange(0, 10): Article.objects.create(name="Article %d" % (n,), category=category, category2=regcategory) RegularArticle.objects.create(name="Article %d" % (n,), category=category, category2=regcategory) def testSharedMemoryReferences(self): article_list = Article.objects.all().select_related('category') last_article = article_list[0] for article in article_list[1:]: self.assertEquals(article.category is last_article.category, True) last_article = article def testRegularReferences(self): article_list = RegularArticle.objects.all().select_related('category') last_article = article_list[0] for article in article_list[1:]: self.assertEquals(article.category2 is last_article.category2, False) last_article = article def testMixedReferences(self): article_list = RegularArticle.objects.all().select_related('category') last_article = article_list[0] for article in article_list[1:]: self.assertEquals(article.category is last_article.category, True) last_article = article article_list = Article.objects.all().select_related('category') last_article = article_list[0] for article in article_list[1:]: self.assertEquals(article.category2 is last_article.category2, False) last_article = article def testObjectDeletion(self): # This must execute first so its guaranteed to be in memory. article_list = list(Article.objects.all().select_related('category')) article = Article.objects.all()[0:1].get() pk = article.pk article.delete() self.assertEquals(pk not in Article.__instance_cache__, True)
Python
""" The gametime module handles the global passage of time in the mud. It also supplies some useful methods to convert between in-mud time and real-world time as well allows to get the total runtime of the server and the current uptime. """ from django.conf import settings from src.scripts.scripts import Script from src.scripts.models import ScriptDB from src.utils.create import create_script from src.utils import logger # name of script that keeps track of the time GAME_TIME_SCRIPT = "sys_game_time" # Speed-up factor of the in-game time compared # to real time. TIMEFACTOR = settings.TIME_FACTOR # Common real-life time measures, in seconds. # You should not change these. REAL_TICK = max(1.0, settings.TIME_TICK) #Smallest time unit (min 1s) REAL_MIN = 60.0 # seconds per minute in real world # Game-time units, in real-life seconds. These are supplied as # a convenient measure for determining the current in-game time, # e.g. when defining events. The words month, week and year can # of course mean whatever units of time are used in the game. TICK = REAL_TICK * TIMEFACTOR MIN = REAL_MIN * TIMEFACTOR HOUR = MIN * settings.TIME_MIN_PER_HOUR DAY = HOUR * settings.TIME_HOUR_PER_DAY WEEK = DAY * settings.TIME_DAY_PER_WEEK MONTH = WEEK * settings.TIME_WEEK_PER_MONTH YEAR = MONTH * settings.TIME_MONTH_PER_YEAR class GameTime(Script): """ This sets up an script that keeps track of the in-game time and some other time units. """ def at_script_creation(self): """ Setup the script """ self.key = "sys_game_time" self.desc = "Keeps track of the game time" self.interval = REAL_MIN # update every minute self.persistent = True self.start_delay = True self.attr("game_time", 0.0) #IC time self.attr("run_time", 0.0) #OOC time self.attr("up_time", 0.0) #OOC time def at_repeat(self): """ Called every minute to update the timers. """ # We store values as floats to avoid drift over time game_time = float(self.attr("game_time")) run_time = float(self.attr("run_time")) up_time = float(self.attr("up_time")) self.attr("game_time", game_time + MIN) self.attr("run_time", run_time + REAL_MIN) self.attr("up_time", up_time + REAL_MIN) def at_start(self): """ This is called once every server restart. We reset the up time. """ self.attr("up_time", 0.0) # Access routines def gametime_format(seconds): """ Converts the count in seconds into an integer tuple of the form (years, months, weeks, days, hours, minutes, seconds) where several of the entries may be 0. We want to keep a separate version of this (rather than just rescale the real time once and use the normal realtime_format below) since the admin might for example decide to change how many hours a 'day' is in their game etc. """ # have to re-multiply in the TIMEFACTOR # do this or we cancel the already counted # timefactor in the timer script... sec = int(seconds * TIMEFACTOR) years, sec = sec/YEAR, sec % YEAR months, sec = sec/MONTH, sec % MONTH weeks, sec = sec/WEEK, sec % WEEK days, sec = sec/DAY, sec % DAY hours, sec = sec/HOUR, sec % HOUR minutes, sec = sec/MIN, sec % MIN return (years, months, weeks, days, hours, minutes, sec) def realtime_format(seconds): """ As gametime format, but with real time units """ sec = int(seconds) years, sec = sec/29030400, sec % 29030400 months, sec = sec/2419200, sec % 2419200 weeks, sec = sec/604800, sec % 604800 days, sec = sec/86400, sec % 86400 hours, sec = sec/3600, sec % 3600 minutes, sec = sec/60, sec % 60 return (years, months, weeks, days, hours, minutes, sec) def gametime(format=False): """ Find the current in-game time (in seconds) since the start of the mud. The value returned from this function can be used to track the 'true' in-game time since only the time the game has actually been active will be adding up (ignoring downtimes). format - instead of returning result in seconds, format to (game-) time units. """ try: script = ScriptDB.objects.get_all_scripts(GAME_TIME_SCRIPT)[0] except (KeyError, IndexError): logger.log_trace("GameTime script not found.") return # we return this as an integer (second-precision is good enough) game_time = int(script.attr("game_time")) if format: return gametime_format(game_time) return game_time def runtime(format=False): """ Get the total actual time the server has been running (minus downtimes) """ try: script = ScriptDB.objects.get_all_scripts(GAME_TIME_SCRIPT)[0] except (KeyError, IndexError): logger.log_trace("GameTime script not found.") return # we return this as an integer (second-precision is good enough) run_time = int(script.attr("run_time")) if format: return realtime_format(run_time) return run_time def uptime(format=False): """ Get the actual time the server has been running since last downtime. """ try: script = ScriptDB.objects.get_all_scripts(GAME_TIME_SCRIPT)[0] except (KeyError, IndexError): logger.log_trace("GameTime script not found.") return # we return this as an integer (second-precision is good enough) up_time = int(script.attr("up_time")) if format: return realtime_format(up_time) return up_time def gametime_to_realtime(secs=0, mins=0, hrs=0, days=0, weeks=0, months=0, yrs=0): """ This method helps to figure out the real-world time it will take until a in-game time has passed. E.g. if an event should take place a month later in-game, you will be able to find the number of real-world seconds this corresponds to (hint: Interval events deal with real life seconds). Example: gametime_to_realtime(days=2) -> number of seconds in real life from now after which 2 in-game days will have passed. """ real_time = secs/TIMEFACTOR + mins*MIN + hrs*HOUR + \ days*DAY + weeks*WEEK + months*MONTH + yrs*YEAR return real_time def realtime_to_gametime(secs=0, mins=0, hrs=0, days=0, weeks=0, months=0, yrs=0): """ This method calculates how large an in-game time a real-world time interval would correspond to. This is usually a lot less interesting than the other way around. Example: realtime_to_gametime(days=2) -> number of game-world seconds corresponding to 2 real days. """ game_time = TIMEFACTOR * (secs + mins*60 + hrs*3600 + days*86400 + \ weeks*604800 + months*2419200 + yrs*29030400) return game_time # Time administration routines def init_gametime(): """ This is called once, when the server starts for the very first time. """ # create the GameTime script and start it game_time = create_script(GameTime) game_time.start()
Python
""" This module gathers all the essential database-creation methods for the game engine's various object types. Only objects created 'stand-alone' are in here, e.g. object Attributes are always created directly through their respective objects. The respective object managers hold more methods for manipulating and searching objects already existing in the database. Models covered: Objects Scripts Help Message Channel Players """ from django.conf import settings from django.contrib.auth.models import User from django.db import IntegrityError from src.utils.idmapper.models import SharedMemoryModel from src.utils import logger, utils, idmapper from src.utils.utils import is_iter, has_parent, inherits_from # # Game Object creation # def create_object(typeclass, key=None, location=None, home=None, player=None, permissions=None, locks=None, aliases=None, destination=None): """ Create a new in-game object. Any game object is a combination of a database object that stores data persistently to the database, and a typeclass, which on-the-fly 'decorates' the database object into whataver different type of object it is supposed to be in the game. See src.objects.managers for methods to manipulate existing objects in the database. src.objects.objects holds the base typeclasses and src.objects.models hold the database model. """ # deferred import to avoid loops from src.objects.objects import Object from src.objects.models import ObjectDB if not typeclass: typeclass = settings.BASE_OBJECT_TYPECLASS elif isinstance(typeclass, ObjectDB): # this is already an objectdb instance, extract its typeclass typeclass = typeclass.typeclass.path elif isinstance(typeclass, Object) or utils.inherits_from(typeclass, Object): # this is already an object typeclass, extract its path typeclass = typeclass.path # create new database object new_db_object = ObjectDB() # assign the typeclass typeclass = utils.to_unicode(typeclass) new_db_object.typeclass_path = typeclass # the name/key is often set later in the typeclass. This # is set here as a failsafe. if key: new_db_object.key = key else: new_db_object.key = "#%i" % new_db_object.id # this will either load the typeclass or the default one new_object = new_db_object.typeclass if not object.__getattribute__(new_db_object, "is_typeclass")(typeclass, exact=True): # this will fail if we gave a typeclass as input and it still gave us a default SharedMemoryModel.delete(new_db_object) return None # from now on we can use the typeclass object # as if it was the database object. if player: # link a player and the object together new_object.player = player player.obj = new_object new_object.destination = destination # call the hook method. This is where all at_creation # customization happens as the typeclass stores custom # things on its database object. new_object.basetype_setup() # setup the basics of Exits, Characters etc. new_object.at_object_creation() # custom-given perms/locks overwrite hooks if permissions: new_object.permissions = permissions if locks: new_object.locks.add(locks) if aliases: new_object.aliases = aliases # perform a move_to in order to display eventual messages. if home: new_object.home = home else: new_object.home = settings.CHARACTER_DEFAULT_HOME if location: new_object.move_to(location, quiet=True) else: # rooms would have location=None. new_object.location = None # post-hook setup (mainly used by Exits) new_object.basetype_posthook_setup() new_object.save() return new_object # # Script creation # def create_script(typeclass, key=None, obj=None, locks=None, autostart=True): """ Create a new script. All scripts are a combination of a database object that communicates with the database, and an typeclass that 'decorates' the database object into being different types of scripts. It's behaviour is similar to the game objects except scripts has a time component and are more limited in scope. Argument 'typeclass' can be either an actual typeclass object or a python path to such an object. Only set key here if you want a unique name for this particular script (set it in config to give same key to all scripts of the same type). Set obj to tie this script to a particular object. See src.scripts.manager for methods to manipulate existing scripts in the database. """ # deferred import to avoid loops. from src.scripts.scripts import Script #print "in create_script", typeclass from src.scripts.models import ScriptDB if not typeclass: typeclass = settings.BASE_SCRIPT_TYPECLASS elif isinstance(typeclass, ScriptDB): # this is already an scriptdb instance, extract its typeclass typeclass = new_db_object.typeclass.path elif isinstance(typeclass, Script) or utils.inherits_from(typeclass, Script): # this is already an object typeclass, extract its path typeclass = typeclass.path # create new database script new_db_script = ScriptDB() # assign the typeclass typeclass = utils.to_unicode(typeclass) new_db_script.typeclass_path = typeclass # the name/key is often set later in the typeclass. This # is set here as a failsafe. if key: new_db_script.key = key else: new_db_script.key = "#%i" % new_db_script.id # this will either load the typeclass or the default one new_script = new_db_script.typeclass if not object.__getattribute__(new_db_script, "is_typeclass")(typeclass, exact=True): # this will fail if we gave a typeclass as input and it still gave us a default print "failure:", new_db_script, typeclass SharedMemoryModel.delete(new_db_script) return None if obj: try: new_script.obj = obj except ValueError: new_script.obj = obj.dbobj # call the hook method. This is where all at_creation # customization happens as the typeclass stores custom # things on its database object. new_script.at_script_creation() # custom-given variables override the hook if key: new_script.key = key if locks: new_script.locks.add(locks) # a new created script should usually be started. if autostart: new_script.start() new_db_script.save() return new_script # # Help entry creation # def create_help_entry(key, entrytext, category="General", locks=None): """ Create a static help entry in the help database. Note that Command help entries are dynamic and directly taken from the __doc__ entries of the command. The database-stored help entries are intended for more general help on the game, more extensive info, in-game setting information and so on. """ from src.help.models import HelpEntry try: new_help = HelpEntry() new_help.key = key new_help.entrytext = entrytext new_help.help_category = category if locks: new_help.locks.add(locks) new_help.save() return new_help except IntegrityError: string = "Could not add help entry: key '%s' already exists." % key logger.log_errmsg(string) return None except Exception: logger.log_trace() return None # # Comm system methods # def create_message(senderobj, message, channels=None, receivers=None, locks=None): """ Create a new communication message. Msgs are used for all player-to-player communication, both between individual players and over channels. senderobj - the player sending the message. This must be the actual object. message - text with the message. Eventual headers, titles etc should all be included in this text string. Formatting will be retained. channels - a channel or a list of channels to send to. The channels may be actual channel objects or their unique key strings. receivers - a player to send to, or a list of them. May be Player objects or playernames. locks - lock definition string The Comm system is created very open-ended, so it's fully possible to let a message both go to several channels and to several receivers at the same time, it's up to the command definitions to limit this as desired. """ from src.comms.models import Msg from src.comms.managers import to_object def to_player(obj): "Make sure the object is a player object" if hasattr(obj, 'user'): return obj elif hasattr(obj, 'player'): return obj.player else: return None if not message: # we don't allow empty messages. return new_message = Msg() new_message.sender = to_player(senderobj) new_message.message = message new_message.save() if channels: if not is_iter(channels): channels = [channels] new_message.channels = [channel for channel in [to_object(channel, objtype='channel') for channel in channels] if channel] if receivers: #print "Found receiver:", receivers if not is_iter(receivers): receivers = [receivers] #print "to_player: %s" % to_player(receivers[0]) new_message.receivers = [to_player(receiver) for receiver in [to_object(receiver) for receiver in receivers] if receiver] if locks: new_message.locks.add(locks) new_message.save() return new_message def create_channel(key, aliases=None, desc=None, locks=None, keep_log=True): """ Create A communication Channel. A Channel serves as a central hub for distributing Msgs to groups of people without specifying the receivers explicitly. Instead players may 'connect' to the channel and follow the flow of messages. By default the channel allows access to all old messages, but this can be turned off with the keep_log switch. key - this must be unique. aliases - list of alternative (likely shorter) keynames. locks - lock string definitions """ from src.comms.models import Channel from src.comms import channelhandler try: new_channel = Channel() new_channel.key = key if aliases: if not is_iter(aliases): aliases = [aliases] new_channel.aliases = ",".join([alias for alias in aliases]) new_channel.desc = desc new_channel.keep_log = keep_log except IntegrityError: string = "Could not add channel: key '%s' already exists." % key logger.log_errmsg(string) return None if locks: new_channel.locks.add(locks) new_channel.save() channelhandler.CHANNELHANDLER.add_channel(new_channel) return new_channel # # Player creation methods # def create_player(name, email, password, user=None, typeclass=None, is_superuser=False, locks=None, permissions=None, create_character=True, character_typeclass=None, character_location=None, character_home=None, player_dbobj=None): """ This creates a new player, handling the creation of the User object and its associated Player object. If player_dbobj is given, this player object is used instead of creating a new one. This is called by the admin interface since it needs to create the player object in order to relate it automatically to the user. If create_character is True, a game player object with the same name as the User/Player will also be created. Its typeclass and base properties can also be given. Returns the new game character, or the Player obj if no character is created. For more info about the typeclass argument, see create_objects() above. Note: if user is supplied, it will NOT be modified (args name, email, passw and is_superuser will be ignored). Change those properties directly on the User instead. If no permissions are given (None), the default permission group as defined in settings.PERMISSION_PLAYER_DEFAULT will be assigned. If permissions are given, no automatic assignment will occur. Concerning is_superuser: A superuser should have access to everything in the game and on the server/web interface. The very first user created in the database is always a superuser (that's using django's own creation, not this one). Usually only the server admin should need to be superuser, all other access levels can be handled with more fine-grained permissions or groups. Since superuser overrules all permissions, we don't set any in this case. """ # The system should already have checked so the name/email # isn't already registered, and that the password is ok before # getting here. from src.players.models import PlayerDB from src.players.player import Player if not email: email = "dummy@dummy.com" if user: new_user = user email = user.email else: if is_superuser: new_user = User.objects.create_superuser(name, email, password) else: new_user = User.objects.create_user(name, email, password) try: if not typeclass: typeclass = settings.BASE_PLAYER_TYPECLASS elif isinstance(typeclass, PlayerDB): # this is already an objectdb instance, extract its typeclass typeclass = typeclass.typeclass.path elif isinstance(typeclass, Player) or utils.inherits_from(typeclass, Player): # this is already an object typeclass, extract its path typeclass = typeclass.path if player_dbobj: new_db_player = player_dbobj else: new_db_player = PlayerDB(db_key=name, user=new_user) new_db_player.save() # assign the typeclass typeclass = utils.to_unicode(typeclass) new_db_player.typeclass_path = typeclass # this will either load the typeclass or the default one new_player = new_db_player.typeclass if not object.__getattribute__(new_db_player, "is_typeclass")(typeclass, exact=True): # this will fail if we gave a typeclass as input and it still gave us a default SharedMemoryModel.delete(new_db_player) return None new_player.basetype_setup() # setup the basic locks and cmdset # call hook method (may override default permissions) new_player.at_player_creation() # custom given arguments potentially overrides the hook if permissions: new_player.permissions = permissions elif not new_player.permissions: new_player.permissions = settings.PERMISSION_PLAYER_DEFAULT if locks: new_player.locks.add(locks) # create *in-game* 'player' object if create_character: if not character_typeclass: character_typeclass = settings.BASE_CHARACTER_TYPECLASS # creating the object automatically links the player # and object together by player.obj <-> obj.player new_character = create_object(character_typeclass, key=name, location=None, home=character_location, permissions=permissions, player=new_player) return new_character return new_player except Exception: # a failure in creating the character if not user: # in there was a failure we clean up everything we can logger.log_trace() try: new_user.delete() except Exception: pass try: new_player.delete() except Exception: pass try: del new_character except Exception: pass
Python
""" These are actions for the dummy client runner, using the default command set and intended for unmodified Evennia. Each client action is defined as a function. The clients will perform these actions randomly (except the login action). Each action-definition function should take one argument- "client", which is a reference to the client currently performing the action Use the client object for saving data between actions. The client object has the following relevant properties and methods: cid - unique client id istep - the current step exits - an empty list. Can be used to store exit names objs - an empty list. Can be used to store object names counter() - get an integer value. This counts up for every call and is always unique between clients. The action-definition function should return the command that the client should send to the server (as if it was input in a mud client). It should also return a string detailing the action taken. This string is used by the "brief verbose" mode of the runner and is prepended by "Client N " to produce output like "Client 3 is creating objects ..." This module *must* also define a variable named ACTIONS. This is a tuple where the first element is the function object for the action function to call when the client logs onto the server. The following elements are 2-tuples (probability, action_func), where probability defines how common it is for that particular action to happen. The runner will randomly pick between those functions based on the probability. ACTIONS = (login_func, (0.3, func1), (0.1, func2) ... ) To change the runner to use your custom ACTION and/or action definitions, edit settings.py and add DUMMYRUNNER_ACTIONS_MODULE = "path.to.your.module" """ # it's very useful to have a unique id for this run to avoid any risk # of clashes import time RUNID = time.time() # some convenient templates START_ROOM = "testing_room_start-%s-%s" % (RUNID, "%i") ROOM_TEMPLATE = "testing_room_%s-%s" % (RUNID, "%i") EXIT_TEMPLATE = "exit_%s-%s" % (RUNID, "%i") OBJ_TEMPLATE = "testing_obj_%s-%s" % (RUNID, "%i") TOBJ_TEMPLATE = "testing_button_%s-%s" % (RUNID, "%i") TOBJ_TYPECLASS = "examples.red_button.RedButton" # action function definitions def c_login(client): "logins to the game" cname = "Dummy-%s-%i" % (RUNID, client.cid) cemail = "%s@dummy.com" % (cname.lower()) cpwd = "%s-%s" % (RUNID, client.cid) cmd = ('create "%s" %s %s' % (cname, cemail, cpwd), 'connect %s %s' % (cemail, cpwd), '@dig %s' % START_ROOM % client.cid, '@teleport %s' % START_ROOM % client.cid) return cmd, "logs into game as %s ..." % cname def c_looks(client): "looks at various objects" cmd = ["look %s" % obj for obj in client.objs] if not cmd: cmd = ["look %s" % exi for exi in client.exits] if not cmd: cmd = "look" return cmd, "looks ..." def c_examines(client): "examines various objects" cmd = ["examine %s" % obj for obj in client.objs] if not cmd: cmd = ["examine %s" % exi for exi in client.exits] if not cmd: cmd = "examine me" return cmd, "examines objs ..." def c_help(client): "reads help files" cmd = ('help', 'help @teleport', 'help look', 'help @tunnel', 'help @dig') return cmd, "reads help ..." def c_digs(client): "digs a new room, storing exit names on client" roomname = ROOM_TEMPLATE % client.counter() exitname1 = EXIT_TEMPLATE % client.counter() exitname2 = EXIT_TEMPLATE % client.counter() client.exits.extend([exitname1, exitname2]) cmd = '@dig %s = %s, %s' % (roomname, exitname1, exitname2) return cmd, "digs ..." def c_creates_obj(client): "creates normal objects, storing their name on client" objname = OBJ_TEMPLATE % client.counter() client.objs.append(objname) cmd = ('@create %s' % objname, '@desc %s = "this is a test object' % objname, '@set %s/testattr = this is a test attribute value.' % objname, '@set %s/testattr2 = this is a second test attribute.' % objname) return cmd, "creates obj ..." def c_creates_button(client): "creates example button, storing name on client" objname = TOBJ_TEMPLATE % client.counter() client.objs.append(objname) cmd = ('@create %s:%s' % (objname, TOBJ_TYPECLASS), '@desc %s = test red button!' % objname) return cmd, "creates button ..." def c_moves(client): "moves to a previously created room, using the stored exits" cmd = client.exits # try all exits - finally one will work if not cmd: cmd = "look" return cmd, "moves ..." # Action tuple (required) # # This is a tuple of client action functions. The first element is the # function the client should use to log into the game and move to # STARTROOM . The following elements are 2-tuples of (probability, # action_function). The probablities should normally sum up to 1, # otherwise the system will normalize them. # ACTIONS = ( c_login, (0.2, c_looks), (0.1, c_examines), (0.2, c_help), (0.1, c_digs), (0.1, c_creates_obj), #(0.1, c_creates_button), (0.2, c_moves))
Python
""" This is a convenient container gathering all the main search methods for the various database tables. It is intended to be used e.g. as > from src.utils import search > match = search.objects(...) Note that this is not intended to be a complete listing of all search methods! You need to refer to the respective manager to get all possible search methods. To get to the managers from your code, import the database model and call its 'objects' property. Also remember that all commands in this file return lists (also if there is only one match) unless noted otherwise. Example: To reach the search method 'get_object_with_user' in src/objects/managers.py: > from src.objects.models import ObjectDB > match = Object.objects.get_object_with_user(...) """ # Import the manager methods to be wrapped from django.contrib.contenttypes.models import ContentType # import objects this way to avoid circular import problems ObjectDB = ContentType.objects.get(app_label="objects", model="objectdb").model_class() PlayerDB = ContentType.objects.get(app_label="players", model="playerdb").model_class() ScriptDB = ContentType.objects.get(app_label="scripts", model="scriptdb").model_class() Msg = ContentType.objects.get(app_label="comms", model="msg").model_class() Channel = ContentType.objects.get(app_label="comms", model="channel").model_class() HelpEntry = ContentType.objects.get(app_label="help", model="helpentry").model_class() # # Search objects as a character # # NOTE: A more powerful wrapper of this method # is reachable from within each command class # by using self.caller.search()! # # def object_search(self, ostring, caller=None, # global_search=False, # attribute_name=None): # """ # Search as an object and return results. # # 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 'name' attribute is used. # """ objects = ObjectDB.objects.object_search # # Search for players # # NOTE: Most usually you would do such searches from # from inseide command definitions using # self.caller.search() by appending an '*' to the # beginning of the search criterion. # # def player_search(self, ostring): # """ # Searches for a particular player by name or # database id. # # ostring = a string or database id. # """ players = PlayerDB.objects.player_search # # Searching for scripts # # 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. # """ scripts = ScriptDB.objects.script_search # # Searching for communication messages # # # def message_search(self, sender=None, receiver=None, channel=None, freetext=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 # channel - get messages sent to a particular channel # 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. # """ messages = Msg.objects.message_search # # Search for Communication Channels # # def channel_search(self, ostring) # """ # Search the channel database for a particular channel. # # ostring - the key or database id of the channel. # """ channels = Channel.objects.channel_search # # Find help entry objects. # # 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 # """ helpentries = HelpEntry.objects.search_help
Python
""" A cmdset holds a set of commands available to the object or to other objects near it. All the commands a player can give (look, @create etc) are stored as the default cmdset on the player object and managed using the CmdHandler object (see cmdhandler.py). The power of having command sets in CmdSets like this is that CmdSets can be merged together according to individual rules to create a new on-the-fly CmdSet that is some combination of the previous ones. Their function are borrowed to a large parts from mathematical Set theory, it should not be much of a problem to understand. See CmdHandler for practical examples on how to apply cmdsets together to create interesting in-game effects. """ import copy from src.utils.utils import inherits_from, is_iter RECURSIVE_PROTECTION = False class CmdSetMeta(type): """ This metaclass makes some minor on-the-fly convenience fixes to the cmdset class. """ def __init__(mcs, *args, **kwargs): """ Fixes some things in the cmdclass """ # by default we key the cmdset the same as the # name of its class. if not hasattr(mcs, 'key') or not mcs.key: mcs.key = mcs.__name__ mcs.path = "%s.%s" % (mcs.__module__, mcs.__name__) if not type(mcs.key_mergetypes) == dict: mcs.key_mergetypes = {} super(CmdSetMeta, mcs).__init__(*args, **kwargs) # Some priority-sensitive merge operations for cmdsets def union(cmdset_a, cmdset_b, duplicates=False): "C = A U B. CmdSet A is assumed to have higher priority" cmdset_c = cmdset_a.copy_this() # we make copies, not refs by use of [:] cmdset_c.commands = cmdset_a.commands[:] if duplicates and cmdset_a.priority == cmdset_b.priority: cmdset_c.commands.extend(cmdset_b.commands) else: cmdset_c.commands.extend([cmd for cmd in cmdset_b if not cmd in cmdset_a]) return cmdset_c def intersect(cmdset_a, cmdset_b, duplicates=False): "C = A (intersect) B. A is assumed higher priority" cmdset_c = cmdset_a.copy_this() if duplicates and cmdset_a.priority == cmdset_b.priority: for cmd in [cmd for cmd in cmdset_a if cmd in cmdset_b]: cmdset_c.add(cmd) cmdset_c.add(cmdset_b.get(cmd)) else: cmdset_c.commands = [cmd for cmd in cmdset_a if cmd in cmdset_b] return cmdset_c def replace(cmdset_a, cmdset_b, cmdset_c): "C = A + B where the result is A." cmdset_c = cmdset_a.copy_this() cmdset_c.commands = cmdset_a.commands[:] return cmdset_c def remove(cmdset_a, cmdset_b, cmdset_c): "C = A + B, where B is filtered by A" cmdset_c = cmdset_a.copy_this() cmdset_c.commands = [cmd for cmd in cmdset_b if not cmd in cmdset_a] return cmdset_c def instantiate(cmd): """ checks so that object is an instantiated command and not, say a cmdclass. If it is, instantiate it. Other types, like strings, are passed through. """ try: return cmd() except TypeError: return cmd class CmdSet(object): """ This class describes a unique cmdset that understands priorities. CmdSets can be merged and made to perform various set operations on each other. CmdSets have priorities that affect which of their ingoing commands gets used. In the examples, cmdset A always have higher priority than cmdset B. key - the name of the cmdset. This can be used on its own for game operations mergetype (partly from Set theory): Union - The two command sets are merged so that as many commands as possible of each cmdset ends up in the merged cmdset. Same-name commands are merged by priority. This is the most common default. Ex: A1,A3 + B1,B2,B4,B5 = A1,B2,A3,B4,B5 Intersect - Only commands found in *both* cmdsets (i.e. which have same names) end up in the merged cmdset, with the higher-priority cmdset replacing the lower one. Ex: A1,A3 + B1,B2,B4,B5 = A1 Replace - The commands of this cmdset completely replaces the lower-priority cmdset's commands, regardless of if same-name commands exist. Ex: A1,A3 + B1,B2,B4,B5 = A1,A3 Remove - This removes the relevant commands from the lower-priority cmdset completely. They are not replaced with anything, so this in effects uses the high-priority cmdset as a filter to affect the low-priority cmdset. Ex: A1,A3 + B1,B2,B4,B5 = B2,B4,B5 Note: Commands longer than 2 characters and starting with double underscrores, like '__noinput_command' are considered 'system commands' and are excempt from all merge operations - they are ALWAYS included across mergers and only affected if same-named system commands replace them. priority- All cmdsets are always merged in pairs of two so that the higher set's mergetype is applied to the lower-priority cmdset. Default commands have priority 0, high-priority ones like Exits and Channels have 10 and 9. Priorities can be negative as well to give default commands preference. duplicates - determines what happens when two sets of equal priority merge. Default has the first of them in the merger (i.e. A above) automatically taking precedence. But if allow_duplicates is true, the result will be a merger with more than one of each name match. This will usually lead to the player receiving a multiple-match error higher up the road, but can be good for things like cmdsets on non-player objects in a room, to allow the system to warn that more than one 'ball' in the room has the same 'kick' command defined on it, so it may offer a chance to select which ball to kick ... Allowing duplicates only makes sense for Union and Intersect, the setting is ignored for the other mergetypes. key_mergetype (dict) - allows the cmdset to define a unique mergetype for particular cmdsets. Format is {CmdSetkeystring:mergetype}. Priorities still apply. Example: {'Myevilcmdset','Replace'} which would make sure for this set to always use 'Replace' on Myevilcmdset no matter what overall mergetype this set has. no_objs - don't include any commands from nearby objects when searching for suitable commands no_exits - ignore the names of exits when matching against commands no_channels - ignore the name of channels when matching against commands (WARNING- this is dangerous since the player can then not even ask staff for help if something goes wrong) """ __metaclass__ = CmdSetMeta key = "Unnamed CmdSet" mergetype = "Union" priority = 0 duplicates = False key_mergetypes = {} no_exits = False no_objs = False no_channels = False permanent = False def __init__(self, cmdsetobj=None, key=None): """ Creates a new CmdSet instance. cmdsetobj - this is the database object to which this particular instance of cmdset is related. It is often a player but may also be a regular object. """ if key: self.key = key self.commands = [] self.actual_mergetype = self.mergetype self.cmdsetobj = cmdsetobj # initialize system self.at_cmdset_creation() def at_cmdset_creation(self): """ Hook method - this should be overloaded in the inheriting class, and should take care of populating the cmdset by use of self.add(). """ pass def add(self, cmd): """ Add a command, a list of commands or a cmdset to this cmdset. Note that if cmd already exists in set, it will replace the old one (no priority checking etc at this point; this is often used to overload default commands). If cmd is another cmdset class or -instance, the commands of that command set is added to this one, as if they were part of the original cmdset definition. No merging or priority checks are made, rather later added commands will simply replace existing ones to make a unique set. """ if inherits_from(cmd, "src.commands.cmdset.CmdSet"): # cmd is a command set so merge all commands in that set # to this one. We raise a visible error if we created # an infinite loop (adding cmdset to itself somehow) try: cmd = instantiate(cmd) except RuntimeError, e: string = "Adding cmdset %s to %s lead to an infinite loop. When adding a cmdset to another, " string += "make sure they are not themself cyclically added to the new cmdset somewhere in the chain." raise RuntimeError(string % (cmd, self.__class__)) cmds = cmd.commands elif is_iter(cmd): cmds = [instantiate(c) for c in cmd] else: cmds = [instantiate(cmd)] for cmd in cmds: # add all commands if not hasattr(cmd, 'obj'): cmd.obj = self.cmdsetobj try: ic = self.commands.index(cmd) self.commands[ic] = cmd # replace except ValueError: self.commands.append(cmd) # extra run to make sure to avoid doublets self.commands = list(set(self.commands)) #print "In cmdset.add(cmd):", self.key, cmd def remove(self, cmd): """ Remove a command instance from the cmdset. cmd can be either a cmd instance or a key string. """ cmd = instantiate(cmd) self.commands = [oldcmd for oldcmd in self.commands if oldcmd != cmd] def get(self, cmd): """ Return the command in this cmdset that matches the given command. cmd may be either a command instance or a key string. """ cmd = instantiate(cmd) for thiscmd in self.commands: if thiscmd == cmd: return thiscmd def count(self): "Return number of commands in set" return len(self.commands) def get_system_cmds(self): """ Return system commands in the cmdset, defined as commands starting with double underscore __. These are excempt from merge operations. """ return [cmd for cmd in self.commands if cmd.key.startswith('__')] def copy_this(self): """ Returns a new cmdset with the same settings as this one (no commands are copied over) """ cmdset = CmdSet() cmdset.key = self.key cmdset.cmdsetobj = self.cmdsetobj cmdset.no_exits = self.no_exits cmdset.no_objs = self.no_objs cmdset.no_channels = self.no_channels cmdset.mergetype = self.mergetype cmdset.priority = self.priority cmdset.duplicates = self.duplicates cmdset.key_mergetypes = self.key_mergetypes.copy() #copy.deepcopy(self.key_mergetypes) return cmdset def make_unique(self, caller): """ This is an unsafe command meant to clean out a cmdset of doublet commands after it has been created. It is useful for commands inheriting cmdsets from the cmdhandler where obj-based cmdsets always are added double. Doublets will be weeded out with preference to commands defined on caller, otherwise just by first-come-first-served. """ unique = {} for cmd in self.commands: if cmd.key in unique: ocmd = unique[cmd.key] if (hasattr(cmd, 'obj') and cmd.obj == caller) and not \ (hasattr(ocmd, 'obj') and ocmd.obj == caller): unique[cmd.key] = cmd else: unique[cmd.key] = cmd self.commands = unique.values() def __str__(self): """ Show all commands in cmdset when printing it. """ return ", ".join([str(cmd) for cmd in sorted(self.commands, key=lambda o:o.key)]) def __iter__(self): """ Allows for things like 'for cmd in cmdset': """ return iter(self.commands) def __contains__(self, othercmd): """ Returns True if this cmdset contains the given command (as defined by command name and aliases). This allows for things like 'if cmd in cmdset' """ return any(cmd == othercmd for cmd in self.commands) def __add__(self, cmdset_b): """ Merge this cmdset (A) with another cmdset (B) using the + operator, C = A + B Here, we (by convention) say that 'A is merged onto B to form C'. The actual merge operation used in the 'addition' depends on which priorities A and B have. The one of the two with the highest priority will apply and give its properties to C. In the case of a tie, A takes priority and replaces the same-named commands in B unless A has the 'duplicate' variable set (which means both sets' commands are kept). """ # It's okay to merge with None if not cmdset_b: return self # preserve system __commands sys_commands = self.get_system_cmds() + cmdset_b.get_system_cmds() if self.priority >= cmdset_b.priority: # A higher or equal priority than B mergetype = self.key_mergetypes.get(cmdset_b.key, self.mergetype) if mergetype == "Intersect": cmdset_c = intersect(self, cmdset_b, cmdset_b.duplicates) elif mergetype == "Replace": cmdset_c = replace(self, cmdset_b, cmdset_b.duplicates) elif mergetype == "Remove": cmdset_c = remove(self, cmdset_b, cmdset_b.duplicates) else: # Union cmdset_c = union(self, cmdset_b, cmdset_b.duplicates) else: # B higher priority than A mergetype = cmdset_b.key_mergetypes.get(self.key, cmdset_b.mergetype) if mergetype == "Intersect": cmdset_c = intersect(cmdset_b, self, self.duplicates) elif mergetype == "Replace": cmdset_c = replace(cmdset_b, self, self.duplicates) elif mergetype == "Remove": cmdset_c = remove(self, cmdset_b, self.duplicates) else: # Union cmdset_c = union(cmdset_b, self, self.duplicates) # we store actual_mergetype since key_mergetypes # might be different from the main mergetype. # This is used for diagnosis. cmdset_c.actual_mergetype = mergetype # return the system commands to the cmdset cmdset_c.add(sys_commands) return cmdset_c
Python
""" CmdSethandler The Cmdhandler tracks an object's 'Current CmdSet', which is the current merged sum of all CmdSets added to it. A CmdSet constitues a set of commands. The CmdSet works as a special intelligent container that, when added to other CmdSet make sure that same-name commands are treated correctly (usually so there are no doublets). This temporary but up-to-date merger of CmdSet is jointly called the Current Cmset. It is this Current CmdSet that the commandhandler looks through whenever a player enters a command (it also adds CmdSets from objects in the room in real-time). All player objects have a 'default cmdset' containing all the normal in-game mud commands (look etc). So what is all this cmdset complexity good for? In its simplest form, a CmdSet has no commands, only a key name. In this case the cmdset's use is up to each individual game - it can be used by an AI module for example (mobs in cmdset 'roam' move from room to room, in cmdset 'attack' they enter combat with players). Defining commands in cmdsets offer some further powerful game-design consequences however. Here are some examples: As mentioned above, all players always have at least the Default CmdSet. This contains the set of all normal-use commands in-game, stuff like look and @desc etc. Now assume our players end up in a dark room. You don't want the player to be able to do much in that dark room unless they light a candle. You could handle this by changing all your normal commands to check if the player is in a dark room. This rapidly goes unwieldly and error prone. Instead you just define a cmdset with only those commands you want to be available in the 'dark' cmdset - maybe a modified look command and a 'light candle' command - and have this completely replace the default cmdset. Another example: Say you want your players to be able to go fishing. You could implement this as a 'fish' command that fails whenever the player has no fishing rod. Easy enough. But what if you want to make fishing more complex - maybe you want four-five different commands for throwing your line, reeling in, etc? Most players won't (we assume) have fishing gear, and having all those detailed commands is cluttering up the command list. And what if you want to use the 'throw' command also for throwing rocks etc instead of 'using it up' for a minor thing like fishing? So instead you put all those detailed fishing commands into their own CommandSet called 'Fishing'. Whenever the player gives the command 'fish' (presumably the code checks there is also water nearby), only THEN this CommandSet is added to the Cmdhandler of the player. The 'throw' command (which normally throws rocks) is replaced by the custom 'fishing variant' of throw. What has happened is that the Fishing CommandSet was merged on top of the Default ones, and due to how we defined it, its command overrules the default ones. When we are tired of fishing, we give the 'go home' command (or whatever) and the Cmdhandler simply removes the fishing CommandSet so that we are back at defaults (and can throw rocks again). Since any number of CommandSets can be piled on top of each other, you can then implement separate sets for different situations. For example, you can have a 'On a boat' set, onto which you then tack on the 'Fishing' set. Fishing from a boat? No problem! """ import traceback from src.utils import logger, utils from src.commands.cmdset import CmdSet from src.server.models import ServerConfig CACHED_CMDSETS = {} def import_cmdset(python_path, cmdsetobj, emit_to_obj=None, no_logging=False): """ This helper function is used by the cmdsethandler to load a cmdset instance from a python module, given a python_path. It's usually accessed through the cmdsethandler's add() and add_default() methods. python_path - This is the full path to the cmdset object. cmdsetobj - the database object/typeclass on which this cmdset is to be assigned (this can be also channels and exits, as well as players but there will always be such an object) emit_to_obj - if given, error is emitted to this object (in addition to logging) no_logging - don't log/send error messages. This can be useful if import_cmdset is just used to check if this is a valid python path or not. function returns None if an error was encountered or path not found. """ try: try: #print "importing %s: CACHED_CMDSETS=%s" % (python_path, CACHED_CMDSETS) wanted_cache_key = python_path cmdsetclass = CACHED_CMDSETS.get(wanted_cache_key, None) errstring = "" if not cmdsetclass: #print "cmdset '%s' not in cache. Reloading %s on %s." % (wanted_cache_key, python_path, cmdsetobj) # Not in cache. Reload from disk. modulepath, classname = python_path.rsplit('.', 1) module = __import__(modulepath, fromlist=[True]) cmdsetclass = module.__dict__[classname] CACHED_CMDSETS[wanted_cache_key] = cmdsetclass #instantiate the cmdset (and catch its errors) if callable(cmdsetclass): cmdsetclass = cmdsetclass(cmdsetobj) return cmdsetclass except ImportError: errstring = "Error loading cmdset: Couldn't import module '%s'." errstring = errstring % modulepath raise except KeyError: errstring = "Error in loading cmdset: No cmdset class '%s' in %s." errstring = errstring % (classname, modulepath) raise except Exception: errstring = "\n%s\nCompile/Run error when loading cmdset '%s'." errstring = errstring % (traceback.format_exc(), python_path) raise except Exception: if errstring and not no_logging: print errstring logger.log_trace() if emit_to_obj and not ServerConfig.objects.conf("server_starting_mode"): object.__getattribute__(emit_to_obj, "msg")(errstring) logger.log_errmsg("Error: %s" % errstring) raise # have to raise, or we will not see any errors in some situations! # classes class CmdSetHandler(object): """ The CmdSetHandler is always stored on an object, this object is supplied as an argument. The 'current' cmdset is the merged set currently active for this object. This is the set the game engine will retrieve when determining which commands are available to the object. The cmdset_stack holds a history of all CmdSets to allow the handler to remove/add cmdsets at will. Doing so will re-calculate the 'current' cmdset. """ def __init__(self, obj): """ This method is called whenever an object is recreated. obj - this is a reference to the game object this handler belongs to. """ self.obj = obj # the id of the "merged" current cmdset for easy access. self.key = None # this holds the "merged" current command set self.current = None # this holds a history of CommandSets self.cmdset_stack = [CmdSet(cmdsetobj=self.obj, key="Empty")] # this tracks which mergetypes are actually in play in the stack self.mergetype_stack = ["Union"] # the subset of the cmdset_paths that are to be stored in the database self.permanent_paths = [""] #self.update(init_mode=True) is then called from the object __init__. def __str__(self): "Display current commands" string = "" mergelist = [] if len(self.cmdset_stack) > 1: # We have more than one cmdset in stack; list them all num = 0 #print self.cmdset_stack, self.mergetype_stack for snum, cmdset in enumerate(self.cmdset_stack): num = snum mergetype = self.mergetype_stack[snum] permstring = "non-perm" if cmdset.permanent: permstring = "perm" if mergetype != cmdset.mergetype: mergetype = "%s^" % (mergetype) string += "\n %i: <%s (%s, prio %i, %s)>: %s" % \ (snum, cmdset.key, mergetype, cmdset.priority, permstring, cmdset) mergelist.append(str(snum)) string += "\n" # Display the currently active cmdset, limited by self.obj's permissions mergetype = self.mergetype_stack[-1] if mergetype != self.current.mergetype: merged_on = self.cmdset_stack[-2].key mergetype = "custom %s on cmdset '%s'" % (mergetype, merged_on) if mergelist: string += " <Merged %s (%s, prio %i)>: %s" % ("+".join(mergelist), mergetype, self.current.priority, self.current) else: permstring = "non-perm" if self.current.permanent: permstring = "perm" string += " <%s (%s, prio %i, %s)>: %s" % (self.current.key, mergetype, self.current.priority, permstring, ", ".join(cmd.key for cmd in sorted(self.current, key=lambda o:o.key))) return string.strip() def update(self, init_mode=False): """ Re-adds all sets in the handler to have an updated current set. init_mode is used right after this handler was created; it imports all permanent cmdsets from db. """ if init_mode: # reimport all permanent cmdsets storage = self.obj.cmdset_storage #print "cmdset_storage:", self.obj.cmdset_storage if storage: self.cmdset_stack = [] for pos, path in enumerate(storage): if pos == 0 and not path: self.cmdset_stack = [CmdSet(cmdsetobj=self.obj, key="Empty")] elif path: cmdset = self.import_cmdset(path) if cmdset: cmdset.permanent = True self.cmdset_stack.append(cmdset) # merge the stack into a new merged cmdset new_current = None self.mergetype_stack = [] for cmdset in self.cmdset_stack: try: # for cmdset's '+' operator, order matters. new_current = cmdset + new_current except TypeError: continue self.mergetype_stack.append(new_current.actual_mergetype) self.current = new_current def import_cmdset(self, cmdset_path, emit_to_obj=None): """ Method wrapper for import_cmdset. load a cmdset from a module. cmdset_path - the python path to an cmdset object. emit_to_obj - object to send error messages to """ if not emit_to_obj: emit_to_obj = self.obj return import_cmdset(cmdset_path, self.obj, emit_to_obj) def add(self, cmdset, emit_to_obj=None, permanent=False): """ Add a cmdset to the handler, on top of the old ones. Default is to not make this permanent, i.e. the set will not survive a server reset. cmdset - can be a cmdset object or the python path to such an object. emit_to_obj - an object to receive error messages. permanent - this cmdset will remain across a server reboot Note: An interesting feature of this method is if you were to send it an *already instantiated cmdset* (i.e. not a class), the current cmdsethandler's obj attribute will then *not* be transferred over to this already instantiated set (this is because it might be used elsewhere and can cause strange effects). This means you could in principle have the handler launch command sets tied to a *different* object than the handler. Not sure when this would be useful, but it's a 'quirk' that has to be documented. """ if callable(cmdset): if not utils.inherits_from(cmdset, CmdSet): raise Exception("Only CmdSets can be added to the cmdsethandler!") cmdset = cmdset(self.obj) elif isinstance(cmdset, basestring): # this is (maybe) a python path. Try to import from cache. cmdset = self.import_cmdset(cmdset) if cmdset: if permanent: # store the path permanently cmdset.permanent = True storage = self.obj.cmdset_storage if not storage: storage = ["", cmdset.path] else: storage.append(cmdset.path) self.obj.cmdset_storage = storage else: cmdset.permanent = False self.cmdset_stack.append(cmdset) self.update() def add_default(self, cmdset, emit_to_obj=None, permanent=True): """ Add a new default cmdset. If an old default existed, it is replaced. If permanent is set, the set will survive a reboot. cmdset - can be a cmdset object or the python path to an instance of such an object. emit_to_obj - an object to receive error messages. permanent - save cmdset across reboots See also the notes for self.add(), which applies here too. """ if callable(cmdset): if not utils.inherits_from(cmdset, CmdSet): raise Exception("Only CmdSets can be added to the cmdsethandler!") cmdset = cmdset(self.obj) elif isinstance(cmdset, basestring): # this is (maybe) a python path. Try to import from cache. cmdset = self.import_cmdset(cmdset) if cmdset: if self.cmdset_stack: self.cmdset_stack[0] = cmdset self.mergetype_stack[0] = cmdset.mergetype else: self.cmdset_stack = [cmdset] self.mergetype_stack = [cmdset.mergetype] if permanent: cmdset.permanent = True storage = self.obj.cmdset_storage if storage: storage[0] = cmdset.path else: storage = [cmdset.path] self.obj.cmdset_storage = storage else: cmdset.permanent = False self.update() def delete(self, cmdset=None): """ Remove a cmdset from the handler. cmdset can be supplied either as a cmdset-key, an instance of the CmdSet or a python path to the cmdset. If no key is given, the last cmdset in the stack is removed. Whenever the cmdset_stack changes, the cmdset is updated. The default cmdset (first entry in stack) is never removed - remove it explicitly with delete_default. """ if len(self.cmdset_stack) < 2: # don't allow deleting default cmdsets here. return if not cmdset: # remove the last one in the stack cmdset = self.cmdset_stack.pop() if cmdset.permanent: storage = self.obj.cmdset_storage storage.pop() self.obj.cmdset_storage = storage else: # try it as a callable if callable(cmdset) and hasattr(cmdset, 'path'): delcmdsets = [cset for cset in self.cmdset_stack[1:] if cset.path == cmdset.path] else: # try it as a path or key delcmdsets = [cset for cset in self.cmdset_stack[1:] if cset.path == cmdset or cset.key == cmdset] storage = [] if any(cset.permanent for cset in delcmdsets): # only hit database if there's need to storage = self.obj.cmdset_storage for cset in delcmdsets: if cset.permanent: try: storage.remove(cset.path) except ValueError: pass for cset in delcmdsets: # clean the in-memory stack try: self.cmdset_stack.remove(cset) except ValueError: pass # re-sync the cmdsethandler. self.update() def delete_default(self): "This explicitly deletes the default cmdset. It's the only command that can." if self.cmdset_stack: cmdset = self.cmdset_stack[0] if cmdset.permanent: storage = self.obj.cmdset_storage if storage: storage[0] = "" else: storage = [""] self.cmdset_storage = storage self.cmdset_stack[0] = CmdSet(cmdsetobj=self.obj, key="Empty") else: self.cmdset_stack = [CmdSet(cmdsetobj=self.obj, key="Empty")] self.update() def all(self): """ Returns the list of cmdsets. Mostly useful to check if stack if empty or not. """ return self.cmdset_stack def clear(self): """ Removes all extra Command sets from the handler, leaving only the default one. """ self.cmdset_stack = [self.cmdset_stack[0]] self.mergetype_stack = [self.cmdset_stack[0].mergetype] storage = self.obj.cmdset_storage if storage: storage = storage[0] self.obj.cmdset_storage = storage self.update() def has_cmdset(self, cmdset_key, must_be_default=False): """ checks so the cmdsethandler contains a cmdset with the given key. must_be_default - only match against the default cmdset. """ if must_be_default: return self.cmdset_stack and self.cmdset_stack[0].key == cmdset_key else: return any([cmdset.key == cmdset_key for cmdset in self.cmdset_stack]) def all(self): """ Returns all cmdsets. """ return self.cmdset_stack def reset(self): """ Force reload of all cmdsets in handler. This should be called after CACHED_CMDSETS have been cleared (normally by @reload). """ new_cmdset_stack = [] new_mergetype_stack = [] for cmdset in self.cmdset_stack: if cmdset.key == "Empty": new_cmdset_stack.append(cmdset) new_mergetype_stack.append("Union") else: new_cmdset_stack.append(self.import_cmdset(cmdset.path)) new_mergetype_stack.append(cmdset.mergetype) self.cmdset_stack = new_cmdset_stack self.mergetype_stack = new_mergetype_stack self.update()
Python
""" Batch processors These commands implements the 'batch-command' and 'batch-code' processors, using the functionality in src.utils.batchprocessors. They allow for offline world-building. Batch-command is the simpler system. This reads a file (*.ev) containing a list of in-game commands and executes them in sequence as if they had been entered in the game (including permission checks etc). Example batch-command file: game/gamesrc/commands/examples/example_batch_cmd.ev Batch-code is a full-fledged python code interpreter that reads blocks of python code (*.py) and executes them in sequence. This allows for much more power than Batch-command, but requires knowing Python and the Evennia API. It is also a severe security risk and should therefore always be limited to superusers only. Example batch-code file: game/gamesrc/commands/examples/example_batch_code.py """ from traceback import format_exc from django.conf import settings from src.utils.batchprocessors import BATCHCMD, BATCHCODE from src.commands.cmdset import CmdSet from src.commands.default.muxcommand import MuxCommand HEADER_WIDTH = 70 UTF8_ERROR = \ """ {rDecode error in '%s'.{n This file contains non-ascii character(s). This is common if you wrote some input in a language that has more letters and special symbols than English; such as accents or umlauts. This is usually fine and fully supported! But for Evennia to know how to decode such characters in a universal way, the batchfile must be saved with the international 'UTF-8' encoding. This file is not. Please re-save the batchfile with the UTF-8 encoding (refer to the documentation of your text editor on how to do this, or switch to a better featured one) and try again. The (first) error was found with a character on line %s in the file. """ #------------------------------------------------------------ # Helper functions #------------------------------------------------------------ def format_header(caller, entry): """ Formats a header """ width = HEADER_WIDTH - 10 entry = entry.strip() header = entry[:min(width, min(len(entry), entry.find('\n')))] if len(entry) > width: header = "%s[...]" % header ptr = caller.ndb.batch_stackptr + 1 stacklen = len(caller.ndb.batch_stack) header = "{w%02i/%02i{G: %s{n" % (ptr, stacklen, header) # add extra space to the side for padding. header = "%s%s" % (header, " "*(width-len(header))) header = header.replace('\n', '\\n') return header def format_code(entry): """ Formats the viewing of code and errors """ code = "" for line in entry.split('\n'): code += "\n{G>>>{n %s" % line return code.strip() def batch_cmd_exec(caller): """ Helper function for executing a single batch-command entry """ ptr = caller.ndb.batch_stackptr stack = caller.ndb.batch_stack command = stack[ptr] caller.msg(format_header(caller, command)) try: caller.execute_cmd(command) except Exception: caller.msg(format_code(format_exc())) return False return True def batch_code_exec(caller): """ Helper function for executing a single batch-code entry """ ptr = caller.ndb.batch_stackptr stack = caller.ndb.batch_stack debug = caller.ndb.batch_debug codedict = stack[ptr] caller.msg(format_header(caller, codedict['code'])) err = BATCHCODE.code_exec(codedict, extra_environ={"caller":caller}, debug=debug) if err: caller.msg(format_code(err)) return False return True def step_pointer(caller, step=1): """ Step in stack, returning the item located. stackptr - current position in stack stack - the stack of units step - how many steps to move from stackptr """ ptr = caller.ndb.batch_stackptr stack = caller.ndb.batch_stack nstack = len(stack) if ptr + step <= 0: caller.msg("{RBeginning of batch file.") if ptr + step >= nstack: caller.msg("{REnd of batch file.") caller.ndb.batch_stackptr = max(0, min(nstack-1, ptr + step)) def show_curr(caller, showall=False): """ Show the current position in stack """ stackptr = caller.ndb.batch_stackptr stack = caller.ndb.batch_stack if stackptr >= len(stack): caller.ndb.batch_stackptr = len(stack) - 1 show_curr(caller, showall) return entry = stack[stackptr] if type(entry) == dict: # this is a batch-code entry string = format_header(caller, entry['code']) codeall = entry['code'].strip() else: # this is a batch-cmd entry string = format_header(caller, entry) codeall = entry.strip() string += "{G(hh for help)" if showall: for line in codeall.split('\n'): string += "\n{n>>> %s" % line caller.msg(string) def purge_processor(caller): """ This purges all effects running on the caller. """ try: del caller.ndb.batch_stack del caller.ndb.batch_stackptr del caller.ndb.batch_pythonpath del caller.ndb.batch_batchmode except: pass # clear everything but the default cmdset. caller.cmdset.delete(BatchSafeCmdSet) caller.cmdset.clear() caller.scripts.validate() # this will purge interactive mode #------------------------------------------------------------ # main access commands #------------------------------------------------------------ class CmdBatchCommands(MuxCommand): """ Build from batch-command file Usage: @batchcommands[/interactive] <python.path.to.file> Switch: interactive - this mode will offer more control when executing the batch file, like stepping, skipping, reloading etc. Runs batches of commands from a batch-cmd text file (*.ev). """ key = "@batchcommands" aliases = ["@batchcommand", "@batchcmd"] locks = "cmd:perm(batchcommands) or superuser()" help_category = "Building" def func(self): "Starts the processor." caller = self.caller args = self.args if not args: caller.msg("Usage: @batchcommands[/interactive] <path.to.file>") return python_path = self.args #parse indata file try: commands = BATCHCMD.parse_file(python_path) except UnicodeDecodeError, err: lnum = err.linenum caller.msg(UTF8_ERROR % (python_path, lnum)) return if not commands: string = "'%s' not found.\nYou have to supply the python path " string += "of the file relative to \none of your batch-file directories (%s)." caller.msg(string % (python_path, ", ".join(settings.BASE_BATCHPROCESS_PATHS))) return switches = self.switches # Store work data in cache caller.ndb.batch_stack = commands caller.ndb.batch_stackptr = 0 caller.ndb.batch_pythonpath = python_path caller.ndb.batch_batchmode = "batch_commands" caller.cmdset.add(BatchSafeCmdSet) if 'inter' in switches or 'interactive' in switches: # Allow more control over how batch file is executed # Set interactive state directly caller.cmdset.add(BatchInteractiveCmdSet) caller.msg("\nBatch-command processor - Interactive mode for %s ..." % python_path) show_curr(caller) else: caller.msg("Running Batch-command processor - Automatic mode for %s ..." % python_path) # add the 'safety' cmdset in case the batch processing adds cmdsets to us for inum in range(len(commands)): # loop through the batch file if not batch_cmd_exec(caller): return step_pointer(caller, 1) # clean out the safety cmdset and clean out all other temporary attrs. string = " Batchfile '%s' applied." % python_path caller.msg("{G%s" % string) purge_processor(caller) class CmdBatchCode(MuxCommand): """ Build from batch-code file Usage: @batchcode[/interactive] <python path to file> Switch: interactive - this mode will offer more control when executing the batch file, like stepping, skipping, reloading etc. debug - auto-delete all objects that has been marked as deletable in the script file (see example files for syntax). This is useful so as to to not leave multiple object copies behind when testing out the script. Runs batches of commands from a batch-code text file (*.py). """ key = "@batchcode" aliases = ["@batchcodes"] locks = "cmd:perm(batchcommands) or superuser()" help_category = "Building" def func(self): "Starts the processor." caller = self.caller args = self.args if not args: caller.msg("Usage: @batchcode[/interactive/debug] <path.to.file>") return python_path = self.args #parse indata file try: codes = BATCHCODE.parse_file(python_path) except UnicodeDecodeError, err: lnum = err.linenum caller.msg(UTF8_ERROR % (python_path, lnum)) return if not codes: string = "'%s' not found.\nYou have to supply the python path " string += "of the file relative to \nyour batch-file directory (%s)." caller.msg(string % (python_path, settings.BASE_BATCHPROCESS_PATH)) return switches = self.switches debug = False if 'debug' in switches: debug = True # Store work data in cache caller.ndb.batch_stack = codes caller.ndb.batch_stackptr = 0 caller.ndb.batch_pythonpath = python_path caller.ndb.batch_batchmode = "batch_code" caller.ndb.batch_debug = debug caller.cmdset.add(BatchSafeCmdSet) if 'inter' in switches or 'interactive'in switches: # Allow more control over how batch file is executed # Set interactive state directly caller.cmdset.add(BatchInteractiveCmdSet) caller.msg("\nBatch-code processor - Interactive mode for %s ..." % python_path) show_curr(caller) else: caller.msg("Running Batch-code processor - Automatic mode for %s ..." % python_path) # add the 'safety' cmdset in case the batch processing adds cmdsets to us for inum in range(len(codes)): # loop through the batch file if not batch_code_exec(caller): return step_pointer(caller, 1) string = " Batchfile '%s' applied." % python_path caller.msg("{G%s" % string) purge_processor(caller) #------------------------------------------------------------ # State-commands for the interactive batch processor modes # (these are the same for both processors) #------------------------------------------------------------ class CmdStateAbort(MuxCommand): """ @abort This is a safety feature. It force-ejects us out of the processor and to the default cmdset, regardless of what current cmdset the processor might have put us in (e.g. when testing buggy scripts etc). """ key = "@abort" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): "Exit back to default." purge_processor(self.caller) self.caller.msg("Exited processor and reset out active cmdset back to the default one.") class CmdStateLL(MuxCommand): """ ll Look at the full source for the current command definition. """ key = "ll" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): show_curr(self.caller, showall=True) class CmdStatePP(MuxCommand): """ pp Process the currently shown command definition. """ key = "pp" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): """ This checks which type of processor we are running. """ caller = self.caller if caller.ndb.batch_batchmode == "batch_code": batch_code_exec(caller) else: batch_cmd_exec(caller) class CmdStateRR(MuxCommand): """ rr Reload the batch file, keeping the current position in it. """ key = "rr" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller if caller.ndb.batch_batchmode == "batch_code": new_data = BATCHCODE.parse_file(caller.ndb.batch_pythonpath) else: new_data = BATCHCMD.parse_file(caller.ndb.batch_pythonpath) caller.ndb.batch_stack = new_data caller.msg(format_code("File reloaded. Staying on same command.")) show_curr(caller) class CmdStateRRR(MuxCommand): """ rrr Reload the batch file, starting over from the beginning. """ key = "rrr" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller if caller.ndb.batch_batchmode == "batch_code": BATCHCODE.parse_file(caller.ndb.batch_pythonpath) else: BATCHCMD.parse_file(caller.ndb.batch_pythonpath) caller.ndb.batch_stackptr = 0 caller.msg(format_code("File reloaded. Restarting from top.")) show_curr(caller) class CmdStateNN(MuxCommand): """ nn Go to next command. No commands are executed. """ key = "nn" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller arg = self.args if arg and arg.isdigit(): step = int(self.args) else: step = 1 step_pointer(caller, step) show_curr(caller) class CmdStateNL(MuxCommand): """ nl Go to next command, viewing its full source. No commands are executed. """ key = "nl" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller arg = self.args if arg and arg.isdigit(): step = int(self.args) else: step = 1 step_pointer(caller, step) show_curr(caller, showall=True) class CmdStateBB(MuxCommand): """ bb Backwards to previous command. No commands are executed. """ key = "bb" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller arg = self.args if arg and arg.isdigit(): step = -int(self.args) else: step = -1 step_pointer(caller, step) show_curr(caller) class CmdStateBL(MuxCommand): """ bl Backwards to previous command, viewing its full source. No commands are executed. """ key = "bl" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller arg = self.args if arg and arg.isdigit(): step = -int(self.args) else: step = -1 step_pointer(caller, step) show_curr(caller, showall=True) class CmdStateSS(MuxCommand): """ ss [steps] Process current command, then step to the next one. If steps is given, process this many commands. """ key = "ss" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller arg = self.args if arg and arg.isdigit(): step = int(self.args) else: step = 1 for istep in range(step): if caller.ndb.batch_batchmode == "batch_code": batch_code_exec(caller) else: batch_cmd_exec(caller) step_pointer(caller, 1) show_curr(caller) class CmdStateSL(MuxCommand): """ sl [steps] Process current command, then step to the next one, viewing its full source. If steps is given, process this many commands. """ key = "sl" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller arg = self.args if arg and arg.isdigit(): step = int(self.args) else: step = 1 for istep in range(step): if caller.ndb.batch_batchmode == "batch_code": batch_code_exec(caller) else: batch_cmd_exec(caller) step_pointer(caller, 1) show_curr(caller) class CmdStateCC(MuxCommand): """ cc Continue to process all remaining commands. """ key = "cc" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller nstack = len(caller.ndb.batch_stack) ptr = caller.ndb.batch_stackptr step = nstack - ptr for istep in range(step): if caller.ndb.batch_batchmode == "batch_code": batch_code_exec(caller) else: batch_cmd_exec(caller) step_pointer(caller, 1) show_curr(caller) del caller.ndb.batch_stack del caller.ndb.batch_stackptr del caller.ndb.batch_pythonpath del caller.ndb.batch_batchmode caller.msg(format_code("Finished processing batch file.")) class CmdStateJJ(MuxCommand): """ j <command number> Jump to specific command number """ key = "j" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller arg = self.args if arg and arg.isdigit(): number = int(self.args)-1 else: caller.msg(format_code("You must give a number index.")) return ptr = caller.ndb.batch_stackptr step = number - ptr step_pointer(caller, step) show_curr(caller) class CmdStateJL(MuxCommand): """ jl <command number> Jump to specific command number and view its full source. """ key = "jl" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): caller = self.caller arg = self.args if arg and arg.isdigit(): number = int(self.args)-1 else: caller.msg(format_code("You must give a number index.")) return ptr = caller.ndb.batch_stackptr step = number - ptr step_pointer(caller, step) show_curr(caller, showall=True) class CmdStateQQ(MuxCommand): """ qq Quit the batchprocessor. """ key = "qq" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): purge_processor(self.caller) self.caller.msg("Aborted interactive batch mode.") class CmdStateHH(MuxCommand): "Help command" key = "hh" help_category = "BatchProcess" locks = "cmd:perm(batchcommands)" def func(self): string = """ Interactive batch processing commands: nn [steps] - next command (no processing) nl [steps] - next & look bb [steps] - back to previous command (no processing) bl [steps] - back & look jj <N> - jump to command nr N (no processing) jl <N> - jump & look pp - process currently shown command (no step) ss [steps] - process & step sl [steps] - process & step & look ll - look at full definition of current command rr - reload batch file (stay on current) rrr - reload batch file (start from first) hh - this help list cc - continue processing to end, then quit. qq - quit (abort all remaining commands) @abort - this is a safety command that always is available regardless of what cmdsets gets added to us during batch-command processing. It immediately shuts down the processor and returns us to the default cmdset. """ self.caller.msg(string) #------------------------------------------------------------ # # Defining the cmdsets for the interactive batchprocessor # mode (same for both processors) # #------------------------------------------------------------ class BatchSafeCmdSet(CmdSet): """ The base cmdset for the batch processor. This sets a 'safe' @abort command that will always be available to get out of everything. """ key = "Batch_default" priority = 104 # override other cmdsets. def at_cmdset_creation(self): "Init the cmdset" self.add(CmdStateAbort()) class BatchInteractiveCmdSet(CmdSet): """ The cmdset for the interactive batch processor mode. """ key = "Batch_interactive" priority = 104 def at_cmdset_creation(self): "init the cmdset" self.add(CmdStateAbort()) self.add(CmdStateLL()) self.add(CmdStatePP()) self.add(CmdStateRR()) self.add(CmdStateRRR()) self.add(CmdStateNN()) self.add(CmdStateNL()) self.add(CmdStateBB()) self.add(CmdStateBL()) self.add(CmdStateSS()) self.add(CmdStateSL()) self.add(CmdStateCC()) self.add(CmdStateJJ()) self.add(CmdStateJL()) self.add(CmdStateQQ()) self.add(CmdStateHH())
Python
""" Admin commands """ import time, re from django.conf import settings from django.contrib.auth.models import User from src.players.models import PlayerDB from src.server.sessionhandler import SESSIONS from src.server.models import ServerConfig from src.utils import utils from src.commands.default.muxcommand import MuxCommand PERMISSION_HIERARCHY = [p.lower() for p in settings.PERMISSION_HIERARCHY] class CmdBoot(MuxCommand): """ @boot Usage @boot[/switches] <player obj> [: reason] Switches: quiet - Silently boot without informing player port - boot by port number instead of name or dbref Boot a player object from the server. If a reason is supplied it will be echoed to the user unless /quiet is set. """ key = "@boot" locks = "cmd:perm(boot) or perm(Wizards)" help_category = "Admin" def func(self): "Implementing the function" caller = self.caller args = self.args if not args: caller.msg("Usage: @boot[/switches] <player> [:reason]") return if ':' in args: args, reason = [a.strip() for a in args.split(':', 1)] else: args, reason = args, "" boot_list = [] if 'port' in self.switches: # Boot a particular port. sessions = SESSIONS.get_session_list(True) for sess in sessions: # Find the session with the matching port number. if sess.getClientAddress()[1] == int(args): boot_list.append(sess) break else: # Boot by player object pobj = caller.search("*%s" % args, global_search=True, player=True) if not pobj: return if pobj.character.has_player: if not pobj.access(caller, 'boot'): string = "You don't have the permission to boot %s." pobj.msg(string) return # we have a bootable object with a connected user matches = SESSIONS.sessions_from_player(pobj) for match in matches: boot_list.append(match) else: caller.msg("That object has no connected player.") return if not boot_list: caller.msg("No matches found.") return # Carry out the booting of the sessions in the boot list. feedback = None if not 'quiet' in self.switches: feedback = "You have been disconnected by %s.\n" % caller.name if reason: feedback += "\nReason given: %s" % reason for session in boot_list: name = session.uname session.msg(feedback) session.disconnect() caller.msg("You booted %s." % name) # regex matching IP addresses with wildcards, eg. 233.122.4.* IPREGEX = re.compile(r"[0-9*]{1,3}\.[0-9*]{1,3}\.[0-9*]{1,3}\.[0-9*]{1,3}") def list_bans(banlist): """ Helper function to display a list of active bans. Input argument is the banlist read into the two commands @ban and @undban below. """ if not banlist: return "No active bans were found." table = [["id"], ["name/ip"], ["date"], ["reason"]] table[0].extend([str(i+1) for i in range(len(banlist))]) for ban in banlist: if ban[0]: table[1].append(ban[0]) else: table[1].append(ban[1]) table[2].extend([ban[3] for ban in banlist]) table[3].extend([ban[4] for ban in banlist]) ftable = utils.format_table(table, 4) string = "{wActive bans:{x" for irow, row in enumerate(ftable): if irow == 0: srow = "\n" + "".join(row) srow = "{w%s{n" % srow.rstrip() else: srow = "\n" + "{w%s{n" % row[0] + "".join(row[1:]) string += srow.rstrip() return string class CmdBan(MuxCommand): """ ban a player from the server Usage: @ban [<name or ip> [: reason]] Without any arguments, shows numbered list of active bans. This command bans a user from accessing the game. Supply an optional reason to be able to later remember why the ban was put in place It is often to prefer over deleting a player with @delplayer. If banned by name, that player account can no longer be logged into. IP (Internet Protocol) address banning allows to block all access from a specific address or subnet. Use the asterisk (*) as a wildcard. Examples: @ban thomas - ban account 'thomas' @ban/ip 134.233.2.111 - ban specific ip address @ban/ip 134.233.2.* - ban all in a subnet @ban/ip 134.233.*.* - even wider ban A single IP filter is easy to circumvent by changing the computer (also, some ISPs assign only temporary IPs to their users in the first placer. Widening the IP block filter with wildcards might be tempting, but remember that blocking too much may accidentally also block innocent users connecting from the same country and region. """ key = "@ban" aliases = ["@bans"] locks = "cmd:perm(ban) or perm(Immortals)" help_category="Admin" def func(self): """ Bans are stored in a serverconf db object as a list of dictionaries: [ (name, ip, ipregex, date, reason), (name, ip, ipregex, date, reason),... ] where name and ip are set by the user and are shown in lists. ipregex is a converted form of ip where the * is replaced by an appropriate regex pattern for fast matching. date is the time stamp the ban was instigated and 'reason' is any optional info given to the command. Unset values in each tuple is set to the empty string. """ banlist = ServerConfig.objects.conf('server_bans') if not banlist: banlist = [] if not self.args or (self.switches and not any(switch in ('ip', 'name') for switch in self.switches)): self.caller.msg(list_bans(banlist)) return now = time.ctime() reason = "" if ':' in self.args: ban, reason = self.args.rsplit(':',1) else: ban = self.args ban = ban.lower() ipban = IPREGEX.findall(ban) if not ipban: # store as name typ = "Name" bantup = (ban, "", "", now, reason) else: # an ip address. typ = "IP" ban = ipban[0] # replace * with regex form and compile it ipregex = ban.replace('.','\.') ipregex = ipregex.replace('*', '[0-9]{1,3}') print "regex:",ipregex ipregex = re.compile(r"%s" % ipregex) bantup = ("", ban, ipregex, now, reason) # save updated banlist banlist.append(bantup) ServerConfig.objects.conf('server_bans', banlist) self.caller.msg("%s-Ban {w%s{x was added." % (typ, ban)) class CmdUnban(MuxCommand): """ remove a ban Usage: @unban <banid> This will clear a player name/ip ban previously set with the @ban command. Use this command without an argument to view a numbered list of bans. Use the numbers in this list to select which one to unban. """ key = "@unban" locks = "cmd:perm(unban) or perm(Immortals)" help_category="Admin" def func(self): "Implement unbanning" banlist = ServerConfig.objects.conf('server_bans') if not self.args: self.caller.msg(list_bans(banlist)) return try: num = int(self.args) except Exception: self.caller.msg("You must supply a valid ban id to clear.") return if not banlist: self.caller.msg("There are no bans to clear.") elif not (0 < num < len(banlist) + 1): self.caller.msg("Ban id {w%s{x was not found." % self.args) else: # all is ok, clear ban ban = banlist[num-1] del banlist[num-1] ServerConfig.objects.conf('server_bans', banlist) self.caller.msg("Cleared ban %s: %s" % (num, " ".join([s for s in ban[:2]]))) class CmdDelPlayer(MuxCommand): """ delplayer - delete player from server Usage: @delplayer[/switch] <name> [: reason] Switch: delobj - also delete the player's currently assigned in-game object. Completely deletes a user from the server database, making their nick and e-mail again available. """ key = "@delplayer" locks = "cmd:perm(delplayer) or perm(Immortals)" help_category = "Admin" def func(self): "Implements the command." caller = self.caller args = self.args if hasattr(caller, 'player'): caller = caller.player if not args: caller.msg("Usage: @delplayer[/delobj] <player/user name or #id> [: reason]") return reason = "" if ':' in args: args, reason = [arg.strip() for arg in args.split(':', 1)] # We use player_search since we want to be sure to find also players # that lack characters. players = caller.search("*%s" % args, player=True) if not players: try: players = PlayerDB.objects.filter(id=args) except ValueError: pass if not players: # try to find a user instead of a Player try: user = User.objects.get(id=args) except Exception: try: user = User.objects.get(username__iexact=args) except Exception: string = "No Player nor User found matching '%s'." % args caller.msg(string) return try: player = user.get_profile() except Exception: player = None if player and not player.access(caller, 'delete'): string = "You don't have the permissions to delete this player." caller.msg(string) return string = "" name = user.username user.delete() if player: name = player.name player.delete() string = "Player %s was deleted." % name else: string += "The User %s was deleted. It had no Player associated with it." % name caller.msg(string) return elif utils.is_iter(players): string = "There were multiple matches:" for player in players: string += "\n %s %s" % (player.id, player.key) return else: # one single match player = players user = player.user character = player.character if not player.access(caller, 'delete'): string = "You don't have the permissions to delete that player." caller.msg(string) return uname = user.username # boot the player then delete if character and character.has_player: caller.msg("Booting and informing player ...") string = "\nYour account '%s' is being *permanently* deleted.\n" % uname if reason: string += " Reason given:\n '%s'" % reason character.msg(string) caller.execute_cmd("@boot %s" % uname) player.delete() user.delete() caller.msg("Player %s was successfully deleted." % uname) class CmdEmit(MuxCommand): """ @emit Usage: @emit[/switches] [<obj>, <obj>, ... =] <message> @remit [<obj>, <obj>, ... =] <message> @pemit [<obj>, <obj>, ... =] <message> Switches: room : limit emits to rooms only (default) players : limit emits to players only contents : send to the contents of matched objects too Emits a message to the selected objects or to your immediate surroundings. If the object is a room, send to its contents. @remit and @pemit are just limited forms of @emit, for sending to rooms and to players respectively. """ key = "@emit" aliases = ["@pemit", "@remit"] locks = "cmd:perm(emit) or perm(Builders)" help_category = "Admin" def func(self): "Implement the command" caller = self.caller args = self.args if not args: string = "Usage: " string += "\n@emit[/switches] [<obj>, <obj>, ... =] <message>" string += "\n@remit [<obj>, <obj>, ... =] <message>" string += "\n@pemit [<obj>, <obj>, ... =] <message>" caller.msg(string) return rooms_only = 'rooms' in self.switches players_only = 'players' in self.switches send_to_contents = 'contents' in self.switches # we check which command was used to force the switches if self.cmdstring == '@remit': rooms_only = True elif self.cmdstring == '@pemit': players_only = True if not self.rhs: message = self.args objnames = [caller.location.key] else: message = self.rhs objnames = self.lhslist # send to all objects for objname in objnames: obj = caller.search(objname, global_search=True) if not obj: return if rooms_only and not obj.location == None: caller.msg("%s is not a room. Ignored." % objname) continue if players_only and not obj.has_player: caller.msg("%s has no active player. Ignored." % objname) continue if obj.access(caller, 'tell'): obj.msg(message) if send_to_contents: for content in obj.contents: content.msg(message) caller.msg("Emitted to %s and its contents." % objname) else: caller.msg("Emitted to %s." % objname) else: caller.msg("You are not allowed to send to %s." % objname) class CmdNewPassword(MuxCommand): """ @setpassword Usage: @userpassword <user obj> = <new password> Set a player's password. """ key = "@userpassword" locks = "cmd:perm(newpassword) or perm(Wizards)" help_category = "Admin" def func(self): "Implement the function." caller = self.caller if not self.rhs: caller.msg("Usage: @userpassword <user obj> = <new password>") return # the player search also matches 'me' etc. player = caller.search("*%s" % self.lhs, global_search=True, player=True) if not player: return player.user.set_password(self.rhs) player.user.save() caller.msg("%s - new password set to '%s'." % (player.name, self.rhs)) if player.character != caller: player.msg("%s has changed your password to '%s'." % (caller.name, self.rhs)) class CmdPerm(MuxCommand): """ @perm - set permissions Usage: @perm[/switch] <object> [= <permission>[,<permission>,...]] @perm[/switch] *<player> [= <permission>[,<permission>,...]] Switches: del : delete the given permission from <object> or <player>. player : set permission on a player (same as adding * to name) This command sets/clears individual permission strings on an object or player. If no permission is given, list all permissions on <object>. """ key = "@perm" aliases = "@setperm" locks = "cmd:perm(perm) or perm(Immortals)" help_category = "Admin" def func(self): "Implement function" caller = self.caller switches = self.switches lhs, rhs = self.lhs, self.rhs if not self.args: string = "Usage: @perm[/switch] object [ = permission, permission, ...]" caller.msg(string) return playermode = 'player' in self.switches or lhs.startswith('*') # locate the object obj = caller.search(lhs, global_search=True, player=playermode) if not obj: return if not rhs: if not obj.access(caller, 'examine'): caller.msg("You are not allowed to examine this object.") return string = "Permissions on {w%s{n: " % obj.key if not obj.permissions: string += "<None>" else: string += ", ".join(obj.permissions) if hasattr(obj, 'player') and hasattr(obj.player, 'is_superuser') and obj.player.is_superuser: string += "\n(... but this object is currently controlled by a SUPERUSER! " string += "All access checks are passed automatically.)" caller.msg(string) return # we supplied an argument on the form obj = perm if not obj.access(caller, 'control'): caller.msg("You are not allowed to edit this object's permissions.") return cstring = "" tstring = "" if 'del' in switches: # delete the given permission(s) from object. for perm in self.rhslist: try: index = obj.permissions.index(perm) except ValueError: cstring += "\nPermission '%s' was not defined on %s." % (perm, obj.name) continue permissions = obj.permissions del permissions[index] obj.permissions = permissions cstring += "\nPermission '%s' was removed from %s." % (perm, obj.name) tstring += "\n%s revokes the permission '%s' from you." % (caller.name, perm) else: # add a new permission permissions = obj.permissions caller.permissions for perm in self.rhslist: # don't allow to set a permission higher in the hierarchy than the one the # caller has (to prevent self-escalation) if perm.lower() in PERMISSION_HIERARCHY and not obj.locks.check_lockstring(caller, "dummy:perm(%s)" % perm): caller.msg("You cannot assign a permission higher than the one you have yourself.") return if perm in permissions: cstring += "\nPermission '%s' is already defined on %s." % (rhs, obj.name) else: permissions.append(perm) obj.permissions = permissions cstring += "\nPermission '%s' given to %s." % (rhs, obj.name) tstring += "\n%s gives you the permission '%s'." % (caller.name, rhs) caller.msg(cstring.strip()) if tstring: obj.msg(tstring.strip()) class CmdWall(MuxCommand): """ @wall Usage: @wall <message> Announces a message to all connected players. """ key = "@wall" locks = "cmd:perm(wall) or perm(Wizards)" help_category = "Admin" def func(self): "Implements command" if not self.args: self.caller.msg("Usage: @wall <message>") return message = "%s shouts \"%s\"" % (self.caller.name, self.args) SESSIONS.announce_all(message)
Python
""" Building and world design commands """ from django.conf import settings from src.objects.models import ObjectDB, ObjAttribute from src.players.models import PlayerAttribute from src.utils import create, utils, debug from src.commands.default.muxcommand import MuxCommand # used by @find CHAR_TYPECLASS = settings.BASE_CHARACTER_TYPECLASS class ObjManipCommand(MuxCommand): """ This is a parent class for some of the defining objmanip commands since they tend to have some more variables to define new objects. Each object definition can have several components. First is always a name, followed by an optional alias list and finally an some optional data, such as a typeclass or a location. A comma ',' separates different objects. Like this: name1;alias;alias;alias:option, name2;alias;alias ... Spaces between all components are stripped. A second situation is attribute manipulation. Such commands are simpler and offer combinations objname/attr/attr/attr, objname/attr, ... """ # OBS - this is just a parent - it's not intended to actually be # included in a commandset on its own! def parse(self): """ We need to expand the default parsing to get all the cases, see the module doc. """ # get all the normal parsing done (switches etc) super(ObjManipCommand, self).parse() obj_defs = ([],[]) # stores left- and right-hand side of '=' obj_attrs = ([], []) # " for iside, arglist in enumerate((self.lhslist, self.rhslist)): # lhslist/rhslist is already split by ',' at this point for objdef in arglist: aliases, option, attrs = [], None, [] if ':' in objdef: objdef, option = [part.strip() for part in objdef.rsplit(':', 1)] if ';' in objdef: objdef, aliases = [part.strip() for part in objdef.split(';', 1)] aliases = [alias.strip() for alias in aliases.split(';') if alias.strip()] if '/' in objdef: objdef, attrs = [part.strip() for part in objdef.split('/', 1)] attrs = [part.strip().lower() for part in attrs.split('/') if part.strip()] # store data obj_defs[iside].append({"name":objdef, 'option':option, 'aliases':aliases}) obj_attrs[iside].append({"name":objdef, 'attrs':attrs}) # store for future access self.lhs_objs = obj_defs[0] self.rhs_objs = obj_defs[1] self.lhs_objattr = obj_attrs[0] self.rhs_objattr = obj_attrs[1] class CmdSetObjAlias(MuxCommand): """ Adding permanent aliases Usage: @alias <obj> [= [alias[,alias,alias,...]]] Assigns aliases to an object so it can be referenced by more than one name. Assign empty to remove all aliases from object. Observe that this is not the same thing as aliases created with the 'alias' command! Aliases set with @alias are changing the object in question, making those aliases usable by everyone. """ key = "@alias" aliases = "@setobjalias" locks = "cmd:perm(setobjalias) or perm(Builders)" help_category = "Building" def func(self): "Set the aliases." caller = self.caller if not self.lhs: string = "Usage: @alias <obj> [= [alias[,alias ...]]]" self.caller.msg(string) return objname = self.lhs # Find the object to receive aliases obj = caller.search(objname, global_search=True) if not obj: return if self.rhs == None: # no =, so we just list aliases on object. aliases = obj.aliases if aliases: caller.msg("Aliases for '%s': %s" % (obj.key, ", ".join(aliases))) else: caller.msg("No aliases exist for '%s'." % obj.key) return if not obj.access(caller, 'edit'): caller.msg("You don't have permission to do that.") return if not self.rhs: # we have given an empty =, so delete aliases old_aliases = obj.aliases if old_aliases: caller.msg("Cleared aliases from %s: %s" % (obj.key, ", ".join(old_aliases))) del obj.dbobj.aliases else: caller.msg("No aliases to clear.") return # merge the old and new aliases (if any) old_aliases = obj.aliases new_aliases = [alias.strip().lower() for alias in self.rhs.split(',') if alias.strip()] # make the aliases only appear once old_aliases.extend(new_aliases) aliases = list(set(old_aliases)) # save back to object. obj.aliases = aliases # we treat this as a re-caching (relevant for exits to re-build their exit commands with the correct aliases) caller.msg("Aliases for '%s' are now set to %s." % (obj.key, ", ".join(obj.aliases))) class CmdCopy(ObjManipCommand): """ @copy - copy objects Usage: @copy[/reset] <original obj> [= new_name][;alias;alias..][:new_location] [,new_name2 ...] switch: reset - make a 'clean' copy off the object, thus removing any changes that might have been made to the original since it was first created. Create one or more copies of an object. If you don't supply any targets, one exact copy of the original object will be created with the name *_copy. """ key = "@copy" locks = "cmd:perm(copy) or perm(Builders)" help_category = "Building" def func(self): "Uses ObjManipCommand.parse()" caller = self.caller args = self.args if not args: caller.msg("Usage: @copy <obj> [=new_name[;alias;alias..]][:new_location] [, new_name2...]") return if not self.rhs: # this has no target =, so an identical new object is created. from_obj_name = self.args from_obj = caller.search(from_obj_name) if not from_obj: return to_obj_name = "%s_copy" % from_obj_name to_obj_aliases = ["%s_copy" % alias for alias in from_obj.aliases] copiedobj = ObjectDB.objects.copy_object(from_obj, new_key=to_obj_name, new_aliases=to_obj_aliases) if copiedobj: string = "Identical copy of %s, named '%s' was created." % (from_obj_name, to_obj_name) else: string = "There was an error copying %s." else: # we have specified =. This might mean many object targets from_obj_name = self.lhs_objs[0]['name'] from_obj = caller.search(from_obj_name) if not from_obj: return for objdef in self.rhs_objs: # loop through all possible copy-to targets to_obj_name = objdef['name'] to_obj_aliases = objdef['aliases'] to_obj_location = objdef['option'] if to_obj_location: to_obj_location = caller.search(to_obj_location, global_search=True) if not to_obj_location: return copiedobj = ObjectDB.objects.copy_object(from_obj, new_key=to_obj_name, new_location=to_obj_location, new_aliases=to_obj_aliases) if copiedobj: string = "Copied %s to '%s' (aliases: %s)." % (from_obj_name, to_obj_name, to_obj_aliases) else: string = "There was an error copying %s to '%s'." % (from_obj_name, to_obj_name) # we are done, echo to user caller.msg(string) class CmdCpAttr(ObjManipCommand): """ @cpattr - copy attributes Usage: @cpattr[/switch] <obj>/<attr> = <obj1>/<attr1> [,<obj2>/<attr2>,<obj3>/<attr3>,...] @cpattr[/switch] <obj>/<attr> = <obj1> [,<obj2>,<obj3>,...] @cpattr[/switch] <attr> = <obj1>/<attr1> [,<obj2>/<attr2>,<obj3>/<attr3>,...] @cpattr[/switch] <attr> = <obj1>[,<obj2>,<obj3>,...] Switches: move - delete the attribute from the source object after copying. Example: @cpattr coolness = Anna/chillout, Anna/nicety, Tom/nicety -> copies the coolness attribute (defined on yourself), to attributes on Anna and Tom. Copy the attribute one object to one or more attributes on another object. If you don't supply a source object, yourself is used. """ key = "@cpattr" locks = "cmd:perm(cpattr) or perm(Builders)" help_category = "Building" def func(self): """ Do the copying. """ caller = self.caller if not self.rhs: string = """Usage: @cpattr[/switch] <obj>/<attr> = <obj1>/<attr1> [,<obj2>/<attr2>,<obj3>/<attr3>,...] @cpattr[/switch] <obj>/<attr> = <obj1> [,<obj2>,<obj3>,...] @cpattr[/switch] <attr> = <obj1>/<attr1> [,<obj2>/<attr2>,<obj3>/<attr3>,...] @cpattr[/switch] <attr> = <obj1>[,<obj2>,<obj3>,...]""" caller.msg(string) return lhs_objattr = self.lhs_objattr to_objs = self.rhs_objattr from_obj_name = lhs_objattr[0]['name'] from_obj_attrs = lhs_objattr[0]['attrs'] if not from_obj_attrs: # this means the from_obj_name is actually an attribute name on self. from_obj_attrs = [from_obj_name] from_obj = self.caller from_obj_name = self.caller.name else: from_obj = caller.search(from_obj_name) if not from_obj or not to_objs: caller.msg("You have to supply both source object and target(s).") return if not from_obj.has_attribute(from_obj_attrs[0]): caller.msg("%s doesn't have an attribute %s." % (from_obj_name, from_obj_attrs[0])) return srcvalue = from_obj.get_attribute(from_obj_attrs[0]) #copy to all to_obj:ects if "move" in self.switches: string = "Moving " else: string = "Copying " string += "%s/%s (with value %s) ..." % (from_obj_name, from_obj_attrs[0], srcvalue) for to_obj in to_objs: to_obj_name = to_obj['name'] to_obj_attrs = to_obj['attrs'] to_obj = caller.search(to_obj_name) if not to_obj: string += "\nCould not find object '%s'" % to_obj_name continue for inum, from_attr in enumerate(from_obj_attrs): try: to_attr = to_obj_attrs[inum] except IndexError: # if there are too few attributes given # on the to_obj, we copy the original name instead. to_attr = from_attr to_obj.set_attribute(to_attr, srcvalue) if "move" in self.switches and not (from_obj == to_obj and from_attr == to_attr): from_obj.del_attribute(from_attr) string += "\nMoved %s.%s -> %s.%s." % (from_obj.name, from_attr, to_obj_name, to_attr) else: string += "\nCopied %s.%s -> %s.%s." % (from_obj.name, from_attr, to_obj_name, to_attr) caller.msg(string) class CmdMvAttr(ObjManipCommand): """ @mvattr - move attributes Usage: @mvattr[/switch] <obj>/<attr> = <obj1>/<attr1> [,<obj2>/<attr2>,<obj3>/<attr3>,...] @mvattr[/switch] <obj>/<attr> = <obj1> [,<obj2>,<obj3>,...] @mvattr[/switch] <attr> = <obj1>/<attr1> [,<obj2>/<attr2>,<obj3>/<attr3>,...] @mvattr[/switch] <attr> = <obj1>[,<obj2>,<obj3>,...] Switches: copy - Don't delete the original after moving. Move an attribute from one object to one or more attributes on another object. If you don't supply a source object, yourself is used. """ key = "@mvattr" locks = "cmd:perm(mvattr) or perm(Builders)" help_category = "Building" def func(self): """ Do the moving """ if not self.rhs: string = """Usage: @mvattr[/switch] <obj>/<attr> = <obj1>/<attr1> [,<obj2>/<attr2>,<obj3>/<attr3>,...] @mvattr[/switch] <obj>/<attr> = <obj1> [,<obj2>,<obj3>,...] @mvattr[/switch] <attr> = <obj1>/<attr1> [,<obj2>/<attr2>,<obj3>/<attr3>,...] @mvattr[/switch] <attr> = <obj1>[,<obj2>,<obj3>,...]""" self.caller.msg(string) return # simply use @cpattr for all the functionality if "copy" in self.switches: self.caller.execute_cmd("@cpattr %s" % self.args) else: self.caller.execute_cmd("@cpattr/move %s" % self.args) class CmdCreate(ObjManipCommand): """ @create - create new objects Usage: @create[/drop] objname[;alias;alias...][:typeclass], objname... switch: drop - automatically drop the new object into your current location (this is not echoed) this also sets the new object's home to the current location rather than to you. Creates one or more new objects. If typeclass is given, the object is created as a child of this typeclass. The typeclass script is assumed to be located under game/gamesrc/types and any further directory structure is given in Python notation. So if you have a correct typeclass object defined in game/gamesrc/types/examples/red_button.py, you could create a new object of this type like this: @create button;red : examples.red_button.RedButton """ key = "@create" locks = "cmd:perm(create) or perm(Builders)" help_category = "Building" def func(self): """ Creates the object. """ caller = self.caller if not self.args: string = "Usage: @create[/drop] <newname>[;alias;alias...] [:typeclass_path]" caller.msg(string) return # create the objects for objdef in self.lhs_objs: string = "" name = objdef['name'] aliases = objdef['aliases'] typeclass = objdef['option'] # create object (if not a valid typeclass, the default # object typeclass will automatically be used) lockstring = "control:id(%s);examine:perm(Builders);delete:id(%s) or perm(Wizards);get:all()" % (caller.id, caller.id) obj = create.create_object(typeclass, name, caller, home=caller, aliases=aliases, locks=lockstring) if not obj: string = "Error when creating object." continue if aliases: string = "You create a new %s: %s (aliases: %s)." string = string % (obj.typeclass.typename, obj.name, ", ".join(aliases)) else: string = "You create a new %s: %s." string = string % (obj.typeclass.typename, obj.name) # set a default desc if not obj.db.desc: obj.db.desc = "You see nothing special." if 'drop' in self.switches: if caller.location: obj.home = caller.location obj.move_to(caller.location, quiet=True) if string: caller.msg(string) class CmdDebug(MuxCommand): """ Debug game entities Usage: @debug[/switch] <path to code> Switches: obj - debug an object script - debug a script Examples: @debug/script game.gamesrc.scripts.myscript.MyScript @debug/script myscript.MyScript @debug/obj examples.red_button.RedButton This command helps when debugging the codes of objects and scripts. It creates the given object and runs tests on its hooks. """ key = "@debug" locks = "cmd:perm(debug) or perm(Builders)" help_category = "Building" def func(self): "Running the debug" if not self.args or not self.switches: self.caller.msg("Usage: @debug[/obj][/script] <path>") return path = self.args if 'obj' in self.switches or 'object' in self.switches: # create and debug the object self.caller.msg(debug.debug_object(path, self.caller)) self.caller.msg(debug.debug_object_scripts(path, self.caller)) elif 'script' in self.switches: self.caller.msg(debug.debug_syntax_script(path)) class CmdDesc(MuxCommand): """ @desc - describe an object or room Usage: @desc [<obj> =] >description> Setts the "desc" attribute on an object. If an object is not given, describe the current room. """ key = "@desc" aliases = "@describe" locks = "cmd:perm(desc) or perm(Builders)" help_category = "Building" def func(self): "Define command" caller = self.caller if not self.args: caller.msg("Usage: @desc [<obj> =] >description>") return if self.rhs: # We have an = obj = caller.search(self.lhs) if not obj: return desc = self.rhs else: obj = caller.location desc = self.args # storing the description obj.db.desc = desc caller.msg("The description was set on %s." % obj.key) class CmdDestroy(MuxCommand): """ @destroy - remove objects from the game Usage: @destroy[/switches] [obj, obj2, obj3, [dbref-dbref], ...] switches: override - The @destroy command will usually avoid accidentally destroying player objects. This switch overrides this safety. examples: @destroy house, roof, door, 44-78 @destroy 5-10, flower, 45 Destroys one or many objects. If dbrefs are used, a range to delete can be given, e.g. 4-10. Also the end points will be deleted. """ key = "@destroy" aliases = ["@delete", "@del"] locks = "cmd:perm(destroy) or perm(Builders)" help_category = "Building" def func(self): "Implements the command." caller = self.caller if not self.args or not self.lhslist: caller.msg("Usage: @destroy[/switches] [obj, obj2, obj3, [dbref-dbref],...]") return "" def delobj(objname): # helper function for deleting a single object string = "" obj = caller.search(objname) if not obj: self.caller.msg(" (Objects to destroy must either be local or specified with a unique dbref.)") return "" objname = obj.name if not obj.access(caller, 'delete'): return "\nYou don't have permission to delete %s." % objname if obj.player and not 'override' in self.switches: return "\nObject %s is controlled by an active player. Use /override to delete anyway." % objname had_exits = hasattr(obj, "exits") and obj.exits had_objs = hasattr(obj, "contents") and any(obj for obj in obj.contents if not (hasattr(obj, "exits") and obj not in obj.exits)) # do the deletion okay = obj.delete() if not okay: string += "\nERROR: %s not deleted, probably because at_obj_delete() returned False." % objname else: string += "\n%s was destroyed." % objname if had_exits: string += " Exits to and from %s were destroyed as well." % objname if had_objs: string += " Objects inside %s were moved to their homes." % objname return string string = "" for objname in self.lhslist: if '-' in objname: # might be a range of dbrefs dmin, dmax = [utils.dbref(part) for part in objname.split('-', 1)] if dmin and dmax: for dbref in range(int(dmin),int(dmax+1)): string += delobj(str(dbref)) else: string += delobj(objname) else: string += delobj(objname) if string: caller.msg(string.strip()) class CmdDig(ObjManipCommand): """ @dig - build and connect new rooms to the current one Usage: @dig[/switches] roomname[;alias;alias...][:typeclass] [= exit_to_there[;alias][:typeclass]] [, exit_to_here[;alias][:typeclass]] Switches: tel or teleport - move yourself to the new room Examples: @dig kitchen = north;n, south;s @dig house:myrooms.MyHouseTypeclass @dig sheer cliff;cliff;sheer = climb up, climb down This command is a convenient way to build rooms quickly; it creates the new room and you can optionally set up exits back and forth between your current room and the new one. You can add as many aliases as you like to the name of the room and the exits in question; an example would be 'north;no;n'. """ key = "@dig" locks = "cmd:perm(dig) or perm(Builders)" help_category = "Building" def func(self): "Do the digging. Inherits variables from ObjManipCommand.parse()" caller = self.caller if not self.lhs: string = "Usage:@ dig[/teleport] roomname[;alias;alias...][:parent] [= exit_there" string += "[;alias;alias..][:parent]] " string += "[, exit_back_here[;alias;alias..][:parent]]" caller.msg(string) return room = self.lhs_objs[0] if not room["name"]: caller.msg("You must supply a new room name.") return location = caller.location # Create the new room typeclass = room['option'] if not typeclass: typeclass = settings.BASE_ROOM_TYPECLASS # create room lockstring = "control:id(%s) or perm(Immortals); delete:id(%s) or perm(Wizards); edit:id(%s) or perm(Wizards)" lockstring = lockstring % (caller.dbref, caller.dbref, caller.dbref) new_room = create.create_object(typeclass, room["name"], aliases=room["aliases"]) new_room.locks.add(lockstring) alias_string = "" if new_room.aliases: alias_string = " (%s)" % ", ".join(new_room.aliases) room_string = "Created room %s(%s)%s of type %s." % (new_room, new_room.dbref, alias_string, typeclass) # create exit to room exit_to_string = "" exit_back_string = "" if self.rhs_objs: to_exit = self.rhs_objs[0] if not to_exit["name"]: exit_to_string = \ "\nNo exit created to new room." elif not location: exit_to_string = \ "\nYou cannot create an exit from a None-location." else: # Build the exit to the new room from the current one typeclass = to_exit["option"] if not typeclass: typeclass = settings.BASE_EXIT_TYPECLASS new_to_exit = create.create_object(typeclass, to_exit["name"], location, aliases=to_exit["aliases"], locks=lockstring, destination=new_room) alias_string = "" if new_to_exit.aliases: alias_string = " (%s)" % ", ".join(new_to_exit.aliases) exit_to_string = "\nCreated Exit from %s to %s: %s(%s)%s." exit_to_string = exit_to_string % (location.name, new_room.name, new_to_exit, new_to_exit.dbref, alias_string) # Create exit back from new room if len(self.rhs_objs) > 1: # Building the exit back to the current room back_exit = self.rhs_objs[1] if not back_exit["name"]: exit_back_string = \ "\nNo back exit created." elif not location: exit_back_string = \ "\nYou cannot create an exit back to a None-location." else: typeclass = back_exit["option"] if not typeclass: typeclass = settings.BASE_EXIT_TYPECLASS new_back_exit = create.create_object(typeclass, back_exit["name"], new_room, aliases=back_exit["aliases"], locks=lockstring, destination=location) alias_string = "" if new_back_exit.aliases: alias_string = " (%s)" % ", ".join(new_back_exit.aliases) exit_back_string = "\nCreated Exit back from %s to %s: %s(%s)%s." exit_back_string = exit_back_string % (new_room.name, location.name, new_back_exit, new_back_exit.dbref, alias_string) caller.msg("%s%s%s" % (room_string, exit_to_string, exit_back_string)) if new_room and ('teleport' in self.switches or "tel" in self.switches): caller.move_to(new_room) class CmdTunnel(MuxCommand): """ dig in often-used directions Usage: @tunnel[/switch] <direction> [= roomname[;alias;alias;...][:typeclass]] Switches: oneway - do not create an exit back to the current location tel - teleport to the newly created room Example: @tunnel n @tunnel n = house;mike's place;green building This is a simple way to build using pre-defined directions: {wn,ne,e,se,s,sw,w,nw{n (north, northeast etc) {wu,d{n (up and down) {wi,o{n (in and out) The full names (north, in, southwest, etc) will always be put as main name for the exit, using the abbreviation as an alias (so an exit will always be able to be used with both "north" as well as "n" for example). Opposite directions will automatically be created back from the new room unless the /oneway switch is given. For more flexibility and power in creating rooms, use @dig. """ key = "@tunnel" aliases = ["@tun"] locks = "cmd: perm(tunnel) or perm(Builders)" help_category = "Building" # store the direction, full name and its opposite directions = {"n" : ("north", "s"), "ne": ("northeast", "sw"), "e" : ("east", "w"), "se": ("southeast", "nw"), "s" : ("south", "n"), "sw": ("southwest", "ne"), "w" : ("west", "e"), "nw": ("northwest", "se"), "u" : ("up", "d"), "d" : ("down", "u"), "i" : ("in", "o"), "o" : ("out", "i")} def func(self): "Implements the tunnel command" if not self.args or not self.lhs: string = "Usage: @tunnel[/switch] <direction> [= roomname[;alias;alias;...][:typeclass]]" self.caller.msg(string) return if self.lhs not in self.directions: string = "@tunnel can only understand the following directions: %s." % ",".join(sorted(self.directions.keys())) string += "\n(use @dig for more freedom)" self.caller.msg(string) return # retrieve all input and parse it exitshort = self.lhs exitname, backshort = self.directions[exitshort] backname = self.directions[backshort][0] roomname = "Some place" if self.rhs: roomname = self.rhs # this may include aliases; that's fine. telswitch = "" if "tel" in self.switches: telswitch = "/teleport" backstring = "" if not "oneway" in self.switches: backstring = ", %s;%s" % (backname, backshort) # build the string we will use to call @dig digstring = "@dig%s %s = %s;%s%s" % (telswitch, roomname, exitname, exitshort, backstring) self.caller.execute_cmd(digstring) class CmdLink(MuxCommand): """ @link - connect objects Usage: @link[/switches] <object> = <target> @link[/switches] <object> = @link[/switches] <object> Switch: twoway - connect two exits. For this to work, BOTH <object> and <target> must be exit objects. If <object> is an exit, set its destination to <target>. Two-way operation instead sets the destination to the *locations* of the respective given arguments. The second form (a lone =) sets the destination to None (same as the @unlink command) and the third form (without =) just shows the currently set destination. """ key = "@link" locks = "cmd:perm(link) or perm(Builders)" help_category = "Building" def func(self): "Perform the link" caller = self.caller if not self.args: caller.msg("Usage: @link[/twoway] <object> = <target>") return object_name = self.lhs # get object obj = caller.search(object_name, global_search=True) if not obj: return string = "" if self.rhs: # this means a target name was given target = caller.search(self.rhs, global_search=True) if not target: return string = "" if not obj.destination: string += "Note: %s(%s) did not have a destination set before. Make sure you linked the right thing." % (obj.name,obj.dbref) if "twoway" in self.switches: if not (target.location and obj.location): string = "To create a two-way link, %s and %s must both have a location" % (obj, target) string += " (i.e. they cannot be rooms, but should be exits)." self.caller.msg(string) return if not target.destination: string += "\nNote: %s(%s) did not have a destination set before. Make sure you linked the right thing." % (target.name, target.dbref) obj.destination = target.location target.destination = obj.location string += "\nLink created %s (in %s) <-> %s (in %s) (two-way)." % (obj.name, obj.location, target.name, target.location) else: obj.destination = target string += "\nLink created %s -> %s (one way)." % (obj.name, target) elif self.rhs == None: # this means that no = was given (otherwise rhs # would have been an empty string). So we inspect # the home/destination on object dest = obj.destination if dest: string = "%s is an exit to %s." % (obj.name, dest.name) else: string = "%s is not an exit. Its home location is %s." % obj.home else: # We gave the command @link 'obj = ' which means we want to # clear destination. if obj.destination: obj.destination = None string = "Former exit %s no longer links anywhere." % obj.name else: string = "%s had no destination to unlink." % obj.name # give feedback caller.msg(string.strip()) class CmdUnLink(CmdLink): """ @unlink - unconnect objects Usage: @unlink <Object> Unlinks an object, for example an exit, disconnecting it from whatever it was connected to. """ # this is just a child of CmdLink key = "@unlink" locks = "cmd:perm(unlink) or perm(Builders)" help_key = "Building" def func(self): """ All we need to do here is to set the right command and call func in CmdLink """ caller = self.caller if not self.args: caller.msg("Usage: @unlink <object>") return # This mimics '@link <obj> = ' which is the same as @unlink self.rhs = "" # call the @link functionality super(CmdUnLink, self).func() class CmdHome(CmdLink): """ @home - control an object's home location Usage: @home <obj> [= home_location] The "home" location is a "safety" location for objects; they will be moved there if their current location ceases to exist. All objects should always have a home location for this reason. It is also a convenient target of the "home" command. If no location is given, just view the object's home location. """ key = "@home" locks = "cmd:perm(@home) or perm(Builders)" help_category = "Building" def func(self): "implement the command" if not self.args: string = "Usage: @home <obj> [= home_location]" self.caller.msg(string) return obj = self.caller.search(self.lhs, global_search=True) if not obj: return if not self.rhs: # just view home = obj.home if not home: string = "This object has no home location set!" else: string = "%s's current home is %s(%s)." % (obj, home, home.dbref) else: # set a home location new_home = self.caller.search(self.rhs, global_search=True) if not new_home: return old_home = obj.home obj.home = new_home if old_home: string = "%s's home location was changed from %s(%s) to %s(%s)." % (obj, old_home, old_home.dbref, new_home, new_home.dbref) else: string = "%s' home location was set to %s(%s)." % (obj, new_home, new_home.dbref) self.caller.msg(string) class CmdListCmdSets(MuxCommand): """ list command sets on an object Usage: @cmdsets [obj] This displays all cmdsets assigned to a user. Defaults to yourself. """ key = "@cmdsets" aliases = "@listcmsets" locks = "cmd:perm(listcmdsets) or perm(Builders)" help_category = "Building" def func(self): "list the cmdsets" caller = self.caller if self.arglist: obj = caller.search(self.arglist[0]) if not obj: return else: obj = caller string = "%s" % obj.cmdset caller.msg(string) class CmdName(ObjManipCommand): """ cname - change the name and/or aliases of an object Usage: @name obj = name;alias1;alias2 Rename an object to something new. """ key = "@name" aliases = ["@rename"] locks = "cmd:perm(rename) or perm(Builders)" help_category = "Building" def func(self): "change the name" caller = self.caller if not self.args: string = "Usage: @name <obj> = <newname>[;alias;alias;...]" caller.msg(string) return if self.lhs_objs: objname = self.lhs_objs[0]['name'] obj = caller.search(objname) if not obj: return if self.rhs_objs: newname = self.rhs_objs[0]['name'] aliases = self.rhs_objs[0]['aliases'] else: newname = self.rhs aliases = None if not newname and not aliases: caller.msg("No names or aliases defined!") return # change the name and set aliases: if newname: obj.name = newname astring = "" if aliases: obj.aliases = aliases astring = " (%s)" % (", ".join(aliases)) caller.msg("Object's name changed to '%s'%s." % (newname, astring)) class CmdOpen(ObjManipCommand): """ @open - create new exit Usage: @open <new exit>[;alias;alias..][:typeclass] [,<return exit>[;alias;..][:typeclass]]] = <destination> Handles the creation of exits. If a destination is given, the exit will point there. The <return exit> argument sets up an exit at the destination leading back to the current room. Destination name can be given both as a #dbref and a name, if that name is globally unique. """ key = "@open" locks = "cmd:perm(open) or perm(Builders)" help_category = "Building" # a custom member method to chug out exits and do checks def create_exit(self, exit_name, location, destination, exit_aliases=None, typeclass=None): """ Helper function to avoid code duplication. At this point we know destination is a valid location """ caller = self.caller string = "" # check if this exit object already exists at the location. # we need to ignore errors (so no automatic feedback)since we # have to know the result of the search to decide what to do. exit_obj = caller.search(exit_name, location=location, ignore_errors=True) if len(exit_obj) > 1: # give error message and return caller.search(exit_name, location=location) return if exit_obj: exit_obj = exit_obj[0] if not exit_obj.destination: # we are trying to link a non-exit string = "'%s' already exists and is not an exit!\nIf you want to convert it " string += "to an exit, you must assign an object to the 'destination' property first." caller.msg(string % exit_name) return None # we are re-linking an old exit. old_destination = exit_obj.destination if old_destination: string = "Exit %s already exists." % exit_name if old_destination.id != destination.id: # reroute the old exit. exit_obj.destination = destination exit_obj.aliases = exit_aliases string += " Rerouted its old destination '%s' to '%s' and changed aliases." % \ (old_destination.name, destination.name) else: string += " It already points to the correct place." else: # exit does not exist before. Create a new one. if not typeclass: typeclass = settings.BASE_EXIT_TYPECLASS exit_obj = create.create_object(typeclass, key=exit_name, location=location, aliases=exit_aliases) if exit_obj: # storing a destination is what makes it an exit! exit_obj.destination = destination string = "Created new Exit '%s' from %s to %s (aliases: %s)." % (exit_name,location.name, destination.name, ", ".join([str(e) for e in exit_aliases])) else: string = "Error: Exit '%s' not created." % (exit_name) # emit results caller.msg(string) return exit_obj def func(self): """ This is where the processing starts. Uses the ObjManipCommand.parser() for pre-processing as well as the self.create_exit() method. """ caller = self.caller if not self.args or not self.rhs: string = "Usage: @open <new exit>[;alias...][:typeclass][,<return exit>[;alias..][:typeclass]]] " string += "= <destination>" caller.msg(string) return # We must have a location to open an exit location = caller.location if not location: caller.msg("You cannot create an exit from a None-location.") return # obtain needed info from cmdline exit_name = self.lhs_objs[0]['name'] exit_aliases = self.lhs_objs[0]['aliases'] exit_typeclass = self.lhs_objs[0]['option'] dest_name = self.rhs # first, check so the destination exists. destination = caller.search(dest_name, global_search=True) if not destination: return # Create exit ok = self.create_exit(exit_name, location, destination, exit_aliases, exit_typeclass) if not ok: # an error; the exit was not created, so we quit. return # Create back exit, if any if len(self.lhs_objs) > 1: back_exit_name = self.lhs_objs[1]['name'] back_exit_aliases = self.lhs_objs[1]['aliases'] back_exit_typeclass = self.lhs_objs[1]['option'] ok = self.create_exit(back_exit_name, destination, location, back_exit_aliases, back_exit_typeclass) class CmdSetAttribute(ObjManipCommand): """ @set - set attributes Usage: @set <obj>/<attr> = <value> @set <obj>/<attr> = @set <obj>/<attr> Sets attributes on objects. The second form clears a previously set attribute while the last form inspects the current value of the attribute (if any). You can also set lists [...] and dicts {...} on attributes with @set (but not nested combinations). Also note that such lists/dicts will always hold strings (never numbers). Use @py if you need to set arbitrary lists and dicts. """ key = "@set" locks = "cmd:perm(set) or perm(Builders)" help_category = "Building" def func(self): "Implement the set attribute - a limited form of @py." caller = self.caller if not self.args: caller.msg("Usage: @set obj/attr = value. Use empty value to clear.") return # get values prepared by the parser value = self.rhs objname = self.lhs_objattr[0]['name'] attrs = self.lhs_objattr[0]['attrs'] obj = caller.search(objname) if not obj: return string = "" if not value: if self.rhs == None: # no = means we inspect the attribute(s) if not attrs: attrs = [attr.key for attr in obj.get_all_attributes()] for attr in attrs: if obj.has_attribute(attr): string += "\nAttribute %s/%s = %s" % (obj.name, attr, obj.get_attribute(attr)) else: string += "\n%s has no attribute '%s'." % (obj.name, attr) # we view it without parsing markup. self.caller.msg(string.strip(), data={"raw":True}) return else: # deleting the attribute(s) for attr in attrs: if obj.has_attribute(attr): val = obj.get_attribute(attr) obj.del_attribute(attr) string += "\nDeleted attribute '%s' (= %s) from %s." % (attr, val, obj.name) else: string += "\n%s has no attribute '%s'." % (obj.name, attr) else: # setting attribute(s) # analyze if we are trying to set a list or a dict. if value.startswith('[') and value.endswith(']'): value = value.lstrip('[').rstrip(']').split(',') value = [utils.to_str(val) for val in value] elif value.startswith('{') and value.endswith('}') and ':' in value: dictpairs = value.lstrip('{').rstrip('}').split(',') try: value = dict([[utils.to_str(p.strip()) for p in pair.split(':')] for pair in dictpairs]) except Exception: pass for attr in attrs: obj.set_attribute(attr, value) string += "\nCreated attribute %s/%s = %s" % (obj.name, attr, value) # send feedback caller.msg(string.strip('\n')) class CmdTypeclass(MuxCommand): """ @typeclass - set object typeclass Usage: @typclass[/switch] <object> [= <typeclass path>] @type '' @parent '' Switch: reset - clean out *all* the attributes on the object - basically making this a new clean object. force - change to the typeclass also if the object already has a typeclass of the same name. Example: @type button = examples.red_button.RedButton Sets an object's typeclass. The typeclass must be identified by its location using python dot-notation pointing to the correct module and class. If no typeclass is given (or a wrong typeclass is given), the object will be set to the default typeclass. The location of the typeclass module is searched from the default typeclass directory, as defined in the server settings. """ key = "@typeclass" aliases = "@type, @parent" locks = "cmd:perm(typeclass) or perm(Builders)" help_category = "Building" def func(self): "Implements command" caller = self.caller if not self.args: caller.msg("Usage: @type <object> [=<typeclass]") return # get object to swap on obj = caller.search(self.lhs) if not obj: return if not self.rhs: # we did not supply a new typeclass, view the # current one instead. if hasattr(obj, "typeclass"): string = "%s's current typeclass is '%s'." % (obj.name, obj.typeclass.typename) else: string = "%s is not a typed object." % obj.name caller.msg(string) return # we have an =, a typeclass was supplied. typeclass = self.rhs if not obj.access(caller, 'edit'): caller.msg("You are not allowed to do that.") return if not hasattr(obj, 'swap_typeclass') or not hasattr(obj, 'typeclass'): caller.msg("This object cannot have a type at all!") return old_path = obj.typeclass_path if obj.is_typeclass(typeclass) and not 'force' in self.switches: string = "%s already has the typeclass '%s'." % (obj.name, typeclass) else: reset = "reset" in self.switches old_typeclass_name = obj.typeclass.typename ok = obj.swap_typeclass(typeclass, clean_attributes=reset) if ok: string = "%s's type is now %s (instead of %s).\n" % (obj.name, obj.typeclass.typename, old_typeclass_name) if reset: string += "All attributes where reset." else: string += "Note that the new class type could have overwritten " string += "same-named attributes on the existing object." else: string = "Could not swap '%s' (%s) to typeclass '%s'." % (obj.name, old_typeclass_name, typeclass) caller.msg(string) class CmdWipe(ObjManipCommand): """ @wipe - clears attributes Usage: @wipe <object>[/attribute[/attribute...]] Example: @wipe box @wipe box/colour Wipes all of an object's attributes, or optionally only those matching the given attribute-wildcard search string. """ key = "@wipe" locks = "cmd:perm(wipe) or perm(Builders)" help_category = "Building" def func(self): """ inp is the dict produced in ObjManipCommand.parse() """ caller = self.caller if not self.args: caller.msg("Usage: @wipe <object>[/attribute/attribute...]") return # get the attributes set by our custom parser objname = self.lhs_objattr[0]['name'] attrs = self.lhs_objattr[0]['attrs'] obj = caller.search(objname) if not obj: return if not obj.access(caller, 'edit'): caller.msg("You are not allowed to do that.") return if not attrs: # wipe everything for attr in obj.get_all_attributes(): attr.delete() string = "Wiped all attributes on %s." % obj.name else: for attrname in attrs: obj.attr(attrname, delete=True ) string = "Wiped attributes %s on %s." string = string % (",".join(attrs), obj.name) caller.msg(string) class CmdLock(ObjManipCommand): """ lock - assign a lock definition to an object Usage: @lock <object>[ = <lockstring>] or @lock[/switch] object/<access_type> Switch: del - delete given access type view - view lock associated with given access type (default) If no lockstring is given, shows all locks on object. Lockstring is on the form 'access_type:[NOT] func1(args)[ AND|OR][ NOT] func2(args) ...] Where func1, func2 ... valid lockfuncs with or without arguments. Separator expressions need not be capitalized. For example: 'get: id(25) or perm(Wizards)' The 'get' access_type is checked by the get command and will an object locked with this string will only be possible to pick up by Wizards or by object with id 25. You can add several access_types after oneanother by separating them by ';', i.e: 'get:id(25);delete:perm(Builders)' """ key = "@lock" aliases = ["@locks", "lock", "locks"] locks = "cmd: perm(@locks) or perm(Builders)" help_category = "Building" def func(self): "Sets up the command" caller = self.caller if not self.args: string = "@lock <object>[ = <lockstring>] or @lock[/switch] object/<access_type>" caller.msg(string) return if '/' in self.lhs: # call on the form @lock obj/access_type objname, access_type = [p.strip() for p in self.lhs.split('/', 1)] obj = caller.search(objname) if not obj: return lockdef = obj.locks.get(access_type) if lockdef: string = lockdef[2] if 'del' in self.switches: if not obj.access(caller, 'control'): caller.msg("You are not allowed to do that.") return obj.locks.delete(access_type) string = "deleted lock %s" % string else: string = "%s has no lock of access type '%s'." % (obj, access_type) caller.msg(string) return if self.rhs: # we have a = separator, so we are assigning a new lock objname, lockdef = self.lhs, self.rhs obj = caller.search(objname) if not obj: return if not obj.access(caller, 'control'): caller.msg("You are not allowed to do that.") return ok = obj.locks.add(lockdef, caller) if ok: caller.msg("Added lock '%s' to %s." % (lockdef, obj)) return # if we get here, we are just viewing all locks obj = caller.search(self.lhs) if not obj: return caller.msg(obj.locks) class CmdExamine(ObjManipCommand): """ examine - detailed info on objects Usage: examine [<object>[/attrname]] examine [*<player>[/attrname]] Switch: player - examine a Player (same as adding *) raw - don't parse escape codes for data. The examine command shows detailed game info about an object and optionally a specific attribute on it. If object is not specified, the current location is examined. Append a * before the search string to examine a player. """ key = "@examine" aliases = ["@ex","ex", "exam", "examine"] locks = "cmd:perm(examine) or perm(Builders)" help_category = "Building" player_mode = False def format_attributes(self, obj, attrname=None, crop=True, raw=False): """ Helper function that returns info about attributes and/or non-persistent data stored on object """ headers = {"persistent":"\n{wPersistent attributes{n:", "nonpersistent":"\n{wNon-persistent attributes{n:"} headers_noansi = {"persistent":"\nPersistent attributes:", "nonpersistent":"\nNon-persistent attributes:"} if raw: headers = headers_noansi if attrname: db_attr = [(attrname, obj.attr(attrname))] try: ndb_attr = [(attrname, object.__getattribute__(obj.ndb, attrname))] except Exception: ndb_attr = None else: if self.player_mode: db_attr = [(attr.key, attr.value) for attr in PlayerAttribute.objects.filter(db_obj=obj)] else: db_attr = [(attr.key, attr.value) for attr in ObjAttribute.objects.filter(db_obj=obj)] try: ndb_attr = [(aname, avalue) for aname, avalue in obj.ndb.__dict__.items()] except Exception: ndb_attr = None string = "" if db_attr and db_attr[0]: #self.caller.msg(db_attr) string += headers["persistent"] for attr, value in db_attr: if crop and isinstance(value, basestring): value = utils.crop(value) string += "\n %s = %s" % (attr, value) if ndb_attr and ndb_attr[0]: string += headers["nonpersistent"] for attr, value in ndb_attr: if crop and isinstance(value, basestring): value = utils.crop(value) string += "\n %s = %s" % (attr, value) return string def format_output(self, obj, raw=False): """ Helper function that creates a nice report about an object. returns a string. """ headers = {"name":"\n{wName/key{n: {c%s{n (%s)", "aliases":"\n{wAliases{n: %s", "player":"\n{wPlayer{n: {c%s{n", "playerperms":"\n{wPlayer Perms{n: %s", "typeclass":"\n{wTypeclass{n: %s (%s)", "location":"\n{wLocation{n: %s", "destination":"\n{wDestination{n: %s", "perms":"\n{wPermissions{n: %s", "locks":"\n{wLocks{n:", "cmdset":"\n{wCurrent Cmdset(s){n:\n %s", "cmdset_avail":"\n{wActual commands available to %s (incl. lock-checks, external cmds etc){n:\n %s", "scripts":"\n{wScripts{n:\n %s", "exits":"\n{wExits{n: ", "characters":"\n{wCharacters{n: ", "contents":"\n{wContents{n: "} headers_noansi = {"name":"\nName/key: %s (%s)", "aliases":"\nAliases: %s", "player":"\nPlayer: %s", "playerperms":"\nPlayer Perms: %s", "typeclass":"\nTypeclass: %s (%s)", "location":"\nLocation: %s", "destination":"\nDestination: %s", "perms":"\nPermissions: %s", "locks":"\nLocks:", "cmdset":"\nCurrent Cmdset(s):\n %s", "cmdset_avail":"\nActual commands available to %s (incl. lock-checks, external cmds, etc):\n %s", "scripts":"\nScripts:\n %s", "exits":"\nExits: ", "characters":"\nCharacters: ", "contents":"\nContents: "} if raw: headers = headers_noansi if hasattr(obj, "has_player") and obj.has_player: string = headers["name"] % (obj.name, obj.dbref) else: string = headers["name"] % (obj.name, obj.dbref) if hasattr(obj, "aliases") and obj.aliases: string += headers["aliases"] % (", ".join(obj.aliases)) if hasattr(obj, "has_player") and obj.has_player: string += headers["player"] % obj.player.name perms = obj.player.permissions if obj.player.is_superuser: perms = ["<Superuser>"] elif not perms: perms = ["<None>"] string += headers["playerperms"] % (", ".join(perms)) string += headers["typeclass"] % (obj.typeclass.typename, obj.typeclass_path) if hasattr(obj, "location"): string += headers["location"] % obj.location if hasattr(obj, "destination") and obj.destination: string += headers["destination"] % obj.destination perms = obj.permissions if perms: string += headers["perms"] % (", ".join(perms)) locks = str(obj.locks) if locks: string += headers["locks"] + utils.fill("; ".join([lock for lock in locks.split(';')]), indent=6) if not (len(obj.cmdset.all()) == 1 and obj.cmdset.current.key == "Empty"): # list the current cmdsets cmdsetstr = "\n".join([utils.fill(cmdset, indent=2) for cmdset in str(obj.cmdset).split("\n")]) string += headers["cmdset"] % cmdsetstr # list the actually available commands from src.commands.cmdhandler import get_and_merge_cmdsets avail_cmdset = get_and_merge_cmdsets(obj) avail_cmdset = sorted([cmd.key for cmd in avail_cmdset if cmd.access(obj, "cmd")]) cmdsetstr = utils.fill(", ".join(avail_cmdset), indent=2) string += headers["cmdset_avail"] % (obj.key, cmdsetstr) if hasattr(obj, "scripts") and hasattr(obj.scripts, "all") and obj.scripts.all(): string += headers["scripts"] % obj.scripts # add the attributes string += self.format_attributes(obj, raw=raw) # add the contents exits = [] pobjs = [] things = [] if hasattr(obj, "contents"): for content in obj.contents: if content.destination: exits.append(content) elif content.player: pobjs.append(content) else: things.append(content) if exits: string += headers["exits"] + ", ".join([exit.name for exit in exits]) if pobjs: string += headers["characters"] + ", ".join(["{c%s{n" % pobj.name for pobj in pobjs]) if things: string += headers["contents"] + ", ".join([cont.name for cont in obj.contents if cont not in exits and cont not in pobjs]) #output info return "-"*78 + '\n' + string.strip() + "\n" + '-'*78 def func(self): "Process command" caller = self.caller msgdata = None if "raw" in self.switches: msgdata = {"raw":True} if not self.args: # If no arguments are provided, examine the invoker's location. obj = caller.location if not obj.access(caller, 'examine'): #If we don't have special info access, just look at the object instead. caller.execute_cmd('look %s' % obj.name) return string = self.format_output(obj, raw=msgdata) caller.msg(string.strip(), data=msgdata) return # we have given a specific target object string = "" for objdef in self.lhs_objattr: obj_name = objdef['name'] obj_attrs = objdef['attrs'] self.player_mode = "player" in self.switches or obj_name.startswith('*') obj = caller.search(obj_name, player=self.player_mode) if not obj: continue if not obj.access(caller, 'examine'): #If we don't have special info access, just look at the object instead. caller.execute_cmd('look %s' % obj_name) continue if obj_attrs: for attrname in obj_attrs: # we are only interested in specific attributes string += self.format_attributes(obj, attrname, crop=False, raw=msgdata) else: string += self.format_output(obj, raw=msgdata) caller.msg(string.strip(), data=msgdata) class CmdFind(MuxCommand): """ find objects Usage: @find[/switches] <name or dbref or *player> [= dbrefmin[-dbrefmax]] Switches: room - only look for rooms (location=None) exit - only look for exits (destination!=None) char - only look for characters (BASE_CHARACTER_TYPECLASS) Searches the database for an object of a particular name or dbref. Use *playername to search for a player. The switches allows for limiting object matches to certain game entities. Dbrefmin and dbrefmax limits matches to within the given dbrefs, or above/below if only one is given. """ key = "@find" aliases = "find, @search, search, @locate, locate" locks = "cmd:perm(find) or perm(Builders)" help_category = "Building" def func(self): "Search functionality" caller = self.caller switches = self.switches if not self.args: caller.msg("Usage: @find <string> [= low [-high]]") return searchstring = self.lhs low, high = 1, ObjectDB.objects.all().order_by("-id")[0].id if self.rhs: if "-" in self.rhs: # also support low-high syntax limlist = [part.strip() for part in self.rhs.split("-", 1)] else: # otherwise split by space limlist = self.rhs.split(None, 1) if limlist and limlist[0].isdigit(): low = max(low, int(limlist[0])) if len(limlist) > 1 and limlist[1].isdigit(): high = min(high, int(limlist[1])) low = min(low, high) high = max(low, high) if searchstring.startswith("*") or utils.dbref(searchstring): # A player/dbref search. # run a normal player- or dbref search. This should be unique. string = "{wMatch{n(#%i-#%i):" % (low, high) result = caller.search(searchstring, global_search=True) if not result: return if not low <= int(result.id) <= high: string += "\n {RNo match found for '%s' within the given dbref limits.{n" % searchstring else: string += "\n{g %s(%s) - %s{n" % (result.key, result.dbref, result.typeclass.path) else: # Not a player/dbref search but a wider search; build a queryset. results = ObjectDB.objects.filter(db_key__istartswith=searchstring, id__gte=low, id__lte=high) if "room" in switches: results = results.filter(db_location__isnull=True) if "exit" in switches: results = results.filter(db_destination__isnull=False) if "char" in switches: results = results.filter(db_typeclass_path=CHAR_TYPECLASS) nresults = results.count() if not nresults: # no matches on the keys. Try aliases instead. results = results = ObjectDB.alias_set.related.model.objects.filter(db_key=searchstring) if "room" in switches: results = results.filter(db_obj__db_location__isnull=True) if "exit" in switches: results = results.filter(db_obj__db_destination__isnull=False) if "char" in switches: results = results.filter(db_obj__db_typeclass_path=CHAR_TYPECLASS) # we have to parse alias -> real object here results = [result.db_obj for result in results] nresults = len(results) restrictions = "" if self.switches: restrictions = ", %s" % (",".join(self.switches)) if nresults: # convert result to typeclasses. results = [result.typeclass for result in results] if nresults > 1: string = "{w%i Matches{n(#%i-#%i%s):" % (nresults, low, high, restrictions) for res in results: string += "\n {g%s(%s) - %s{n" % (res.key, res.dbref, res.path) else: string = "{wOne Match{n(#%i-#%i%s):" % (low, high, restrictions) string += "\n {g%s(%s) - %s{n" % (results[0].key, results[0].dbref, results[0].path) else: string = "{wMatch{n(#%i-#%i%s):" % (low, high, restrictions) string += "\n {RNo matches found for '%s'{n" % searchstring # send result caller.msg(string.strip()) class CmdTeleport(MuxCommand): """ teleport Usage: @tel/switch [<object> =] <location> Switches: quiet - don't inform the source and target locations about the move. Teleports an object somewhere. If no object is given we are teleporting ourselves. """ key = "@tel" aliases = "@teleport" locks = "cmd:perm(teleport) or perm(Builders)" help_category = "Building" def func(self): "Performs the teleport" caller = self.caller args = self.args lhs, rhs = self.lhs, self.rhs switches = self.switches if not args: caller.msg("Usage: teleport[/switches] [<obj> =] <target_loc>|home") return # The quiet switch suppresses leaving and arrival messages. if "quiet" in switches: tel_quietly = True else: tel_quietly = False if rhs: obj_to_teleport = caller.search(lhs, global_search=True) destination = caller.search(rhs, global_search=True) else: obj_to_teleport = caller destination = caller.search(args, global_search=True) if not obj_to_teleport: caller.msg("Did not find object to teleport.") return if not destination: caller.msg("Destination not found.") return if obj_to_teleport == destination: caller.msg("You can't teleport an object inside of itself!") return # try the teleport if obj_to_teleport.move_to(destination, quiet=tel_quietly, emit_to_obj=caller): if obj_to_teleport == caller: caller.msg("Teleported to %s." % destination.key) else: caller.msg("Teleported %s -> %s." % (obj_to_teleport, destination.key)) class CmdScript(MuxCommand): """ attach scripts Usage: @script[/switch] <obj> [= <script.path or scriptkey>] Switches: start - start all non-running scripts on object, or a given script only stop - stop all scripts on objects, or a given script only If no script path/key is given, lists all scripts active on the given object. Script path can be given from the base location for scripts as given in settings. If adding a new script, it will be started automatically (no /start switch is needed). Using the /start or /stop switches on an object without specifying a script key/path will start/stop ALL scripts on the object. """ key = "@script" aliases = "@addscript" locks = "cmd:perm(script) or perm(Wizards)" help_category = "Building" def func(self): "Do stuff" caller = self.caller if not self.args: string = "Usage: @script[/switch] <obj> [= <script.path or script key>]" caller.msg(string) return obj = caller.search(self.lhs) if not obj: return string = "" if not self.rhs: # no rhs means we want to operate on all scripts scripts = obj.scripts.all() if not scripts: string += "No scripts defined on %s." % obj.key elif not self.switches: # view all scripts from src.commands.default.system import format_script_list string += format_script_list(scripts) elif "start" in self.switches: num = sum([obj.scripts.start(script.key) for script in scripts]) string += "%s scripts started on %s." % (num, obj.key) elif "stop" in self.switches: for script in scripts: string += "Stopping script %s on %s." % (script.key, obj.key) script.stop() string = string.strip() obj.scripts.validate() else: # rhs exists if not self.switches: # adding a new script, and starting it ok = obj.scripts.add(self.rhs, autostart=True) if not ok: string += "\nScript %s could not be added and/or started on %s." % (self.rhs, obj.key) else: string = "Script {w%s{n successfully added and started on %s." % (self.rhs, obj.key) else: paths = [self.rhs] + ["%s.%s" % (prefix, self.rhs) for prefix in settings.SCRIPT_TYPECLASS_PATHS] if "stop" in self.switches: # we are stopping an already existing script for path in paths: ok = obj.scripts.stop(path) if not ok: string += "\nScript %s could not be stopped. Does it exist?" % path else: string = "Script stopped and removed from object." break if "start" in self.switches: # we are starting an already existing script for path in paths: ok = obj.scripts.start(path) if not ok: string += "\nScript %s could not be (re)started." % path else: string = "Script started successfully." break caller.msg(string.strip())
Python
""" The command template for the default MUX-style command set """ from src.utils import utils from src.commands.command import Command class MuxCommand(Command): """ This sets up the basis for a MUX command. The idea is that most other Mux-related commands should just inherit from this and don't have to implement much parsing of their own unless they do something particularly advanced. Note that the class's __doc__ string (this text) is used by Evennia to create the automatic help entry for the command, so make sure to document consistently here. """ def has_perm(self, srcobj): """ This is called by the cmdhandler to determine if srcobj is allowed to execute this command. We just show it here for completeness - we are satisfied using the default check in Command. """ return super(MuxCommand, self).has_perm(srcobj) def at_pre_cmd(self): """ This hook is called before self.parse() on all commands """ pass def at_post_cmd(self): """ This hook is called after the command has finished executing (after self.func()). """ pass def parse(self): """ This method is called by the cmdhandler once the command name has been identified. It creates a new set of member variables that can be later accessed from self.func() (see below) The following variables are available for our use when entering this method (from the command definition, and assigned on the fly by the cmdhandler): self.key - the name of this command ('look') self.aliases - the aliases of this cmd ('l') self.permissions - permission string for this command self.help_category - overall category of command self.caller - the object calling this command self.cmdstring - the actual command name used to call this (this allows you to know which alias was used, for example) self.args - the raw input; everything following self.cmdstring. self.cmdset - the cmdset from which this command was picked. Not often used (useful for commands like 'help' or to list all available commands etc) self.obj - the object on which this command was defined. It is often the same as self.caller. A MUX command has the following possible syntax: name[ with several words][/switch[/switch..]] arg1[,arg2,...] [[=|,] arg[,..]] The 'name[ with several words]' part is already dealt with by the cmdhandler at this point, and stored in self.cmdname (we don't use it here). The rest of the command is stored in self.args, which can start with the switch indicator /. This parser breaks self.args into its constituents and stores them in the following variables: self.switches = [list of /switches (without the /)] self.raw = This is the raw argument input, including switches self.args = This is re-defined to be everything *except* the switches self.lhs = Everything to the left of = (lhs:'left-hand side'). If no = is found, this is identical to self.args. self.rhs: Everything to the right of = (rhs:'right-hand side'). If no '=' is found, this is None. self.lhslist - [self.lhs split into a list by comma] self.rhslist - [list of self.rhs split into a list by comma] self.arglist = [list of space-separated args (stripped, including '=' if it exists)] All args and list members are stripped of excess whitespace around the strings, but case is preserved. """ raw = self.args args = raw.strip() # split out switches switches = [] if args and len(args) > 1 and args[0] == "/": # we have a switch, or a set of switches. These end with a space. #print "'%s'" % args switches = args[1:].split(None, 1) if len(switches) > 1: switches, args = switches switches = switches.split('/') else: args = "" switches = switches[0].split('/') arglist = [arg.strip() for arg in args.split()] # check for arg1, arg2, ... = argA, argB, ... constructs lhs, rhs = args, None lhslist, rhslist = [arg.strip() for arg in args.split(',')], [] if args and '=' in args: lhs, rhs = [arg.strip() for arg in args.split('=', 1)] lhslist = [arg.strip() for arg in lhs.split(',')] rhslist = [arg.strip() for arg in rhs.split(',')] # save to object properties: self.raw = raw self.switches = switches self.args = args.strip() self.arglist = arglist self.lhs = lhs self.lhslist = lhslist self.rhs = rhs self.rhslist = rhslist def func(self): """ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein. """ # a simple test command to show the available properties string = "-" * 50 string += "\n{w%s{n - Command variables from evennia:\n" % self.key string += "-" * 50 string += "\nname of cmd (self.key): {w%s{n\n" % self.key string += "cmd aliases (self.aliases): {w%s{n\n" % self.aliases string += "cmd locks (self.locks): {w%s{n\n" % self.locks string += "help category (self.help_category): {w%s{n\n" % self.help_category string += "object calling (self.caller): {w%s{n\n" % self.caller string += "object storing cmdset (self.obj): {w%s{n\n" % self.obj string += "command string given (self.cmdstring): {w%s{n\n" % self.cmdstring # show cmdset.key instead of cmdset to shorten output string += utils.fill("current cmdset (self.cmdset): {w%s{n\n" % self.cmdset) string += "\n" + "-" * 50 string += "\nVariables from MuxCommand baseclass\n" string += "-" * 50 string += "\nraw argument (self.raw): {w%s{n \n" % self.raw string += "cmd args (self.args): {w%s{n\n" % self.args string += "cmd switches (self.switches): {w%s{n\n" % self.switches string += "space-separated arg list (self.arglist): {w%s{n\n" % self.arglist string += "lhs, left-hand side of '=' (self.lhs): {w%s{n\n" % self.lhs string += "lhs, comma separated (self.lhslist): {w%s{n\n" % self.lhslist string += "rhs, right-hand side of '=' (self.rhs): {w%s{n\n" % self.rhs string += "rhs, comma separated (self.rhslist): {w%s{n\n" % self.rhslist string += "-" * 50 self.caller.msg(string)
Python
""" Comsystem command module. Comm commands are OOC commands and intended to be made available to the Player at all times (they go into the PlayerCmdSet). So we make sure to homogenize self.caller to always be the player object for easy handling. """ from django.conf import settings from src.comms.models import Channel, Msg, PlayerChannelConnection, ExternalChannelConnection from src.comms import irc, imc2, rss from src.comms.channelhandler import CHANNELHANDLER from src.utils import create, utils from src.commands.default.muxcommand import MuxCommand def find_channel(caller, channelname, silent=False, noaliases=False): """ Helper function for searching for a single channel with some error handling. """ channels = Channel.objects.channel_search(channelname) if not channels: if not noaliases: channels = [chan for chan in Channel.objects.all() if channelname in chan.aliases] if channels: return channels[0] if not silent: caller.msg("Channel '%s' not found." % channelname) return None elif len(channels) > 1: matches = ", ".join(["%s(%s)" % (chan.key, chan.id) for chan in channels]) if not silent: caller.msg("Multiple channels match (be more specific): \n%s" % matches) return None return channels[0] class CommCommand(MuxCommand): """ This is a parent for comm-commands. Since These commands are to be available to the Player, we make sure to homogenize the caller here, so it's always seen as a player to the command body. """ def parse(self): "overload parts of parse" # run parent super(CommCommand, self).parse() # fix obj->player if utils.inherits_from(self.caller, "src.objects.objects.Object"): # an object. Convert it to its player. self.caller = self.caller.player class CmdAddCom(MuxCommand): """ addcom - subscribe to a channel with optional alias Usage: addcom [alias=] <channel> Joins a given channel. If alias is given, this will allow you to refer to the channel by this alias rather than the full channel name. Subsequent calls of this command can be used to add multiple aliases to an already joined channel. """ key = "addcom" aliases = ["aliaschan","chanalias"] help_category = "Comms" locks = "cmd:not pperm(channel_banned)" def func(self): "Implement the command" caller = self.caller args = self.args player = caller if not args: caller.msg("Usage: addcom [alias =] channelname.") return if self.rhs: # rhs holds the channelname channelname = self.rhs alias = self.lhs else: channelname = self.args alias = None channel = find_channel(caller, channelname) if not channel: # we use the custom search method to handle errors. return # check permissions if not channel.access(player, 'listen'): caller.msg("%s: You are not allowed to listen to this channel." % channel.key) return string = "" if not channel.has_connection(player): # we want to connect as well. if not channel.connect_to(player): # if this would have returned True, the player is connected caller.msg("%s: You are not allowed to join this channel." % channel.key) return else: string += "You now listen to the channel %s. " % channel.key else: string += "You are already connected to channel %s." % channel.key if alias: # create a nick and add it to the caller. caller.nicks.add(alias, channel.key, nick_type="channel") string += " You can now refer to the channel %s with the alias '%s'." caller.msg(string % (channel.key, alias)) else: string += " No alias added." caller.msg(string) class CmdDelCom(MuxCommand): """ delcom - unsubscribe from channel or remove channel alias Usage: delcom <alias or channel> If the full channel name is given, unsubscribe from the channel. If an alias is given, remove the alias but don't unsubscribe. """ key = "delcom" aliases = ["delaliaschan, delchanalias"] help_category = "Comms" locks = "cmd:not perm(channel_banned)" def func(self): "Implementing the command. " caller = self.caller player = caller if not self.args: caller.msg("Usage: delcom <alias or channel>") return ostring = self.args.lower() channel = find_channel(caller, ostring, silent=True, noaliases=True) if channel: # we have given a channel name - unsubscribe if not channel.has_connection(player): caller.msg("You are not listening to that channel.") return chkey = channel.key.lower() # find all nicks linked to this channel and delete them for nick in [nick for nick in caller.nicks.get(nick_type="channel") if nick.db_real.lower() == chkey]: nick.delete() channel.disconnect_from(player) caller.msg("You stop listening to channel '%s'. Eventual aliases were removed." % channel.key) return else: # we are removing a channel nick channame = caller.nicks.get(ostring, nick_type="channel") channel = find_channel(caller, channame, silent=True) if not channel: caller.msg("No channel with alias '%s' was found." % ostring) else: if caller.nicks.has(ostring, nick_type="channel"): caller.nicks.delete(ostring, nick_type="channel") caller.msg("Your alias '%s' for channel %s was cleared." % (ostring, channel.key)) else: caller.msg("You had no such alias defined for this channel.") class CmdAllCom(MuxCommand): """ allcom - operate on all channels Usage: allcom [on | off | who | destroy] Allows the user to universally turn off or on all channels they are on, as well as perform a 'who' for all channels they are on. Destroy deletes all channels that you control. Without argument, works like comlist. """ key = "allcom" locks = "cmd: not pperm(channel_banned)" help_category = "Comms" def func(self): "Runs the function" caller = self.caller args = self.args if not args: caller.execute_cmd("@channels") caller.msg("(Usage: allcom on | off | who | destroy)") return if args == "on": # get names of all channels available to listen to and activate them all channels = [chan for chan in Channel.objects.get_all_channels() if chan.access(caller, 'listen')] for channel in channels: caller.execute_cmd("addcom %s" % channel.key) elif args == "off": #get names all subscribed channels and disconnect from them all channels = [conn.channel for conn in PlayerChannelConnection.objects.get_all_player_connections(caller)] for channel in channels: caller.execute_cmd("delcom %s" % channel.key) elif args == "destroy": # destroy all channels you control channels = [chan for chan in Channel.objects.get_all_channels() if chan.access(caller, 'control')] for channel in channels: caller.execute_cmd("@cdestroy %s" % channel.key) elif args == "who": # run a who, listing the subscribers on visible channels. string = "\n{CChannel subscriptions{n" channels = [chan for chan in Channel.objects.get_all_channels() if chan.access(caller, 'listen')] if not channels: string += "No channels." for channel in channels: string += "\n{w%s:{n\n" % channel.key conns = PlayerChannelConnection.objects.get_all_connections(channel) if conns: string += " " + ", ".join([conn.player.key for conn in conns]) else: string += " <None>" caller.msg(string.strip()) else: # wrong input caller.msg("Usage: allcom on | off | who | clear") class CmdChannels(MuxCommand): """ @clist Usage: @channels @clist comlist Lists all channels available to you, wether you listen to them or not. Use 'comlist" to only view your current channel subscriptions. """ key = "@channels" aliases = ["@clist", "channels", "comlist", "chanlist", "channellist", "all channels"] help_category = "Comms" locks = "cmd: not pperm(channel_banned)" def func(self): "Implement function" caller = self.caller # all channels we have available to listen to channels = [chan for chan in Channel.objects.get_all_channels() if chan.access(caller, 'listen')] if not channels: caller.msg("No channels available.") return # all channel we are already subscribed to subs = [conn.channel for conn in PlayerChannelConnection.objects.get_all_player_connections(caller)] if self.cmdstring != "comlist": string = "\nChannels available:" cols = [[" "], ["Channel"], ["Aliases"], ["Perms"], ["Description"]] for chan in channels: if chan in subs: cols[0].append(">") else: cols[0].append(" ") cols[1].append(chan.key) cols[2].append(",".join(chan.aliases)) cols[3].append(str(chan.locks)) cols[4].append(chan.desc) # put into table for ir, row in enumerate(utils.format_table(cols)): if ir == 0: string += "\n{w" + "".join(row) + "{n" else: string += "\n" + "".join(row) self.caller.msg(string) string = "\nChannel subscriptions:" if not subs: string += "(None)" else: nicks = [nick for nick in caller.nicks.get(nick_type="channel")] cols = [[" "], ["Channel"], ["Aliases"], ["Description"]] for chan in subs: cols[0].append(" ") cols[1].append(chan.key) cols[2].append(",".join([nick.db_nick for nick in nicks if nick.db_real.lower() == chan.key.lower()] + chan.aliases)) cols[3].append(chan.desc) # put into table for ir, row in enumerate(utils.format_table(cols)): if ir == 0: string += "\n{w" + "".join(row) + "{n" else: string += "\n" + "".join(row) caller.msg(string) class CmdCdestroy(MuxCommand): """ @cdestroy Usage: @cdestroy <channel> Destroys a channel that you control. """ key = "@cdestroy" help_category = "Comms" locks = "cmd: not pperm(channel_banned)" def func(self): "Destroy objects cleanly." caller = self.caller if not self.args: caller.msg("Usage: @cdestroy <channelname>") return channel = find_channel(caller, self.args) if not channel: caller.msg("Could not find channel %s." % self.args) return if not channel.access(caller, 'control'): caller.msg("You are not allowed to do that.") return message = "%s is being destroyed. Make sure to change your aliases." % channel msgobj = create.create_message(caller, message, channel) channel.msg(msgobj) channel.delete() CHANNELHANDLER.update() caller.msg("%s was destroyed." % channel) class CmdCBoot(MuxCommand): """ @cboot Usage: @cboot[/quiet] <channel> = <player> [:reason] Switches: quiet - don't notify the channel Kicks a player or object from a channel you control. """ key = "@cboot" locks = "cmd: not pperm(channel_banned)" help_category = "Comms" def func(self): "implement the function" if not self.args or not self.rhs: string = "Usage: @cboot[/quiet] <channel> = <player> [:reason]" self.caller.msg(string) return channel = find_channel(self.caller, self.lhs) if not channel: return reason = "" if ":" in self.rhs: playername, reason = self.rhs.rsplit(":", 1) searchstring = playername.lstrip('*') else: searchstring = self.rhs.lstrip('*') player = self.caller.search(searchstring, player=True) if not player: return if reason: reason = " (reason: %s)" % reason if not channel.access(self.caller, "control"): string = "You don't control this channel." self.caller.msg(string) return if not PlayerChannelConnection.objects.has_connection(player, channel): string = "Player %s is not connected to channel %s." % (player.key, channel.key) self.caller.msg(string) return if not "quiet" in self.switches: string = "%s boots %s from channel.%s" % (self.caller, player.key, reason) channel.msg(string) # find all player's nicks linked to this channel and delete them for nick in [nick for nick in player.character.nicks.get(nick_type="channel") if nick.db_real.lower() == channel.key]: nick.delete() # disconnect player channel.disconnect_from(player) class CmdCemit(MuxCommand): """ @cemit - send a message to channel Usage: @cemit[/switches] <channel> = <message> Switches: noheader - don't show the [channel] header before the message sendername - attach the sender's name before the message quiet - don't echo the message back to sender Allows the user to broadcast a message over a channel as long as they control it. It does not show the user's name unless they provide the /sendername switch. """ key = "@cemit" aliases = ["@cmsg"] locks = "cmd: not pperm(channel_banned)" help_category = "Comms" def func(self): "Implement function" if not self.args or not self.rhs: string = "Usage: @cemit[/switches] <channel> = <message>" self.caller.msg(string) return channel = find_channel(self.caller, self.lhs) if not channel: return if not channel.access(self.caller, "control"): string = "You don't control this channel." self.caller.msg(string) return message = self.rhs if "sendername" in self.switches: message = "%s: %s" % (self.caller.key, message) if not "noheader" in self.switches: message = "[%s] %s" % (channel.key, message) channel.msg(message) if not "quiet" in self.switches: string = "Sent to channel %s: %s" % (channel.key, message) self.caller.msg(string) class CmdCWho(MuxCommand): """ @cwho Usage: @cwho <channel> List who is connected to a given channel you have access to. """ key = "@cwho" locks = "cmd: not pperm(channel_banned)" help_category = "Comms" def func(self): "implement function" if not self.args: string = "Usage: @cwho <channel>" self.caller.msg(string) return channel = find_channel(self.caller, self.lhs) if not channel: return if not channel.access(self.caller, "listen"): string = "You can't access this channel." self.caller.msg(string) string = "\n{CChannel subscriptions{n" string += "\n{w%s:{n\n" % channel.key conns = PlayerChannelConnection.objects.get_all_connections(channel) if conns: string += " " + ", ".join([conn.player.key for conn in conns]) else: string += " <None>" self.caller.msg(string.strip()) class CmdChannelCreate(MuxCommand): """ @ccreate channelcreate Usage: @ccreate <new channel>[;alias;alias...] = description Creates a new channel owned by you. """ key = "@ccreate" aliases = "channelcreate" locks = "cmd:not pperm(channel_banned)" help_category = "Comms" def func(self): "Implement the command" caller = self.caller if not self.args: caller.msg("Usage @ccreate <channelname>[;alias;alias..] = description") return description = "" if self.rhs: description = self.rhs lhs = self.lhs channame = lhs aliases = None if ';' in lhs: channame, aliases = [part.strip().lower() for part in lhs.split(';', 1) if part.strip()] aliases = [alias.strip().lower() for alias in aliases.split(';') if alias.strip()] channel = Channel.objects.channel_search(channame) if channel: caller.msg("A channel with that name already exists.") return # Create and set the channel up lockstring = "send:all();listen:all();control:id(%s)" % caller.id new_chan = create.create_channel(channame, aliases, description, locks=lockstring) new_chan.connect_to(caller) caller.msg("Created channel %s and connected to it." % new_chan.key) class CmdCset(MuxCommand): """ @cset - changes channel access restrictions Usage: @cset <channel> [= <lockstring>] Changes the lock access restrictions of a channel. If no lockstring was given, view the current lock definitions. """ key = "@cset" locks = "cmd:not pperm(channel_banned)" aliases = ["@cclock"] help_category = "Comms" def func(self): "run the function" if not self.args: string = "Usage: @cset channel [= lockstring]" self.caller.msg(string) return channel = find_channel(self.caller, self.lhs) if not channel: return if not self.rhs: # no =, so just view the current locks string = "Current locks on %s:" % channel.key string = "%s\n %s" % (string, channel.locks) self.caller.msg(string) return # we want to add/change a lock. if not channel.access(self.caller, "control"): string = "You don't control this channel." self.caller.msg(string) return # Try to add the lock channel.locks.add(self.rhs) string = "Lock(s) applied. " string += "Current locks on %s:" % channel.key string = "%s\n %s" % (string, channel.locks) self.caller.msg(string) class CmdCdesc(MuxCommand): """ @cdesc - set channel description Usage: @cdesc <channel> = <description> Changes the description of the channel as shown in channel lists. """ key = "@cdesc" locks = "cmd:not pperm(channel_banned)" help_category = "Comms" def func(self): "Implement command" caller = self.caller if not self.rhs: caller.msg("Usage: @cdesc <channel> = <description>") return channel = find_channel(caller, self.lhs) if not channel: caller.msg("Channel '%s' not found." % self.lhs) return #check permissions if not caller.access(caller, 'control'): caller.msg("You cant admin this channel.") return # set the description channel.desc = self.rhs channel.save() caller.msg("Description of channel '%s' set to '%s'." % (channel.key, self.rhs)) class CmdPage(MuxCommand): """ page - send private message Usage: page[/switches] [<player>,<player>,... = <message>] tell '' page <number> Switch: last - shows who you last messaged list - show your last <number> of tells/pages (default) Send a message to target user (if online). If no argument is given, you will get a list of your latest messages. """ key = "page" aliases = ['tell'] locks = "cmd:not pperm(page_banned)" help_category = "Comms" def func(self): "Implement function using the Msg methods" caller = self.caller player = caller # get the messages we've sent messages_we_sent = list(Msg.objects.get_messages_by_sender(player)) pages_we_sent = [msg for msg in messages_we_sent if msg.receivers] # get last messages we've got pages_we_got = list(Msg.objects.get_messages_by_receiver(player)) if 'last' in self.switches: if pages_we_sent: string = "You last paged {c%s{n." % (", ".join([obj.name for obj in pages_we_sent[-1].receivers])) caller.msg(string) return else: string = "You haven't paged anyone yet." caller.msg(string) return if not self.args or not self.rhs: pages = pages_we_sent + pages_we_got pages.sort(lambda x, y: cmp(x.date_sent, y.date_sent)) number = 5 if self.args: try: number = int(self.args) except ValueError: caller.msg("Usage: tell [<player> = msg]") return if len(pages) > number: lastpages = pages[-number:] else: lastpages = pages lastpages = "\n ".join(["{w%s{n {c%s{n to {c%s{n: %s" % (utils.datetime_format(page.date_sent), page.sender.name, "{n,{c ".join([obj.name for obj in page.receivers]), page.message) for page in lastpages]) if lastpages: string = "Your latest pages:\n %s" % lastpages else: string = "You haven't paged anyone yet." caller.msg(string) return # We are sending. Build a list of targets if not self.lhs: # If there are no targets, then set the targets # to the last person they paged. if pages_we_sent: receivers = pages_we_sent[-1].receivers else: caller.msg("Who do you want to page?") return else: receivers = self.lhslist recobjs = [] for receiver in set(receivers): if isinstance(receiver, basestring): pobj = caller.search("*%s" % (receiver.lstrip('*')), global_search=True) if not pobj: return elif hasattr(receiver, 'character'): pobj = receiver.character else: caller.msg("Who do you want to page?") return recobjs.append(pobj) if not recobjs: caller.msg("No players matching your target were found.") return header = "{wPlayer{n {c%s{n {wpages:{n" % caller.key message = self.rhs # if message begins with a :, we assume it is a 'page-pose' if message.startswith(":"): message = "%s %s" % (caller.key, message.strip(':').strip()) # create the persistent message object msg = create.create_message(player, message, receivers=recobjs) # tell the players they got a message. received = [] rstrings = [] for pobj in recobjs: if not pobj.access(caller, 'msg'): rstrings.append("You are not allowed to page %s." % pobj) continue pobj.msg("%s %s" % (header, message)) if hasattr(pobj, 'has_player') and not pobj.has_player: received.append("{C%s{n" % pobj.name) rstrings.append("%s is offline. They will see your message if they list their pages later." % received[-1]) else: received.append("{c%s{n" % pobj.name) if rstrings: caller.msg(rstrings = "\n".join(rstrings)) caller.msg("You paged %s with: '%s'." % (", ".join(received), message)) class CmdIRC2Chan(MuxCommand): """ @irc2chan - link evennia channel to an IRC channel Usage: @irc2chan[/switches] <evennia_channel> = <ircnetwork> <port> <#irchannel> <botname> Switches: /disconnect - this will delete the bot and remove the irc connection to the channel. /remove - " /list - show all irc<->evennia mappings Example: @irc2chan myircchan = irc.dalnet.net 6667 myevennia-channel evennia-bot This creates an IRC bot that connects to a given IRC network and channel. It will relay everything said in the evennia channel to the IRC channel and vice versa. The bot will automatically connect at server start, so this comman need only be given once. The /disconnect switch will permanently delete the bot. To only temporarily deactivate it, use the @services command instead. """ key = "@irc2chan" locks = "cmd:serversetting(IRC_ENABLED) and pperm(Immortals)" help_category = "Comms" def func(self): "Setup the irc-channel mapping" if not settings.IRC_ENABLED: string = """IRC is not enabled. You need to activate it in game/settings.py.""" self.caller.msg(string) return if 'list' in self.switches: # show all connections connections = ExternalChannelConnection.objects.filter(db_external_key__startswith='irc_') if connections: cols = [["Evennia channel"], ["IRC channel"]] for conn in connections: cols[0].append(conn.channel.key) cols[1].append(" ".join(conn.external_config.split('|'))) ftable = utils.format_table(cols) string = "" for ir, row in enumerate(ftable): if ir == 0: string += "{w%s{n" % "".join(row) else: string += "\n" + "".join(row) self.caller.msg(string) else: self.caller.msg("No connections found.") return if not self.args or not self.rhs: string = "Usage: @irc2chan[/switches] <evennia_channel> = <ircnetwork> <port> <#irchannel> <botname>" self.caller.msg(string) return channel = self.lhs self.rhs = self.rhs.replace('#', ' ') # to avoid Python comment issues try: irc_network, irc_port, irc_channel, irc_botname = [part.strip() for part in self.rhs.split(None, 3)] irc_channel = "#%s" % irc_channel except Exception: string = "IRC bot definition '%s' is not valid." % self.rhs self.caller.msg(string) return if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches: chanmatch = find_channel(self.caller, channel, silent=True) if chanmatch: channel = chanmatch.key ok = irc.delete_connection(channel, irc_network, irc_port, irc_channel, irc_botname) if not ok: self.caller.msg("IRC connection/bot could not be removed, does it exist?") else: self.caller.msg("IRC connection destroyed.") return channel = find_channel(self.caller, channel) if not channel: return ok = irc.create_connection(channel, irc_network, irc_port, irc_channel, irc_botname) if not ok: self.caller.msg("This IRC connection already exists.") return self.caller.msg("Connection created. Starting IRC bot.") class CmdIMC2Chan(MuxCommand): """ imc2chan - link an evennia channel to imc2 Usage: @imc2chan[/switches] <evennia_channel> = <imc2_channel> Switches: /disconnect - this clear the imc2 connection to the channel. /remove - " /list - show all imc2<->evennia mappings Example: @imc2chan myimcchan = ievennia Connect an existing evennia channel to a channel on an IMC2 network. The network contact information is defined in settings and should already be accessed at this point. Use @imcchanlist to see available IMC channels. """ key = "@imc2chan" locks = "cmd:serversetting(IMC2_ENABLED) and pperm(Immortals)" help_category = "Comms" def func(self): "Setup the imc-channel mapping" if not settings.IMC2_ENABLED: string = """IMC is not enabled. You need to activate it in game/settings.py.""" self.caller.msg(string) return if 'list' in self.switches: # show all connections connections = ExternalChannelConnection.objects.filter(db_external_key__startswith='imc2_') if connections: cols = [["Evennia channel"], ["<->"], ["IMC channel"]] for conn in connections: cols[0].append(conn.channel.key) cols[1].append("") cols[2].append(conn.external_config) ftable = utils.format_table(cols) string = "" for ir, row in enumerate(ftable): if ir == 0: string += "{w%s{n" % "".join(row) else: string += "\n" + "".join(row) self.caller.msg(string) else: self.caller.msg("No connections found.") return if not self.args or not self.rhs: string = "Usage: @imc2chan[/switches] <evennia_channel> = <imc2_channel>" self.caller.msg(string) return channel = self.lhs imc2_channel = self.rhs if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches: # we don't search for channels before this since we want to clear the link # also if the channel no longer exists. ok = imc2.delete_connection(channel, imc2_channel) if not ok: self.caller.msg("IMC2 connection could not be removed, does it exist?") else: self.caller.msg("IMC2 connection destroyed.") return # actually get the channel object channel = find_channel(self.caller, channel) if not channel: return ok = imc2.create_connection(channel, imc2_channel) if not ok: self.caller.msg("The connection %s <-> %s already exists." % (channel.key, imc2_channel)) return self.caller.msg("Created connection channel %s <-> IMC channel %s." % (channel.key, imc2_channel)) class CmdIMCInfo(MuxCommand): """ imcinfo - package of imc info commands Usage: @imcinfo[/switches] @imcchanlist - list imc2 channels @imclist - list connected muds @imcwhois <playername> - whois info about a remote player Switches for @imcinfo: channels - as @imcchanlist (default) games or muds - as @imclist whois - as @imcwhois (requires an additional argument) update - force an update of all lists Shows lists of games or channels on the IMC2 network. """ key = "@imcinfo" aliases = ["@imcchanlist", "@imclist", "@imcwhois"] locks = "cmd: serversetting(IMC2_ENABLED) and pperm(Wizards)" help_category = "Comms" def func(self): "Run the command" if not settings.IMC2_ENABLED: string = """IMC is not enabled. You need to activate it in game/settings.py.""" self.caller.msg(string) return if "update" in self.switches: # update the lists import time from src.comms.imc2lib import imc2_packets as pck from src.comms.imc2 import IMC2_MUDLIST, IMC2_CHANLIST, IMC2_CLIENT # update connected muds IMC2_CLIENT.send_packet(pck.IMC2PacketKeepAliveRequest()) # prune inactive muds for name, mudinfo in IMC2_MUDLIST.mud_list.items(): if time.time() - mudinfo.last_updated > 3599: del IMC2_MUDLIST.mud_list[name] # update channel list IMC2_CLIENT.send_packet(pck.IMC2PacketIceRefresh()) self.caller.msg("IMC2 lists were re-synced.") elif "games" in self.switches or "muds" in self.switches or self.cmdstring == "@imclist": # list muds from src.comms.imc2 import IMC2_MUDLIST muds = IMC2_MUDLIST.get_mud_list() networks = set(mud.networkname for mud in muds) string = "" nmuds = 0 for network in networks: string += "\n {GMuds registered on %s:{n" % network cols = [["Name"], ["Url"], ["Host"], ["Port"]] for mud in (mud for mud in muds if mud.networkname == network): nmuds += 1 cols[0].append(mud.name) cols[1].append(mud.url) cols[2].append(mud.host) cols[3].append(mud.port) ftable = utils.format_table(cols) for ir, row in enumerate(ftable): if ir == 0: string += "\n{w" + "".join(row) + "{n" else: string += "\n" + "".join(row) string += "\n %i Muds found." % nmuds self.caller.msg(string) elif "whois" in self.switches or self.cmdstring == "@imcwhois": # find out about a player if not self.args: self.caller.msg("Usage: @imcwhois <playername>") return from src.comms.imc2 import IMC2_CLIENT self.caller.msg("Sending IMC whois request. If you receive no response, no matches were found.") IMC2_CLIENT.msg_imc2(None, from_obj=self.caller, packet_type="imcwhois", data={"target":self.args}) elif not self.switches or "channels" in self.switches or self.cmdstring == "@imcchanlist": # show channels from src.comms.imc2 import IMC2_CHANLIST, IMC2_CLIENT channels = IMC2_CHANLIST.get_channel_list() string = "" nchans = 0 string += "\n {GChannels on %s:{n" % IMC2_CLIENT.factory.network cols = [["Full name"], ["Name"], ["Owner"], ["Perm"], ["Policy"]] for channel in channels: nchans += 1 cols[0].append(channel.name) cols[1].append(channel.localname) cols[2].append(channel.owner) cols[3].append(channel.level) cols[4].append(channel.policy) ftable = utils.format_table(cols) for ir, row in enumerate(ftable): if ir == 0: string += "\n{w" + "".join(row) + "{n" else: string += "\n" + "".join(row) string += "\n %i Channels found." % nchans self.caller.msg(string) else: # no valid inputs string = "Usage: imcinfo|imcchanlist|imclist" self.caller.msg(string) # unclear if this is working ... class CmdIMCTell(MuxCommand): """ imctell - send a page to a remote IMC player Usage: imctell User@MUD = <msg> imcpage " Sends a page to a user on a remote MUD, connected over IMC2. """ key = "imctell" aliases = ["imcpage", "imc2tell", "imc2page"] locks = "cmd: serversetting(IMC2_ENABLED)" help_category = "Comms" def func(self): "Send tell across IMC" if not settings.IMC2_ENABLED: string = """IMC is not enabled. You need to activate it in game/settings.py.""" self.caller.msg(string) return from src.comms.imc2 import IMC2_CLIENT if not self.args or not '@' in self.lhs or not self.rhs: string = "Usage: imctell User@Mud = <msg>" self.caller.msg(string) return target, destination = self.lhs.split("@", 1) message = self.rhs.strip() data = {"target":target, "destination":destination} # send to imc2 IMC2_CLIENT.msg_imc2(message, from_obj=self.caller, packet_type="imctell", data=data) self.caller.msg("You paged {c%s@%s{n (over IMC): '%s'." % (target, destination, message)) # RSS connection class CmdRSS2Chan(MuxCommand): """ @rss2chan - link evennia channel to an RSS feed Usage: @rss2chan[/switches] <evennia_channel> = <rss_url> Switches: /disconnect - this will stop the feed and remove the connection to the channel. /remove - " /list - show all rss->evennia mappings Example: @rss2chan rsschan = http://code.google.com/feeds/p/evennia/updates/basic This creates an RSS reader that connects to a given RSS feed url. Updates will be echoed as a title and news link to the given channel. The rate of updating is set with the RSS_UPDATE_INTERVAL variable in settings (default is every 10 minutes). When disconnecting you need to supply both the channel and url again so as to identify the connection uniquely. """ key = "@rss2chan" locks = "cmd:serversetting(RSS_ENABLED) and pperm(Immortals)" help_category = "Comms" def func(self): "Setup the rss-channel mapping" if not settings.RSS_ENABLED: string = """RSS is not enabled. You need to activate it in game/settings.py.""" self.caller.msg(string) return if 'list' in self.switches: # show all connections connections = ExternalChannelConnection.objects.filter(db_external_key__startswith='rss_') if connections: cols = [["Evennia-channel"], ["RSS-url"]] for conn in connections: cols[0].append(conn.channel.key) cols[1].append(conn.external_config.split('|')[0]) ftable = utils.format_table(cols) string = "" for ir, row in enumerate(ftable): if ir == 0: string += "{w%s{n" % "".join(row) else: string += "\n" + "".join(row) self.caller.msg(string) else: self.caller.msg("No connections found.") return if not self.args or not self.rhs: string = "Usage: @rss2chan[/switches] <evennia_channel> = <rss url>" self.caller.msg(string) return channel = self.lhs url = self.rhs if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches: chanmatch = find_channel(self.caller, channel, silent=True) if chanmatch: channel = chanmatch.key ok = rss.delete_connection(channel, url) if not ok: self.caller.msg("RSS connection/reader could not be removed, does it exist?") else: self.caller.msg("RSS connection destroyed.") return channel = find_channel(self.caller, channel) if not channel: return interval = settings.RSS_UPDATE_INTERVAL if not interval: interval = 10*60 ok = rss.create_connection(channel, url, interval) if not ok: self.caller.msg("This RSS connection already exists.") return self.caller.msg("Connection created. Starting RSS reader.")
Python
""" System commands These are the default commands called by the system commandhandler when various exceptions occur. If one of these commands are not implemented and part of the current cmdset, the engine falls back to a default solution instead. Some system commands are shown in this module as a REFERENCE only (they are not all added to Evennia's default cmdset since they don't currently do anything differently from the default backup systems hard-wired in the engine). Overloading these commands in a cmdset can be used to create interesting effects. An example is using the NoMatch system command to implement a line-editor where you don't have to start each line with a command (if there is no match to a known command, the line is just added to the editor buffer). """ from src.comms.models import Channel from src.utils import create # The command keys the engine is calling # (the actual names all start with __) from src.commands.cmdhandler import CMD_NOINPUT from src.commands.cmdhandler import CMD_NOMATCH from src.commands.cmdhandler import CMD_MULTIMATCH from src.commands.cmdhandler import CMD_CHANNEL from src.commands.default.muxcommand import MuxCommand # Command called when there is no input at line # (i.e. an lone return key) class SystemNoInput(MuxCommand): """ This is called when there is no input given """ key = CMD_NOINPUT locks = "cmd:all()" def func(self): "Do nothing." pass # # Command called when there was no match to the # command name # class SystemNoMatch(MuxCommand): """ No command was found matching the given input. """ key = CMD_NOMATCH locks = "cmd:all()" def func(self): """ This is given the failed raw string as input. """ self.caller.msg("Huh?") # # Command called when there were mulitple matches to the command. # class SystemMultimatch(MuxCommand): """ Multiple command matches. The cmdhandler adds a special attribute 'matches' to this system command. matches = [(candidate, cmd) , (candidate, cmd), ...], where candidate is an instance of src.commands.cmdparser.CommandCandidate and cmd is an an instantiated Command object matching the candidate. """ key = CMD_MULTIMATCH locks = "cmd:all()" def format_multimatches(self, caller, matches): """ Format multiple command matches to a useful error. This is copied directly from the default method in src.commands.cmdhandler. """ string = "There where multiple matches:" for num, match in enumerate(matches): # each match is a tuple (candidate, cmd) candidate, cmd = match is_channel = hasattr(cmd, "is_channel") and cmd.is_channel if is_channel: is_channel = " (channel)" else: is_channel = "" is_exit = hasattr(cmd, "is_exit") and cmd.is_exit if is_exit and cmd.destination: is_exit = " (exit to %s)" % cmd.destination else: is_exit = "" id1 = "" id2 = "" if not (is_channel or is_exit) and (hasattr(cmd, 'obj') and cmd.obj != caller): # the command is defined on some other object id1 = "%s-" % cmd.obj.name id2 = " (%s-%s)" % (num + 1, candidate.cmdname) else: id1 = "%s-" % (num + 1) id2 = "" string += "\n %s%s%s%s%s" % (id1, candidate.cmdname, id2, is_channel, is_exit) return string def func(self): """ argument to cmd is a comma-separated string of all the clashing matches. """ string = self.format_multimatches(self.caller, self.matches) self.caller.msg(string) # Command called when the command given at the command line # was identified as a channel name, like there existing a # channel named 'ooc' and the user wrote # > ooc Hello! class SystemSendToChannel(MuxCommand): """ This is a special command that the cmdhandler calls when it detects that the command given matches an existing Channel object key (or alias). """ key = CMD_CHANNEL locks = "cmd:all()" def parse(self): channelname, msg = self.args.split(':', 1) self.args = channelname.strip(), msg.strip() def func(self): """ Create a new message and send it to channel, using the already formatted input. """ caller = self.caller channelkey, msg = self.args 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) msgobj = create.create_message(caller, msg, channels=[channel]) channel.msg(msgobj)
Python
""" This module describes the unlogged state of the default game. The setting STATE_UNLOGGED should be set to the python path of the state instance in this module. """ from src.commands.cmdset import CmdSet from src.commands.default import unloggedin class UnloggedinCmdSet(CmdSet): """ Sets up the unlogged cmdset. """ key = "Unloggedin" priority = 0 def at_cmdset_creation(self): "Populate the cmdset" self.add(unloggedin.CmdConnect()) self.add(unloggedin.CmdCreate()) self.add(unloggedin.CmdQuit()) self.add(unloggedin.CmdUnconnectedLook()) self.add(unloggedin.CmdUnconnectedHelp())
Python
""" This is the cmdset for OutOfCharacter (OOC) commands. These are stored on the Player object and should thus be able to handle getting a Player object as caller rather than a Character. """ from src.commands.cmdset import CmdSet from src.commands.default import help, comms, general, admin class OOCCmdSet(CmdSet): """ Implements the player command set. """ key = "DefaultOOC" priority = -5 def at_cmdset_creation(self): "Populates the cmdset" # general commands self.add(general.CmdOOCLook()) self.add(general.CmdIC()) self.add(general.CmdOOC()) self.add(general.CmdEncoding()) self.add(general.CmdQuit()) self.add(general.CmdPassword()) # help command self.add(help.CmdHelp()) # admin commands self.add(admin.CmdBoot()) self.add(admin.CmdDelPlayer()) self.add(admin.CmdNewPassword()) # Comm commands self.add(comms.CmdAddCom()) self.add(comms.CmdDelCom()) self.add(comms.CmdAllCom()) self.add(comms.CmdChannels()) self.add(comms.CmdCdestroy()) self.add(comms.CmdChannelCreate()) self.add(comms.CmdCset()) self.add(comms.CmdCBoot()) self.add(comms.CmdCemit()) self.add(comms.CmdCWho()) self.add(comms.CmdCdesc()) self.add(comms.CmdPage()) self.add(comms.CmdIRC2Chan()) self.add(comms.CmdIMC2Chan()) self.add(comms.CmdIMCInfo()) self.add(comms.CmdIMCTell()) self.add(comms.CmdRSS2Chan())
Python
""" This module ties together all the commands of the default command set. Note that some commands, such as communication-commands are instead put in the OOC cmdset. """ from src.commands.cmdset import CmdSet from src.commands.default import general, help, admin, system from src.commands.default import building from src.commands.default import batchprocess class DefaultCmdSet(CmdSet): """ Implements the default command set. """ key = "DefaultMUX" priority = 0 def at_cmdset_creation(self): "Populates the cmdset" # The general commands self.add(general.CmdLook()) self.add(general.CmdHome()) self.add(general.CmdWho()) self.add(general.CmdInventory()) self.add(general.CmdPose()) self.add(general.CmdNick()) self.add(general.CmdGet()) self.add(general.CmdDrop()) self.add(general.CmdSay()) self.add(general.CmdAccess()) # The help system self.add(help.CmdHelp()) self.add(help.CmdSetHelp()) # System commands self.add(system.CmdReload()) self.add(system.CmdReset()) self.add(system.CmdShutdown()) self.add(system.CmdPy()) self.add(system.CmdScripts()) self.add(system.CmdObjects()) self.add(system.CmdService()) self.add(system.CmdVersion()) self.add(system.CmdTime()) self.add(system.CmdServerLoad()) self.add(system.CmdPs()) # Admin commands self.add(admin.CmdBoot()) self.add(admin.CmdBan()) self.add(admin.CmdUnban()) self.add(admin.CmdDelPlayer()) self.add(admin.CmdEmit()) self.add(admin.CmdNewPassword()) self.add(admin.CmdPerm()) self.add(admin.CmdWall()) # Building and world manipulation self.add(building.CmdTeleport()) self.add(building.CmdSetObjAlias()) self.add(building.CmdListCmdSets()) self.add(building.CmdDebug()) self.add(building.CmdWipe()) self.add(building.CmdSetAttribute()) self.add(building.CmdName()) self.add(building.CmdDesc()) self.add(building.CmdCpAttr()) self.add(building.CmdMvAttr()) self.add(building.CmdCopy()) self.add(building.CmdFind()) self.add(building.CmdOpen()) self.add(building.CmdLink()) self.add(building.CmdUnLink()) self.add(building.CmdCreate()) self.add(building.CmdDig()) self.add(building.CmdTunnel()) self.add(building.CmdDestroy()) self.add(building.CmdExamine()) self.add(building.CmdTypeclass()) self.add(building.CmdLock()) self.add(building.CmdScript()) self.add(building.CmdHome()) # Batchprocessor commands self.add(batchprocess.CmdBatchCommands()) self.add(batchprocess.CmdBatchCode())
Python
# -*- coding: utf-8 -*- """ ** OBS - this is not a normal command module! ** ** You cannot import anything in this module as a command! ** This is part of the Evennia unittest framework, for testing the stability and integrity of the codebase during updates. This module test the default command set. It is instantiated by the src/objects/tests.py module, which in turn is run by as part of the main test suite started with > python game/manage.py test. """ import re, time 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.utils import create, ansi from src.server import serversession, sessionhandler from src.locks.lockhandler import LockHandler from src.server.models import ServerConfig from src.comms.models import Channel, Msg, PlayerChannelConnection, ExternalChannelConnection from django.contrib.auth.models import User from src.players.models import PlayerDB from src.objects.models import ObjectDB #------------------------------------------------------------ # Command testing # ------------------------------------------------------------ # print all feedback from test commands (can become very verbose!) VERBOSE = False def cleanup(): User.objects.all().delete() PlayerDB.objects.all().delete() ObjectDB.objects.all().delete() Channel.objects.all().delete() Msg.objects.all().delete() PlayerChannelConnection.objects.all().delete() ExternalChannelConnection.objects.all().delete() ServerConfig.objects.all().delete() class FakeSessionHandler(sessionhandler.ServerSessionHandler): """ Fake sessionhandler, without an amp connection """ def portal_shutdown(self): pass def disconnect(self, session, reason=""): pass def login(self, session): pass def session_sync(self): pass def data_out(self, session, string="", data=""): return string SESSIONS = FakeSessionHandler() class FakeSession(serversession.ServerSession): """ A fake session that implements dummy versions of the real thing; this is needed to mimic a logged-in player. """ protocol_key = "TestProtocol" sessdict = {'protocol_key':'telnet', 'address':('0.0.0.0','5000'), 'sessid':2, 'uid':2, 'uname':None, 'logged_in':False, 'cid':None, 'ndb':{}, 'encoding':'utf-8', 'conn_time':time.time(), 'cmd_last':time.time(), 'cmd_last_visible':time.time(), 'cmd_total':1} def connectionMade(self): self.load_sync_data(self.sessdict) self.sessionhandler = SESSIONS def disconnectClient(self): pass def lineReceived(self, raw_string): pass def msg(self, message, data=None): if message.startswith("Traceback (most recent call last):"): #retval = "Traceback last line: %s" % message.split('\n')[-4:] raise AssertionError(message) if self.player.character.ndb.return_string != None: return_list = self.player.character.ndb.return_string if hasattr(return_list, '__iter__'): rstring = return_list.pop(0) self.player.character.ndb.return_string = return_list else: rstring = return_list self.player.character.ndb.return_string = None message_noansi = ansi.parse_ansi(message, strip_ansi=True).strip() rstring = rstring.strip() if not message_noansi.startswith(rstring): sep1 = "\n" + "="*30 + "Wanted message" + "="*34 + "\n" sep2 = "\n" + "="*30 + "Returned message" + "="*32 + "\n" sep3 = "\n" + "="*78 retval = sep1 + rstring + sep2 + message_noansi + sep3 raise AssertionError(retval) if VERBOSE: print message class CommandTest(TestCase): """ Sets up the basics of testing the default commands and the generic things that should always be present in a command. Inherit new tests from this. """ NOMANGLE = True # mangle command input for extra testing def setUp(self): "sets up the testing environment" #ServerConfig.objects.conf("default_home", 2) self.addCleanup(cleanup) self.room1 = create.create_object(settings.BASE_ROOM_TYPECLASS, key="room1") self.room2 = create.create_object(settings.BASE_ROOM_TYPECLASS, key="room2") # create a faux player/character for testing. self.char1 = create.create_player("TestChar", "testplayer@test.com", "testpassword", character_location=self.room1) self.char1.player.user.is_superuser = True self.char1.lock_storage = "" self.char1.locks = LockHandler(self.char1) self.char1.ndb.return_string = None sess = FakeSession() sess.connectionMade() sess.session_login(self.char1.player) # create second player self.char2 = create.create_player("TestChar2", "testplayer2@test.com", "testpassword2", character_location=self.room1) self.char2.player.user.is_superuser = False self.char2.lock_storage = "" self.char2.locks = LockHandler(self.char2) self.char2.ndb.return_string = None sess2 = FakeSession() sess2.connectionMade() sess2.session_login(self.char2.player) # A non-player-controlled character self.char3 = create.create_object(settings.BASE_CHARACTER_TYPECLASS, key="TestChar3", location=self.room1) # create some objects self.obj1 = create.create_object(settings.BASE_OBJECT_TYPECLASS, key="obj1", location=self.room1) self.obj2 = create.create_object(settings.BASE_OBJECT_TYPECLASS, key="obj2", location=self.room1) self.exit1 = create.create_object(settings.BASE_EXIT_TYPECLASS, key="exit1", location=self.room1) self.exit2 = create.create_object(settings.BASE_EXIT_TYPECLASS, key="exit2", location=self.room2) def tearDown(self): "Cleans up testing environment after test has run." User.objects.all().delete() PlayerDB.objects.all().delete() ObjectDB.objects.all().delete() Channel.objects.all().delete() Msg.objects.all().delete() PlayerChannelConnection.objects.all().delete() ExternalChannelConnection.objects.all().delete() ServerConfig.objects.all().delete() def get_cmd(self, cmd_class, argument_string=""): """ Obtain a cmd instance from a class and an input string Note: This does not make use of the cmdhandler functionality. """ cmd = cmd_class() cmd.caller = self.char1 cmd.cmdstring = cmd_class.key cmd.args = argument_string cmd.cmdset = None cmd.obj = self.char1 return cmd def execute_cmd(self, raw_string, wanted_return_string=None, nomangle=False): """ Creates the command through faking a normal command call; This also mangles the input in various ways to test if the command will be fooled. """ if not nomangle and not VERBOSE and not self.NOMANGLE: # only mangle if not VERBOSE, to make fewer return lines test1 = re.sub(r'\s', '', raw_string) # remove all whitespace inside it test2 = "%s/åäö öäö;-:$£@*~^' 'test" % raw_string # inserting weird characters in call test3 = "%s %s" % (raw_string, raw_string) # multiple calls self.char1.execute_cmd(test1) self.char1.execute_cmd(test2) self.char1.execute_cmd(test3) # actual call, we potentially check so return is ok. self.char1.ndb.return_string = wanted_return_string try: self.char1.execute_cmd(raw_string) except AssertionError, e: self.fail(e) self.char1.ndb.return_string = None class BuildTest(CommandTest): """ We need to turn of mangling for build commands since it creates arbitrary objects that mess up tests later. """ NOMANGLE = True #------------------------------------------------------------ # Default set Command testing #------------------------------------------------------------ # # general.py tests class TestLook(CommandTest): def test_call(self): self.execute_cmd("look here") class TestHome(CommandTest): def test_call(self): self.char1.location = self.room1 self.char1.home = self.room2 self.execute_cmd("home") self.assertEqual(self.char1.location, self.room2) class TestPassword(CommandTest): def test_call(self): self.execute_cmd("@password testpassword = newpassword") class TestInventory(CommandTest): def test_call(self): self.execute_cmd("inv") class TestQuit(CommandTest): def test_call(self): self.execute_cmd("@quit") class TestPose(CommandTest): def test_call(self): self.execute_cmd("pose is testing","TestChar is testing") class TestNick(CommandTest): def test_call(self): self.char1.player.user.is_superuser = False self.execute_cmd("nickname testalias = testaliasedstring1") self.execute_cmd("nickname/player testalias = testaliasedstring2") self.execute_cmd("nickname/object testalias = testaliasedstring3") self.assertEqual(u"testaliasedstring1", self.char1.nicks.get("testalias")) self.assertEqual(u"testaliasedstring2", self.char1.nicks.get("testalias",nick_type="player")) self.assertEqual(u"testaliasedstring3", self.char1.nicks.get("testalias",nick_type="object")) class TestGet(CommandTest): def test_call(self): self.obj1.location = self.room1 self.execute_cmd("get obj1", "You pick up obj1.") class TestDrop(CommandTest): def test_call(self): self.obj1.location = self.char1 self.execute_cmd("drop obj1", "You drop obj1.") class TestWho(CommandTest): def test_call(self): self.execute_cmd("who") class TestSay(CommandTest): def test_call(self): self.execute_cmd("say Hello", 'You say, "Hello') class TestAccess(CommandTest): def test_call(self): self.execute_cmd("access") class TestEncoding(CommandTest): def test_call(self): global NOMANGLE NOMANGLE = True self.char1.db.encoding="utf-8" self.execute_cmd("@encoding", "Default encoding:") NOMANGLE = False # help.py command tests class TestHelpSystem(CommandTest): def test_call(self): self.NOMANGLE = True sep = "-"*78 + "\n" self.execute_cmd("@help/add TestTopic,TestCategory = Test1", ) self.execute_cmd("help TestTopic",sep + "Help topic for Testtopic\nTest1" + "\n" + sep) self.execute_cmd("@help/merge TestTopic = Test2", "Added the new text right after") self.execute_cmd("help TestTopic", sep + "Help topic for Testtopic\nTest1 Test2") self.execute_cmd("@help/append TestTopic = Test3", "Added the new text as a") self.execute_cmd("help TestTopic",sep + "Help topic for Testtopic\nTest1 Test2\n\nTest3") self.execute_cmd("@help/delete TestTopic","Deleted the help entry") self.execute_cmd("help TestTopic","No help entry found for 'TestTopic'") # system.py command tests class TestPy(CommandTest): def test_call(self): self.execute_cmd("@py 1+2", [">>> 1+2", "<<< 3"]) class TestScripts(CommandTest): def test_call(self): script = create.create_script(None, "test") self.execute_cmd("@scripts", "id") class TestObjects(CommandTest): def test_call(self): self.execute_cmd("@objects", "Database totals") # Cannot be tested since we don't have an active server running at this point. # class TestListService(CommandTest): # def test_call(self): # self.execute_cmd("@service/list", "---") class TestVersion(CommandTest): def test_call(self): self.execute_cmd("@version", '---') class TestTime(CommandTest): def test_call(self): self.execute_cmd("@time", "Current server uptime") class TestServerLoad(CommandTest): def test_call(self): self.execute_cmd("@serverload", "Server load") class TestPs(CommandTest): def test_call(self): self.execute_cmd("@ps","Non-timed scripts") # admin.py command tests class TestBoot(CommandTest): def test_call(self): self.execute_cmd("@boot TestChar2","You booted TestChar2.") class TestDelPlayer(CommandTest): def test_call(self): self.execute_cmd("@delplayer TestChar2","Booting and informing player ...") class TestEmit(CommandTest): def test_call(self): self.execute_cmd("@emit Test message", "Emitted to room1.") class TestUserPassword(CommandTest): def test_call(self): self.execute_cmd("@userpassword TestChar2 = newpass", "TestChar2 - new password set to 'newpass'.") class TestPerm(CommandTest): def test_call(self): self.execute_cmd("@perm TestChar2 = Builders", "Permission 'Builders' given to") # cannot test this here; screws up the test suite #class TestPuppet(CommandTest): # def test_call(self): # self.execute_cmd("@puppet TestChar3", "You now control TestChar3.") # self.execute_cmd("@puppet TestChar", "You now control TestChar.") class TestWall(CommandTest): def test_call(self): self.execute_cmd("@wall = This is a test message", "TestChar shouts") # building.py command tests class TestObjAlias(BuildTest): def test_call(self): self.execute_cmd("@alias obj1 = obj1alias, obj1alias2", "Aliases for") self.execute_cmd("look obj1alias2", "obj1") class TestCopy(BuildTest): def test_call(self): self.execute_cmd("@copy obj1 = obj1_copy;alias1;alias2", "Copied obj1 to 'obj1_copy'") self.execute_cmd("look alias2","obj1_copy") class TestSet(BuildTest): def test_call(self): self.execute_cmd("@set obj1/test = value", "Created attribute obj1/test = value") self.execute_cmd("@set obj1/test", "Attribute obj1/test = value") self.assertEqual(self.obj1.db.test, u"value") class TestCpAttr(BuildTest): def test_call(self): self.execute_cmd("@set obj1/test = value") self.execute_cmd("@set me/test2 = value2") self.execute_cmd("@cpattr obj1/test = obj2/test") self.execute_cmd("@cpattr test2 = obj2") self.assertEqual(self.obj2.db.test, u"value") self.assertEqual(self.obj2.db.test2, u"value2") class TestMvAttr(BuildTest): def test_call(self): self.execute_cmd("@set obj1/test = value") self.execute_cmd("@mvattr obj1/test = obj2") self.assertEqual(self.obj2.db.test, u"value") self.assertEqual(self.obj1.db.test, None) class TestCreate(BuildTest): def test_call(self): self.execute_cmd("@create testobj;alias1;alias2") self.execute_cmd("look alias1", "testobj") class TestDebug(BuildTest): def test_call(self): self.execute_cmd("@debug/obj obj1") class TestDesc(BuildTest): def test_call(self): self.execute_cmd("@desc obj1 = Test object", "The description was set on") self.assertEqual(self.obj1.db.desc, u"Test object") class TestDestroy(BuildTest): def test_call(self): self.execute_cmd("@destroy obj1, obj2", "obj1 was destroyed.\nobj2 was destroyed.") class TestFind(BuildTest): def test_call(self): self.execute_cmd("@find obj1", "One Match") class TestDig(BuildTest): def test_call(self): self.execute_cmd("@dig room3;roomalias1;roomalias2 = north;n,south;s") self.execute_cmd("@find room3", "One Match") self.execute_cmd("@find roomalias1", "One Match") self.execute_cmd("@find roomalias2", "One Match") self.execute_cmd("@find/room roomalias2", "One Match") self.execute_cmd("@find/exit south", "One Match") self.execute_cmd("@find/exit n", "One Match") class TestUnLink(BuildTest): def test_call(self): self.execute_cmd("@dig room3;roomalias1, north, south") self.execute_cmd("@unlink north") class TestLink(BuildTest): def test_call(self): self.execute_cmd("@dig room3;roomalias1, north, south") self.execute_cmd("@unlink north") self.execute_cmd("@link north = room3") class TestHome(BuildTest): def test_call(self): self.obj1.db_home = self.obj2.dbobj self.obj1.save() self.execute_cmd("@home obj1") self.assertEqual(self.obj1.db_home, self.obj2.dbobj) class TestCmdSets(BuildTest): def test_call(self): self.execute_cmd("@cmdsets") self.execute_cmd("@cmdsets obj1") class TestDesc(BuildTest): def test_call(self): self.execute_cmd("@name obj1 = Test object", "Object's name changed to 'Test object'.") self.assertEqual(self.obj1.key, u"Test object") class TestOpen(BuildTest): def test_call(self): self.execute_cmd("@dig room4;roomalias4") self.execute_cmd("@open testexit4;aliasexit4 = roomalias4", "Created new Exit") class TestScript(BuildTest): def test_call(self): self.execute_cmd("@typeclass obj1 = src.objects.objects.Character", "obj's type is now") self.assertEqual(self.obj1.db_typeclass_path, u"src.objects.objects.Character") class TestScript(BuildTest): def test_call(self): self.execute_cmd("@set box1/test = value") self.execute_cmd("@wipe box1", "Wiped") self.assertEqual(self.obj1.db.all(), []) class TestLock(BuildTest): # lock functionality itseld is tested separately def test_call(self): self.char1.permissions = ["TestPerm"] self.execute_cmd("@lock obj1 = test:perm(TestPerm)") self.assertEqual(True, self.obj1.access(self.char1, u"test")) class TestExamine(BuildTest): def test_call(self): self.execute_cmd("examine obj1", "------------") class TestTeleport(BuildTest): def test_call(self): self.execute_cmd("@tel obj1 = obj2") self.assertEqual(self.obj1.location, self.obj2.dbobj) class TestScript(BuildTest): def test_call(self): self.execute_cmd("@script TestChar = examples.bodyfunctions.BodyFunctions", "Script successfully added") # Comms commands class TestChannelCreate(CommandTest): def test_call(self): self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel") self.execute_cmd("testchan1 Hello", "[testchannel1] TestChar: Hello") class TestAddCom(CommandTest): def test_call(self): self.execute_cmd("@cdestroy testchannel1", "Channel 'testchannel1'") self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel") self.execute_cmd("addcom chan1 = testchannel1") self.execute_cmd("addcom chan2 = testchan1") self.execute_cmd("delcom testchannel1") self.execute_cmd("addcom testchannel1" "You now listen to the channel channel.") class TestDelCom(CommandTest): def test_call(self): self.execute_cmd("@cdestroy testchannel1", "Channel 'testchannel1'") self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel") self.execute_cmd("addcom chan1 = testchan1") self.execute_cmd("addcom chan2 = testchan1b") self.execute_cmd("addcom chan3 = testchannel1") self.execute_cmd("delcom chan1", "Your alias 'chan1' for ") self.execute_cmd("delcom chan2", "Your alias 'chan2' for ") self.execute_cmd("delcom testchannel1" "You stop listening to") class TestAllCom(CommandTest): def test_call(self): self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel") self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel") self.execute_cmd("allcom off") self.execute_cmd("allcom on") self.execute_cmd("allcom destroy") class TestChannels(CommandTest): def test_call(self): self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel") self.execute_cmd("@cdestroy testchannel1", "Channel 'testchannel1'") class TestCBoot(CommandTest): def test_call(self): self.execute_cmd("@cdestroy testchannel1", "Channel 'testchannel1'") self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel") self.execute_cmd("addcom testchan = testchannel1") self.execute_cmd("@cboot testchannel1 = TestChar", "TestChar boots TestChar from channel.") class TestCemit(CommandTest): def test_call(self): self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel") self.execute_cmd("@cemit testchan1 = Testing!", "[testchannel1] Testing!") class TestCwho(CommandTest): def test_call(self): self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel") self.execute_cmd("@cwho testchan1b", "Channel subscriptions") # OOC commands #class TestOOC_and_IC(CommandTest): # can't be tested it seems, causes errors in other commands (?) # def test_call(self): # self.execute_cmd("@ooc", "\nYou go OOC.") # self.execute_cmd("@ic", "\nYou become TestChar") # Unloggedin commands # these cannot be tested from here.
Python
""" The help command. The basic idea is that help texts for commands are best written by those that write the commands - the admins. So command-help is all auto-loaded and searched from the current command set. The normal, database-tied help system is used for collaborative creation of other help topics such as RP help or game-world aides. """ from src.utils.utils import fill, dedent from src.commands.command import Command from src.help.models import HelpEntry from src.utils import create from src.commands.default.muxcommand import MuxCommand LIST_ARGS = ["list", "all"] SEP = "{C" + "-"*78 + "{n" def format_help_entry(title, help_text, aliases=None, suggested=None): """ This visually formats the help entry. """ string = SEP + "\n" if title: string += "{CHelp topic for {w%s{n" % (title.capitalize()) if aliases: string += " {C(aliases: {w%s{n{C){n" % (", ".join(aliases)) if help_text: string += "\n%s" % dedent(help_text.rstrip()) if suggested: string += "\n\n{CSuggested:{n " string += "{w%s{n" % fill(", ".join(suggested)) string.strip() string += "\n" + SEP return string def format_help_list(hdict_cmds, hdict_db): """ Output a category-ordered list. """ string = "" if hdict_cmds and hdict_cmds.values(): string += "\n" + SEP + "\n {CCommand help entries{n\n" + SEP for category in sorted(hdict_cmds.keys()): string += "\n {w%s{n:\n" % (str(category).capitalize()) string += "{G" + fill(", ".join(sorted(hdict_cmds[category]))) + "{n" if hdict_db and hdict_db.values(): string += "\n\n" + SEP + "\n\r {COther help entries{n\n" + SEP for category in sorted(hdict_db.keys()): string += "\n\r {w%s{n:\n" % (str(category).capitalize()) string += "{G" + fill(", ".join(sorted([str(topic) for topic in hdict_db[category]]))) + "{n" return string class CmdHelp(Command): """ The main help command Usage: help <topic or command> help list help all This will search for help on commands and other topics related to the game. """ key = "help" locks = "cmd:all()" # this is a special cmdhandler flag that makes the cmdhandler also pack # the current cmdset with the call to self.func(). return_cmdset = True def parse(self): """ input is a string containing the command or topic to match. """ self.original_args = self.args.strip() self.args = self.args.strip().lower() def func(self): """ Run the dynamic help entry creator. """ query, cmdset = self.args, self.cmdset caller = self.caller if not query: query = "all" # removing doublets in cmdset, caused by cmdhandler # having to allow doublet commands to manage exits etc. cmdset.make_unique(caller) # Listing help entries if query in LIST_ARGS: # we want to list all available help entries hdict_cmd = {} for cmd in (cmd for cmd in cmdset if cmd.access(caller) if not cmd.key.startswith('__') and not (hasattr(cmd, 'is_exit') and cmd.is_exit)): if hdict_cmd.has_key(cmd.help_category): hdict_cmd[cmd.help_category].append(cmd.key) else: hdict_cmd[cmd.help_category] = [cmd.key] hdict_db = {} for topic in (topic for topic in HelpEntry.objects.get_all_topics() if topic.access(caller, 'view', default=True)): if hdict_db.has_key(topic.help_category): hdict_db[topic.help_category].append(topic.key) else: hdict_db[topic.help_category] = [topic.key] help_entry = format_help_list(hdict_cmd, hdict_db) caller.msg(help_entry) return # Look for a particular help entry # Cmd auto-help dynamic entries cmdmatches = [cmd for cmd in cmdset if query in cmd and cmd.access(caller)] if len(cmdmatches) > 1: # multiple matches. Try to limit it down to exact match exactmatches = [cmd for cmd in cmdmatches if cmd == query] if exactmatches: cmdmatches = exactmatches # Help-database static entries dbmatches = \ [topic for topic in HelpEntry.objects.find_topicmatch(query, exact=False) if topic.access(caller, 'view', default=True)] if len(dbmatches) > 1: exactmatches = \ [topic for topic in HelpEntry.objects.find_topicmatch(query, exact=True) if topic.access(caller, 'view', default=True)] if exactmatches: dbmatches = exactmatches # Handle result if (not cmdmatches) and (not dbmatches): # no normal match. Check if this is a category match instead categ_cmdmatches = [cmd.key for cmd in cmdset if query == cmd.help_category and cmd.access(caller)] categ_dbmatches = \ [topic.key for topic in HelpEntry.objects.find_topics_with_category(query) if topic.access(caller, 'view', default=True)] cmddict = None dbdict = None if categ_cmdmatches: cmddict = {query:categ_cmdmatches} if categ_dbmatches: dbdict = {query:categ_dbmatches} if cmddict or dbdict: help_entry = format_help_list(cmddict, dbdict) else: help_entry = "No help entry found for '%s'" % self.original_args elif len(cmdmatches) == 1: # we matched against a command name or alias. Show its help entry. suggested = [] if dbmatches: suggested = [entry.key for entry in dbmatches] cmd = cmdmatches[0] help_entry = format_help_entry(cmd.key, cmd.__doc__, aliases=cmd.aliases, suggested=suggested) elif len(dbmatches) == 1: # matched against a database entry entry = dbmatches[0] help_entry = format_help_entry(entry.key, entry.entrytext) else: # multiple matches of either type cmdalts = [cmd.key for cmd in cmdmatches] dbalts = [entry.key for entry in dbmatches] helptext = "Multiple help entries match your search ..." help_entry = format_help_entry("", helptext, None, cmdalts + dbalts) # send result to user caller.msg(help_entry) class CmdSetHelp(MuxCommand): """ @help - edit the help database Usage: @help[/switches] <topic>[,category[,locks]] = <text> Switches: add - add or replace a new topic with text. append - add text to the end of topic with a newline between. merge - As append, but don't add a newline between the old text and the appended text. delete - remove help topic. force - (used with add) create help topic also if the topic already exists. Examples: @sethelp/add throw = This throws something at ... @sethelp/append pickpocketing,Thievery,is_thief, is_staff) = This steals ... @sethelp/append pickpocketing, ,is_thief, is_staff) = This steals ... """ key = "@help" aliases = "@sethelp" locks = "cmd:perm(PlayerHelpers)" help_category = "Building" def func(self): "Implement the function" caller = self.caller switches = self.switches lhslist = self.lhslist rhs = self.rhs if not self.args: caller.msg("Usage: @sethelp/[add|del|append|merge] <topic>[,category[,locks,..] = <text>]") return topicstr = "" category = "" lockstring = "" try: topicstr = lhslist[0] category = lhslist[1] lockstring = ",".join(lhslist[2:]) except Exception: pass if not topicstr: caller.msg("You have to define a topic!") return string = "" #print topicstr, category, lockstring if switches and switches[0] in ('append', 'app','merge'): # add text to the end of a help topic # find the topic to append to old_entry = HelpEntry.objects.filter(db_key__iexact=topicstr) if not old_entry: string = "Could not find topic '%s'. You must give an exact name." % topicstr else: old_entry = old_entry[0] entrytext = old_entry.entrytext if switches[0] == 'merge': old_entry.entrytext = "%s %s" % (entrytext, self.rhs) string = "Added the new text right after the old one (merge)." else: old_entry.entrytext = "%s\n\n%s" % (entrytext, self.rhs) string = "Added the new text as a new paragraph after the old one (append)" old_entry.save() elif switches and switches[0] in ('delete','del'): #delete a help entry old_entry = HelpEntry.objects.filter(db_key__iexact=topicstr) if not old_entry: string = "Could not find topic '%s'." % topicstr else: old_entry[0].delete() string = "Deleted the help entry '%s'." % topicstr else: # add a new help entry. force_create = ('for' in switches) or ('force' in switches) old_entry = None try: old_entry = HelpEntry.objects.get(key=topicstr) except Exception: pass if old_entry: if force_create: old_entry.key = topicstr old_entry.entrytext = self.rhs old_entry.help_category = category old_entry.locks.clear() old_entry.locks.add(lockstring) old_entry.save() string = "Overwrote the old topic '%s' with a new one." % topicstr else: string = "Topic '%s' already exists. Use /force to overwrite it." % topicstr else: # no old entry. Create a new one. new_entry = create.create_help_entry(topicstr, rhs, category, lockstring) if new_entry: string = "Topic '%s' was successfully created." % topicstr else: string = "Error when creating topic '%s'! Maybe it already exists?" % topicstr # give feedback caller.msg(string)
Python
""" System commands """ import traceback import os, datetime, time import django, twisted from django.contrib.auth.models import User from django.conf import settings from src.server.sessionhandler import SESSIONS from src.scripts.models import ScriptDB from src.objects.models import ObjectDB from src.players.models import PlayerDB from src.server.models import ServerConfig from src.utils import create, logger, utils, gametime from src.commands.default.muxcommand import MuxCommand class CmdReload(MuxCommand): """ Reload the system Usage: @reload This restarts the server. The Portal is not affected. Non-persistent scripts will survive a @reload (use @reset to purge) and at_reload() hooks will be called. """ key = "@reload" locks = "cmd:perm(reload) or perm(Immortals)" help_category = "System" def func(self): """ Reload the system. """ SESSIONS.announce_all(" Server restarting ...") SESSIONS.server.shutdown(mode='reload') class CmdReset(MuxCommand): """ Reset and reboot the system Usage: @reset A cold reboot. This works like a mixture of @reload and @shutdown, - all shutdown hooks will be called and non-persistent scrips will be purged. But the Portal will not be affected and the server will automatically restart again. """ key = "@reset" aliases = ['@reboot'] locks = "cmd:perm(reload) or perm(Immortals)" help_category = "System" def func(self): """ Reload the system. """ SESSIONS.announce_all(" Server restarting ...") SESSIONS.server.shutdown(mode='reset') class CmdShutdown(MuxCommand): """ @shutdown Usage: @shutdown [announcement] Gracefully shut down both Server and Portal. """ key = "@shutdown" locks = "cmd:perm(shutdown) or perm(Immortals)" help_category = "System" def func(self): "Define function" try: session = self.caller.sessions[0] except Exception: return self.caller.msg('Shutting down server ...') announcement = "\nServer is being SHUT DOWN!\n" if self.args: announcement += "%s\n" % self.args logger.log_infomsg('Server shutdown by %s.' % self.caller.name) SESSIONS.announce_all(announcement) SESSIONS.portal_shutdown() SESSIONS.server.shutdown(mode='shutdown') class CmdPy(MuxCommand): """ Execute a snippet of python code Usage: @py <cmd> Separate multiple commands by ';'. A few variables are made available for convenience in order to offer access to the system (you can import more at execution time). Available variables in @py environment: self, me : caller here : caller.location obj : dummy obj instance script : dummy script instance config : dummy conf instance ObjectDB : ObjectDB class ScriptDB : ScriptDB class ServerConfig : ServerConfig class inherits_from(obj, parent) : check object inheritance {rNote: In the wrong hands this command is a severe security risk. It should only be accessible by trusted server admins/superusers.{n """ key = "@py" aliases = ["!"] locks = "cmd:perm(py) or perm(Immortals)" help_category = "System" def func(self): "hook function" caller = self.caller pycode = self.args if not pycode: string = "Usage: @py <code>" caller.msg(string) return # create temporary test objects for playing with script = create.create_script("src.scripts.scripts.DoNothing", key='testscript') obj = create.create_object("src.objects.objects.Object", key='testobject') conf = ServerConfig() # used to access conf values # import useful checker available_vars = {'self':caller, 'me':caller, 'here':caller.location, 'obj':obj, 'script':script, 'config':conf, 'inherits_from':utils.inherits_from, 'ObjectDB':ObjectDB, 'ScriptDB':ScriptDB, 'ServerConfig':ServerConfig} caller.msg(">>> %s" % pycode) try: ret = eval(pycode, {}, available_vars) ret = "<<< %s" % str(ret) except Exception: try: exec(pycode, {}, available_vars) ret = "<<< Done." except Exception: errlist = traceback.format_exc().split('\n') if len(errlist) > 4: errlist = errlist[4:] ret = "\n".join("<<< %s" % line for line in errlist if line) caller.msg(ret) obj.delete() try: script.delete() except AssertionError: # this is a strange thing; the script looses its id somehow..? pass # helper function. Kept outside so it can be imported and run # by other commands. def format_script_list(scripts): "Takes a list of scripts and formats the output." if not scripts: return "<No scripts>" table = [["id"], ["obj"], ["key"], ["intval"], ["next"], ["rept"], ["db"], ["typeclass"], ["desc"]] for script in scripts: table[0].append(script.id) if not hasattr(script, 'obj') or not script.obj: table[1].append("<Global>") else: table[1].append(script.obj.key) table[2].append(script.key) if not hasattr(script, 'interval') or script.interval < 0: table[3].append("--") else: table[3].append("%ss" % script.interval) next = script.time_until_next_repeat() if not next: table[4].append("--") else: table[4].append("%ss" % next) if not hasattr(script, 'repeats') or not script.repeats: table[5].append("--") else: table[5].append("%s" % script.repeats) if script.persistent: table[6].append("*") else: table[6].append("-") typeclass_path = script.typeclass_path.rsplit('.', 1) table[7].append("%s" % typeclass_path[-1]) table[8].append(script.desc) ftable = utils.format_table(table) string = "" for irow, row in enumerate(ftable): if irow == 0: srow = "\n" + "".join(row) srow = "{w%s{n" % srow.rstrip() else: srow = "\n" + "{w%s{n" % row[0] + "".join(row[1:]) string += srow.rstrip() return string.strip() class CmdScripts(MuxCommand): """ Operate on scripts. Usage: @scripts[/switches] [<obj or scriptid>] Switches: stop - stops an existing script kill - kills a script - without running its cleanup hooks validate - run a validation on the script(s) If no switches are given, this command just views all active scripts. The argument can be either an object, at which point it will be searched for all scripts defined on it, or an script name or dbref. For using the /stop switch, a unique script dbref is required since whole classes of scripts often have the same name. """ key = "@scripts" aliases = "@listscripts" locks = "cmd:perm(listscripts) or perm(Wizards)" help_category = "System" def func(self): "implement method" caller = self.caller args = self.args string = "" if args: # test first if this is a script match scripts = ScriptDB.objects.get_all_scripts(key=args) if not scripts: # try to find an object instead. objects = ObjectDB.objects.object_search(args, caller=caller, global_search=True) if objects: scripts = [] for obj in objects: # get all scripts on the object(s) scripts.extend(ScriptDB.objects.get_all_scripts_on_obj(obj)) else: # we want all scripts. scripts = ScriptDB.objects.get_all_scripts() if not scripts: string = "No scripts found with a key '%s', or on an object named '%s'." % (args, args) caller.msg(string) return if self.switches and self.switches[0] in ('stop', 'del', 'delete', 'kill'): # we want to delete something if not scripts: string = "No scripts/objects matching '%s'. " % args string += "Be more specific." elif len(scripts) == 1: # we have a unique match! if 'kill' in self.switches: string = "Killing script '%s'" % scripts[0].key scripts[0].stop(kill=True) else: string = "Stopping script '%s'." % scripts[0].key scripts[0].stop() #import pdb #pdb.set_trace() ScriptDB.objects.validate() #just to be sure all is synced else: # multiple matches. string = "Multiple script matches. Please refine your search:\n" string += format_script_list(scripts) elif self.switches and self.switches[0] in ("validate", "valid", "val"): # run validation on all found scripts nr_started, nr_stopped = ScriptDB.objects.validate(scripts=scripts) string = "Validated %s scripts. " % ScriptDB.objects.all().count() string += "Started %s and stopped %s scripts." % (nr_started, nr_stopped) else: # No stopping or validation. We just want to view things. string = format_script_list(scripts) caller.msg(string) class CmdObjects(MuxCommand): """ Give a summary of object types in database Usage: @objects [<nr>] Gives statictics on objects in database as well as a list of <nr> latest objects in database. If not given, <nr> defaults to 10. """ key = "@objects" aliases = ["@listobjects", "@listobjs", '@stats', '@db'] locks = "cmd:perm(listobjects) or perm(Builders)" help_category = "System" def func(self): "Implement the command" caller = self.caller if self.args and self.args.isdigit(): nlim = int(self.args) else: nlim = 10 string = "\n{wDatabase totals:{n" nplayers = PlayerDB.objects.count() nobjs = ObjectDB.objects.count() base_char_typeclass = settings.BASE_CHARACTER_TYPECLASS nchars = ObjectDB.objects.filter(db_typeclass_path=base_char_typeclass).count() nrooms = ObjectDB.objects.filter(db_location__isnull=True).exclude(db_typeclass_path=base_char_typeclass).count() nexits = ObjectDB.objects.filter(db_location__isnull=False, db_destination__isnull=False).count() string += "\n{wPlayers:{n %i" % nplayers string += "\n{wObjects:{n %i" % nobjs string += "\n{w Characters (BASE_CHARACTER_TYPECLASS):{n %i" % nchars string += "\n{w Rooms (location==None):{n %i" % nrooms string += "\n{w Exits (destination!=None):{n %i" % nexits string += "\n{w Other:{n %i\n" % (nobjs - nchars - nrooms - nexits) dbtotals = ObjectDB.objects.object_totals() table = [["Count"], ["Typeclass"]] for path, count in dbtotals.items(): table[0].append(count) table[1].append(path) ftable = utils.format_table(table, 3) for irow, row in enumerate(ftable): srow = "\n" + "".join(row) srow = srow.rstrip() if irow == 0: srow = "{w%s{n" % srow string += srow string += "\n\n{wLast %s Objects created:{n" % min(nobjs, nlim) objs = ObjectDB.objects.all().order_by("db_date_created")[max(0, nobjs - nlim):] table = [["Created"], ["dbref"], ["name"], ["typeclass"]] for i, obj in enumerate(objs): table[0].append(utils.datetime_format(obj.date_created)) table[1].append(obj.dbref) table[2].append(obj.key) table[3].append(str(obj.typeclass.path)) ftable = utils.format_table(table, 5) for irow, row in enumerate(ftable): srow = "\n" + "".join(row) srow = srow.rstrip() if irow == 0: srow = "{w%s{n" % srow string += srow caller.msg(string) class CmdService(MuxCommand): """ @service - manage services Usage: @service[/switch] <service> Switches: list - shows all available services (default) start - activates a service stop - stops a service Service management system. Allows for the listing, starting, and stopping of services. If no switches are given, services will be listed. """ key = "@service" aliases = ["@services"] locks = "cmd:perm(service) or perm(Immortals)" help_category = "System" def func(self): "Implement command" caller = self.caller switches = self.switches if switches and switches[0] not in ["list", "start", "stop"]: caller.msg("Usage: @service/<start|stop|list> [service]") return # get all services sessions = caller.sessions if not sessions: return service_collection = SESSIONS.server.services if not switches or switches[0] == "list": # Just display the list of installed services and their # status, then exit. string = "-" * 78 string += "\n{wServices{n (use @services/start|stop):" for service in service_collection.services: if service.running: status = 'Running' string += '\n * {g%s{n (%s)' % (service.name, status) else: status = 'Inactive' string += '\n {R%s{n (%s)' % (service.name, status) string += "\n" + "-" * 78 caller.msg(string) return # Get the service to start / stop try: service = service_collection.getServiceNamed(self.args) except Exception: string = 'Invalid service name. This command is case-sensitive. ' string += 'See @service/list for valid services.' caller.msg(string) return if switches[0] == "stop": # Stopping a service gracefully closes it and disconnects # any connections (if applicable). if not service.running: caller.msg('That service is not currently running.') return if service.name[:7] == 'Evennia': string = "You seem to be shutting down a core Evennia* service. Note that" string += "Stopping some TCP port services will *not* disconnect users *already*" string += "connected on those ports, but *may* instead cause spurious errors for them. To " string += "safely and permanently remove ports, change settings file and restart the server." caller.msg(string) service.stopService() caller.msg("Stopping service '%s'." % self.args) return if switches[0] == "start": #Starts a service. if service.running: caller.msg('That service is already running.') return caller.msg("Starting service '%s'." % self.args) service.startService() class CmdVersion(MuxCommand): """ @version - game version Usage: @version Display the game version info. """ key = "@version" help_category = "System" def func(self): "Show the version" version = utils.get_evennia_version() string = "-" * 50 + "\n\r" string += " {cEvennia{n %s\n\r" % version string += " (Django %s, " % (django.get_version()) string += " Twisted %s)\n\r" % (twisted.version.short()) string += "-" * 50 self.caller.msg(string) class CmdTime(MuxCommand): """ @time Usage: @time Server local time. """ key = "@time" aliases = "@uptime" locks = "cmd:perm(time) or perm(Players)" help_category = "System" def func(self): "Show times." table = [["Current server uptime:", "Total server running time:", "Total in-game time (realtime x %g):" % (gametime.TIMEFACTOR), "Server time stamp:" ], [utils.time_format(time.time() - SESSIONS.server.start_time, 3), utils.time_format(gametime.runtime(format=False), 2), utils.time_format(gametime.gametime(format=False), 2), datetime.datetime.now() ]] if utils.host_os_is('posix'): loadavg = os.getloadavg() table[0].append("Server load (per minute):") table[1].append("%g" % (loadavg[0])) stable = [] for col in table: stable.append([str(val).strip() for val in col]) ftable = utils.format_table(stable, 5) string = "" for row in ftable: string += "\n " + "{w%s{n" % row[0] + "".join(row[1:]) self.caller.msg(string) class CmdServerLoad(MuxCommand): """ server load statistics Usage: @serverload Show server load statistics in a table. """ key = "@serverload" locks = "cmd:perm(list) or perm(Immortals)" help_category = "System" def func(self): "Show list." caller = self.caller # display active processes if not utils.host_os_is('posix'): string = "Process listings are only available under Linux/Unix." else: import resource loadavg = os.getloadavg() psize = resource.getpagesize() pid = os.getpid() rmem = float(os.popen('ps -p %d -o %s | tail -1' % (pid, "rss")).read()) / 1024.0 vmem = float(os.popen('ps -p %d -o %s | tail -1' % (pid, "vsz")).read()) / 1024.0 rusage = resource.getrusage(resource.RUSAGE_SELF) table = [["Server load (1 min):", "Process ID:", "Bytes per page:", "CPU time used:", "Resident memory:", "Virtual memory:", "Page faults:", "Disk I/O:", "Network I/O:", "Context switching:" ], ["%g" % loadavg[0], "%10d" % pid, "%10d " % psize, "%s (%gs)" % (utils.time_format(rusage.ru_utime), rusage.ru_utime), #"%10d shared" % rusage.ru_ixrss, #"%10d pages" % rusage.ru_maxrss, "%10d Mb" % rmem, "%10d Mb" % vmem, "%10d hard" % rusage.ru_majflt, "%10d reads" % rusage.ru_inblock, "%10d in" % rusage.ru_msgrcv, "%10d vol" % rusage.ru_nvcsw ], ["", "", "", "(user: %gs)" % rusage.ru_stime, "", #"%10d private" % rusage.ru_idrss, "", #"%10d bytes" % (rusage.ru_maxrss * psize), "%10d soft" % rusage.ru_minflt, "%10d writes" % rusage.ru_oublock, "%10d out" % rusage.ru_msgsnd, "%10d forced" % rusage.ru_nivcsw ], ["", "", "", "", "", #"%10d stack" % rusage.ru_isrss, "", "%10d swapouts" % rusage.ru_nswap, "", "", "%10d sigs" % rusage.ru_nsignals ] ] stable = [] for col in table: stable.append([str(val).strip() for val in col]) ftable = utils.format_table(stable, 5) string = "" for row in ftable: string += "\n " + "{w%s{n" % row[0] + "".join(row[1:]) caller.msg(string) class CmdPs(MuxCommand): """ list processes Usage @ps Shows the process/event table. """ key = "@ps" locks = "cmd:perm(ps) or perm(Builders)" help_category = "System" def func(self): "run the function." all_scripts = ScriptDB.objects.get_all_scripts() repeat_scripts = [script for script in all_scripts if script.interval > 0] nrepeat_scripts = [script for script in all_scripts if script.interval <= 0] string = "\n{wNon-timed scripts:{n -- PID name desc --" if not nrepeat_scripts: string += "\n <None>" for script in nrepeat_scripts: string += "\n {w%i{n %s %s" % (script.id, script.key, script.desc) string += "\n{wTimed scripts:{n -- PID name [time/interval][repeats] desc --" if not repeat_scripts: string += "\n <None>" for script in repeat_scripts: repeats = "[inf] " if script.repeats: repeats = "[%i] " % script.repeats time_next = "[inf/inf]" if script.time_until_next_repeat() != None: time_next = "[%d/%d]" % (script.time_until_next_repeat(), script.interval) string += "\n {w%i{n %s %s%s%s" % (script.id, script.key, time_next, repeats, script.desc) string += "\n{wTotal{n: %d scripts." % len(all_scripts) self.caller.msg(string)
Python
""" Generic command module. Pretty much every command should go here for now. """ import time from django.conf import settings from src.server.sessionhandler import SESSIONS from src.utils import utils from src.objects.models import ObjectNick as Nick from src.commands.default.muxcommand import MuxCommand AT_SEARCH_RESULT = utils.mod_import(*settings.SEARCH_AT_RESULT.rsplit('.', 1)) BASE_PLAYER_TYPECLASS = settings.BASE_PLAYER_TYPECLASS class CmdHome(MuxCommand): """ home Usage: home Teleports the player to their home. """ key = "home" locks = "cmd:perm(home) or perm(Builders)" def func(self): "Implement the command" caller = self.caller home = caller.home if not home: caller.msg("You have no home set.") else: caller.move_to(home) caller.msg("There's no place like home ...") class CmdLook(MuxCommand): """ look Usage: look look <obj> look *<player> Observes your location or objects in your vicinity. """ key = "look" aliases = ["l", "ls"] locks = "cmd:all()" def func(self): """ Handle the looking. """ caller = self.caller args = self.args if args: # Use search to handle duplicate/nonexistant results. looking_at_obj = caller.search(args, use_nicks=True) if not looking_at_obj: return else: looking_at_obj = caller.location if not looking_at_obj: caller.msg("You have no location to look at!") return if not hasattr(looking_at_obj, 'return_appearance'): # this is likely due to us having a player instead looking_at_obj = looking_at_obj.character if not looking_at_obj.access(caller, "view"): caller.msg("Could not find '%s'." % args) return # get object's appearance caller.msg(looking_at_obj.return_appearance(caller)) # the object's at_desc() method. looking_at_obj.at_desc(looker=caller) class CmdPassword(MuxCommand): """ @password - set your password Usage: @password <old password> = <new password> Changes your password. Make sure to pick a safe one. """ key = "@password" locks = "cmd:all()" def func(self): "hook function." caller = self.caller if hasattr(caller, "player"): caller = caller.player if not self.rhs: caller.msg("Usage: @password <oldpass> = <newpass>") return oldpass = self.lhslist[0] # this is already stripped by parse() newpass = self.rhslist[0] # '' try: uaccount = caller.user except AttributeError: caller.msg("This is only applicable for players.") return if not uaccount.check_password(oldpass): caller.msg("The specified old password isn't correct.") elif len(newpass) < 3: caller.msg("Passwords must be at least three characters long.") else: uaccount.set_password(newpass) uaccount.save() caller.msg("Password changed.") class CmdNick(MuxCommand): """ Define a personal alias/nick Usage: nick[/switches] <nickname> = [<string>] alias '' Switches: object - alias an object player - alias a player clearall - clear all your aliases list - show all defined aliases If no switch is given, a command alias is created, used to replace strings before sending the command. Give an empty right-hand side to clear the nick Creates a personal nick for some in-game object or string. When you enter that string, it will be replaced with the alternate string. The switches dictate in what situations the nick is checked and substituted. If string is None, the alias (if it exists) will be cleared. Obs - no objects are actually changed with this command, if you want to change the inherent aliases of an object, use the @alias command instead. """ key = "nick" aliases = ["nickname", "nicks", "@nick", "alias"] locks = "cmd:all()" def func(self): "Create the nickname" caller = self.caller switches = self.switches nicks = Nick.objects.filter(db_obj=caller.dbobj).exclude(db_type="channel") if 'list' in switches or self.cmdstring == "nicks": string = "{wDefined Nicks:{n" cols = [["Type"],["Nickname"],["Translates-to"] ] for nick in nicks: cols[0].append(nick.db_type) cols[1].append(nick.db_nick) cols[2].append(nick.db_real) for ir, row in enumerate(utils.format_table(cols)): if ir == 0: string += "\n{w" + "".join(row) + "{n" else: string += "\n" + "".join(row) caller.msg(string) return if 'clearall' in switches: nicks.delete() caller.msg("Cleared all aliases.") return if not self.args or not self.lhs: caller.msg("Usage: nick[/switches] nickname = [realname]") return nick = self.lhs real = self.rhs if real == nick: caller.msg("No point in setting nick same as the string to replace...") return # check so we have a suitable nick type if not any(True for switch in switches if switch in ("object", "player", "inputline")): switches = ["inputline"] string = "" for switch in switches: oldnick = Nick.objects.filter(db_obj=caller.dbobj, db_nick__iexact=nick, db_type__iexact=switch) if not real: # removal of nick if oldnick: # clear the alias string += "\nNick '%s' (= '%s') was cleared." % (nick, oldnick[0].db_real) caller.nicks.delete(nick, nick_type=switch) else: string += "\nNo nick '%s' found, so it could not be removed." % nick else: # creating new nick if oldnick: string += "\nNick %s changed from '%s' to '%s'." % (nick, oldnick[0].db_real, real) else: string += "\nNick set: '%s' = '%s'." % (nick, real) caller.nicks.add(nick, real, nick_type=switch) caller.msg(string) class CmdInventory(MuxCommand): """ inventory Usage: inventory inv Shows a player's inventory. """ key = "inventory" aliases = ["inv", "i"] locks = "cmd:all()" def func(self): "check inventory" items = self.caller.contents if not items: string = "You are not carrying anything." else: # format item list into nice collumns cols = [[],[]] for item in items: cols[0].append(item.name) desc = item.db.desc if not desc: desc = "" cols[1].append(utils.crop(str(desc))) # auto-format the columns to make them evenly wide ftable = utils.format_table(cols) string = "You are carrying:" for row in ftable: string += "\n " + "{C%s{n - %s" % (row[0], row[1]) self.caller.msg(string) class CmdGet(MuxCommand): """ get Usage: get <obj> Picks up an object from your location and puts it in your inventory. """ key = "get" aliases = "grab" locks = "cmd:all()" def func(self): "implements the command." caller = self.caller if not self.args: caller.msg("Get what?") return obj = caller.search(self.args) if not obj: return if caller == obj: caller.msg("You can't get yourself.") return if obj.location == caller: caller.msg("You already hold that.") return if not obj.access(caller, 'get'): if obj.db.get_err_msg: caller.msg(obj.db.get_err_msg) else: caller.msg("You can't get that.") return obj.move_to(caller, quiet=True) caller.msg("You pick up %s." % obj.name) caller.location.msg_contents("%s picks up %s." % (caller.name, obj.name), exclude=caller) # calling hook method obj.at_get(caller) class CmdDrop(MuxCommand): """ drop Usage: drop <obj> Lets you drop an object from your inventory into the location you are currently in. """ key = "drop" locks = "cmd:all()" def func(self): "Implement command" caller = self.caller if not self.args: caller.msg("Drop what?") return results = caller.search(self.args, ignore_errors=True) # we process the results ourselves since we want to sift out only # those in our inventory. results = [obj for obj in results if obj in caller.contents] # now we send it into the handler. obj = AT_SEARCH_RESULT(caller, self.args, results, False) if not obj: return obj.move_to(caller.location, quiet=True) caller.msg("You drop %s." % (obj.name,)) caller.location.msg_contents("%s drops %s." % (caller.name, obj.name), exclude=caller) # Call the object script's at_drop() method. obj.at_drop(caller) class CmdQuit(MuxCommand): """ quit Usage: @quit Gracefully disconnect from the game. """ key = "@quit" locks = "cmd:all()" def func(self): "hook function" for session in self.caller.sessions: session.msg("{RQuitting{n. Hope to see you soon again.") session.session_disconnect() class CmdWho(MuxCommand): """ who Usage: who doing Shows who is currently online. Doing is an alias that limits info also for those with all permissions. """ key = "who" aliases = "doing" locks = "cmd:all()" def func(self): """ Get all connected players by polling session. """ caller = self.caller session_list = SESSIONS.get_sessions() if self.cmdstring == "doing": show_session_data = False else: show_session_data = caller.check_permstring("Immortals") or caller.check_permstring("Wizards") if show_session_data: table = [["Player Name"], ["On for"], ["Idle"], ["Room"], ["Cmds"], ["Host"]] else: table = [["Player Name"], ["On for"], ["Idle"]] for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time plr_pobject = session.get_character() if not plr_pobject: plr_pobject = session.get_player() show_session_data = False table = [["Player Name"], ["On for"], ["Idle"]] if show_session_data: table[0].append(plr_pobject.name[:25]) table[1].append(utils.time_format(delta_conn, 0)) table[2].append(utils.time_format(delta_cmd, 1)) table[3].append(plr_pobject.location.id) table[4].append(session.cmd_total) table[5].append(session.address[0]) else: table[0].append(plr_pobject.name[:25]) table[1].append(utils.time_format(delta_conn,0)) table[2].append(utils.time_format(delta_cmd,1)) stable = [] for row in table: # prettify values stable.append([str(val).strip() for val in row]) ftable = utils.format_table(stable, 5) string = "" for ir, row in enumerate(ftable): if ir == 0: string += "\n" + "{w%s{n" % ("".join(row)) else: string += "\n" + "".join(row) nplayers = (SESSIONS.player_count()) if nplayers == 1: string += '\nOne player logged in.' else: string += '\n%d players logged in.' % nplayers caller.msg(string) class CmdSay(MuxCommand): """ say Usage: say <message> Talk to those in your current location. """ key = "say" aliases = ['"'] locks = "cmd:all()" def func(self): "Run the say command" caller = self.caller if not self.args: caller.msg("Say what?") return speech = self.args # calling the speech hook on the location speech = caller.location.at_say(caller, speech) # Feedback for the object doing the talking. caller.msg('You say, "%s{n"' % speech) # Build the string to emit to neighbors. emit_string = '{c%s{n says, "%s{n"' % (caller.name, speech) caller.location.msg_contents(emit_string, exclude=caller) class CmdPose(MuxCommand): """ pose - strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an script being taken. The pose text will automatically begin with your name. """ key = "pose" aliases = [":", "emote"] locks = "cmd:all()" def parse(self): """ Custom parse the cases where the emote starts with some special letter, such as 's, at which we don't want to separate the caller's name and the emote with a space. """ args = self.args if args and not args[0] in ["'", ",", ":"]: args = " %s" % args.strip() self.args = args def func(self): "Hook function" if not self.args: msg = "Do what?" else: msg = "%s%s" % (self.caller.name, self.args) self.caller.location.msg_contents(msg) class CmdEncoding(MuxCommand): """ encoding - set a custom text encoding Usage: @encoding/switches [<encoding>] Switches: clear - clear your custom encoding This sets the text encoding for communicating with Evennia. This is mostly an issue only if you want to use non-ASCII characters (i.e. letters/symbols not found in English). If you see that your characters look strange (or you get encoding errors), you should use this command to set the server encoding to be the same used in your client program. Common encodings are utf-8 (default), latin-1, ISO-8859-1 etc. If you don't submit an encoding, the current encoding will be displayed instead. """ key = "@encoding" aliases = "@encode" locks = "cmd:all()" def func(self): """ Sets the encoding. """ caller = self.caller if hasattr(caller, 'player'): caller = caller.player if 'clear' in self.switches: # remove customization old_encoding = caller.db.encoding if old_encoding: string = "Your custom text encoding ('%s') was cleared." % old_encoding else: string = "No custom encoding was set." del caller.db.encoding elif not self.args: # just list the encodings supported pencoding = caller.db.encoding string = "" if pencoding: string += "Default encoding: {g%s{n (change with {w@encoding <encoding>{n)" % pencoding encodings = settings.ENCODINGS if encodings: string += "\nServer's alternative encodings (tested in this order):\n {g%s{n" % ", ".join(encodings) if not string: string = "No encodings found." else: # change encoding old_encoding = caller.db.encoding encoding = self.args caller.db.encoding = encoding string = "Your custom text encoding was changed from '%s' to '%s'." % (old_encoding, encoding) caller.msg(string.strip()) class CmdAccess(MuxCommand): """ access - show access groups Usage: access This command shows you the permission hierarchy and which permission groups you are a member of. """ key = "access" aliases = ["groups", "hierarchy"] locks = "cmd:all()" def func(self): "Load the permission groups" caller = self.caller hierarchy_full = settings.PERMISSION_HIERARCHY string = "\n{wPermission Hierarchy{n (climbing):\n %s" % ", ".join(hierarchy_full) hierarchy = [p.lower() for p in hierarchy_full] if self.caller.player.is_superuser: cperms = "<Superuser>" pperms = "<Superuser>" else: cperms = ", ".join(caller.permissions) pperms = ", ".join(caller.player.permissions) string += "\n{wYour access{n:" string += "\nCharacter {c%s{n: %s" % (caller.key, cperms) if hasattr(caller, 'player'): string += "\nPlayer {c%s{n: %s" % (caller.player.key, pperms) caller.msg(string) # OOC commands class CmdOOCLook(CmdLook): """ ooc look Usage: look 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 we are controlling a character, pass control over to normal look. """ key = "look" aliases = ["l", "ls"] locks = "cmd:all()" help_cateogory = "General" def func(self): "implement the ooc look command" 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: string = "You are out-of-character (OOC). " string += "Use {w@ic{n to get back to the game, {whelp{n for more info." self.caller.msg(string) else: self.caller = self.character # we have to put this back for normal look to work. super(CmdOOCLook, self).func() class CmdIC(MuxCommand): """ Switch control to an object Usage: @ic <character> Go in-character (IC) as a given Character. This will attempt to "become" a different object assuming you have the right to do so. You cannot become an object that is already controlled by another player. In principle <character> can be any in-game object as long as you have access right to puppet it. """ key = "@ic" locks = "cmd:all()" # must be all() or different puppeted objects won't be able to access it. aliases = "@puppet" help_category = "General" def func(self): """ Simple puppet method """ caller = self.caller if utils.inherits_from(caller, "src.objects.objects.Object"): caller = caller.player new_character = None if not self.args: new_character = caller.db.last_puppet if not new_character: caller.msg("Usage: @ic <character>") return if not new_character: # search for a matching character new_character = caller.search(self.args, global_search=True) if not new_character: # the search method handles error messages etc. return if new_character.player: if new_character.player == caller: caller.msg("{RYou already are {c%s{n." % new_character.name) else: caller.msg("{c%s{r is already acted by another player.{n" % new_character.name) return if not new_character.access(caller, "puppet"): caller.msg("{rYou may not become %s.{n" % new_character.name) return old_char = None if caller.character: # save the old character. We only assign this to last_puppet if swap is successful. old_char = caller.character if caller.swap_character(new_character): new_character.msg("\n{gYou become {c%s{n.\n" % new_character.name) caller.db.last_puppet = old_char if not new_character.location: # this might be due to being hidden away at logout; check loc = new_character.db.prelogout_location if not loc: # still no location; use home loc = new_character.home new_character.location = loc if new_character.location: new_character.location.msg_contents("%s has entered the game." % new_character.key, exclude=[new_character]) new_character.location.at_object_receive(new_character, new_character.location) new_character.execute_cmd("look") else: caller.msg("{rYou cannot become {C%s{n." % new_character.name) class CmdOOC(MuxCommand): """ @ooc - go ooc Usage: @ooc Go out-of-character (OOC). This will leave your current character and put you in a incorporeal OOC state. """ key = "@ooc" locks = "cmd:all()" # this must be all(), or different puppeted objects won't be able to access it. aliases = "@unpuppet" help_category = "General" def func(self): "Implement function" caller = self.caller if utils.inherits_from(caller, "src.objects.objects.Object"): caller = self.caller.player if not caller.character: string = "You are already OOC." caller.msg(string) return caller.db.last_puppet = caller.character # save location as if we were disconnecting from the game entirely. if caller.character.location: caller.character.location.msg_contents("%s has left the game." % caller.character.key, exclude=[caller.character]) caller.character.db.prelogout_location = caller.character.location caller.character.location = None # disconnect caller.character.player = None caller.character = None caller.msg("\n{GYou go OOC.{n\n") caller.execute_cmd("look")
Python
""" Commands that are available from the connect screen. """ import re import traceback from django.conf import settings from django.contrib.auth.models import User from src.server import sessionhandler from src.players.models import PlayerDB from src.objects.models import ObjectDB from src.server.models import ServerConfig from src.comms.models import Channel from src.utils import create, logger, utils, ansi from src.commands.default.muxcommand import MuxCommand from src.commands.cmdhandler import CMD_LOGINSTART CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE class CmdConnect(MuxCommand): """ Connect to the game. Usage (at login screen): connect <email> <password> Use the create command to first create an account before logging in. """ key = "connect" aliases = ["conn", "con", "co"] locks = "cmd:all()" # not really needed def func(self): """ Uses the Django admin api. Note that unlogged-in commands have a unique position in that their func() receives a session object instead of a source_object like all other types of logged-in commands (this is because there is no object yet before the player has logged in) """ session = self.caller arglist = self.arglist if not arglist or len(arglist) < 2: session.msg("\n\r Usage (without <>): connect <email> <password>") return email = arglist[0] password = arglist[1] # Match an email address to an account. player = PlayerDB.objects.get_player_from_email(email) # No playername match if not player: string = "The email '%s' does not match any accounts." % email string += "\n\r\n\rIf you are new you should first create a new account " string += "using the 'create' command." session.msg(string) return # We have at least one result, so we can check the password. if not player.user.check_password(password): session.msg("Incorrect password.") return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0]==player.name for tup in bans) or any(tup[2].match(session.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" session.msg(string) session.execute_cmd("quit") return # actually do the login. This will call all hooks. session.session_login(player) # 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") class CmdCreate(MuxCommand): """ Create a new account. Usage (at login screen): create \"playername\" <email> <password> This creates a new player account. """ key = "create" aliases = ["cre", "cr"] locks = "cmd:all()" def parse(self): """ The parser must handle the multiple-word player name enclosed in quotes: connect "Long name with many words" my@myserv.com mypassw """ super(CmdCreate, self).parse() self.playerinfo = [] if len(self.arglist) < 3: return if len(self.arglist) > 3: # this means we have a multi_word playername. pop from the back. password = self.arglist.pop() email = self.arglist.pop() # what remains is the playername. playername = " ".join(self.arglist) else: playername, email, password = self.arglist playername = playername.replace('"', '') # remove " playername = playername.replace("'", "") self.playerinfo = (playername, email, password) def func(self): "Do checks and create account" session = self.caller try: playername, email, password = self.playerinfo except ValueError: string = "\n\r Usage (without <>): create \"<playername>\" <email> <password>" session.msg(string) return if not re.findall('^[\w. @+-]+$', playername) or not (0 < len(playername) <= 30): session.msg("\n\r Playername can max be 30 characters or fewer. Letters, spaces, dig\ its and @/./+/-/_ only.") # this echoes the restrictions made by django's auth module. return if not email or not password: session.msg("\n\r You have to supply an e-mail address followed by a password." ) return if not utils.validate_email_address(email): # check so the email at least looks ok. session.msg("'%s' is not a valid e-mail address." % email) return # Run sanity and security checks if PlayerDB.objects.get_player_from_name(playername) or User.objects.filter(username=playername): # player already exists session.msg("Sorry, there is already a player with the name '%s'." % playername) return if PlayerDB.objects.get_player_from_email(email): # email already set on a player session.msg("Sorry, there is already a player with that email address.") return if len(password) < 3: # too short password string = "Your 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." session.msg(string) return # everything's ok. Create the new player account. try: default_home = ObjectDB.objects.get_id(settings.CHARACTER_DEFAULT_HOME) typeclass = settings.BASE_CHARACTER_TYPECLASS permissions = settings.PERMISSION_PLAYER_DEFAULT new_character = create.create_player(playername, email, password, permissions=permissions, character_typeclass=typeclass, character_location=default_home, character_home=default_home) if not new_character: session.msg("There was an error creating the default Character/Player. This error was logged. Contact an admin.") return new_player = new_character.player # This needs to be called so the engine knows this player is logging in for the first time. # (so it knows to call the right hooks during login later) 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) # allow only the character itself and the player to puppet this character (and Immortals). new_character.locks.add("puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" % (new_character.id, new_player.id)) # set a default description new_character.db.desc = "This is a Player." # tell the caller everything went well. string = "A new account '%s' was created with the email address %s. Welcome!" string += "\n\nYou can now log with the command 'connect %s <your password>'." session.msg(string % (playername, email, email)) 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." session.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc()) class CmdQuit(MuxCommand): """ 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 = "quit" aliases = ["q", "qu"] locks = "cmd:all()" def func(self): "Simply close the connection." session = self.caller session.msg("Good bye! Disconnecting ...") session.session_disconnect() class CmdUnconnectedLook(MuxCommand): """ This is an unconnected version of the look command for simplicity. This is called by the server and kicks everything in gear. All it does is display the connect screen. """ key = CMD_LOGINSTART aliases = ["look", "l"] locks = "cmd:all()" def func(self): "Show the connect screen." try: screen = utils.string_from_module(CONNECTION_SCREEN_MODULE) string = ansi.parse_ansi(screen) self.caller.msg(string) except Exception, e: self.caller.msg("Error in CONNECTION_SCREEN MODULE: " + str(e)) self.caller.msg("Connect screen not found. Enter 'help' for aid.") class CmdUnconnectedHelp(MuxCommand): """ This is an unconnected version of the help command, for simplicity. It shows a pane of info. """ key = "help" aliases = ["h", "?"] locks = "cmd:all()" def func(self): "Shows help" string = \ """ You are not yet logged into the game. Commands available at this point: {wcreate, connect, look, help, quit{n To login to the system, you need to do one of the following: {w1){n If you have no previous account, you need to use the 'create' command like this: {wcreate "Anna the Barbarian" anna@myemail.com c67jHL8p{n 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. {w2){n If you have an account already, either because you just created one in {w1){n above or you are returning, use the 'connect' command: {wconnect anna@myemail.com c67jHL8p{n This should log you in. Run {whelp{n again once you're logged in to get more aid. Hope you enjoy your stay! You can use the {wlook{n command if you want to see the connect screen again. """ self.caller.msg(string)
Python
# # This is Evennia's default connection screen. It is imported # and run from game/gamesrc/world/connection_screens.py. # from src.utils import utils DEFAULT_SCREEN = \ """{b=============================================================={n Welcome to {gEvennia{n, version %s! If you have an existing account, connect to it by typing: {wconnect <email> <password>{n If you need to create an account, type (without the <>'s): {wcreate \"<username>\" <email> <password>{n Enter {whelp{n for more info. {wlook{n will re-show this screen. {b=============================================================={n""" % utils.get_evennia_version()
Python
""" The default command parser. Use your own by assigning settings.ALTERNATE_PARSER to a Python path to a module containing the replacing cmdparser function. The replacement parser must return a CommandCandidates object. """ def cmdparser(raw_string, cmdset, caller, match_index=None): """ This function is called by the cmdhandler once it has gathered all valid cmdsets for the calling player. raw_string is the unparsed text entered by the caller. The cmdparser understand the following command combinations (where [] marks optional parts. [cmdname[ cmdname2 cmdname3 ...] [the rest] A command may consist of any number of space-separated words of any length, and contain any character. The parser makes use of the cmdset to find command candidates. The parser return a list of matches. Each match is a tuple with its first three elements being the parsed cmdname (lower case), the remaining arguments, and the matched cmdobject from the cmdset. """ def create_match(cmdname, string, cmdobj): """ Evaluates the quality of a match by counting how many chars of cmdname matches string (counting from beginning of string). We also calculate a ratio from 0-1 describing how much cmdname matches string. We return a tuple (cmdname, count, ratio, args, cmdobj). """ cmdlen, strlen = len(cmdname), len(string) mratio = 1 - (strlen - cmdlen) / (1.0 * strlen) args = string[cmdlen:] return (cmdname, args, cmdobj, cmdlen, mratio) if not raw_string: return None matches = [] # match everything that begins with a matching cmdname. l_raw_string = raw_string.lower() for cmd in cmdset: matches.extend([create_match(cmdname, raw_string, cmd) for cmdname in [cmd.key] + cmd.aliases if cmdname and l_raw_string.startswith(cmdname.lower())]) if not matches: # no matches found. if '-' in raw_string: # This could be due to the user trying to identify the # command with a #num-<command> style syntax. mindex, new_raw_string = raw_string.split("-", 1) if mindex.isdigit(): mindex = int(mindex) - 1 # feed result back to parser iteratively return cmdparser(new_raw_string, cmdset, caller, match_index=mindex) # only select command matches we are actually allowed to call. matches = [match for match in matches if match[2].access(caller, 'cmd')] if len(matches) > 1: # see if it helps to analyze the match with preserved case. matches = [match for match in matches if raw_string.startswith(match[0])] if len(matches) > 1: # we still have multiple matches. Sort them by count quality. matches = sorted(matches, key=lambda m: m[3]) # only pick the matches with highest count quality quality = [mat[3] for mat in matches] matches = matches[-quality.count(quality[-1]):] if len(matches) > 1: # still multiple matches. Fall back to ratio-based quality. matches = sorted(matches, key=lambda m: m[4]) # only pick the highest rated ratio match quality = [mat[4] for mat in matches] matches = matches[-quality.count(quality[-1]):] if len(matches) > 1 and match_index != None and 0 <= match_index < len(matches): # We couldn't separate match by quality, but we have an index argument to # tell us which match to use. matches = [matches[match_index]] # no matter what we have at this point, we have to return it. return matches #------------------------------------------------------------ # Search parsers and support methods #------------------------------------------------------------ # # Default functions for formatting and processing searches. # # This is in its own module due to them being possible to # replace from the settings file by setting the variables # # SEARCH_AT_RESULTERROR_HANDLER # SEARCH_MULTIMATCH_PARSER # # The the replacing modules must have the same inputs and outputs as # those in this module. # def at_search_result(msg_obj, ostring, results, global_search=False): """ Called by search methods after a result of any type has been found. Takes a search result (a list) and formats eventual errors. msg_obj - object to receive feedback. ostring - original search string results - list of found matches (0, 1 or more) global_search - if this was a global_search or not (if it is, there might be an idea of supplying dbrefs instead of only numbers) Multiple matches are returned to the searching object as 1-object 2-object 3-object etc """ string = "" if not results: # no results. string = "Could not find '%s'." % ostring results = None elif len(results) > 1: # we have more than one match. We will display a # list of the form 1-objname, 2-objname etc. # check if the msg_object may se dbrefs show_dbref = global_search string += "More than one match for '%s'" % ostring string += " (please narrow target):" for num, result in enumerate(results): invtext = "" dbreftext = "" if hasattr(result, "location") and result.location == msg_obj: invtext = " (carried)" if show_dbref: dbreftext = "(#%i)" % result.id string += "\n %i-%s%s%s" % (num+1, result.name, dbreftext, invtext) results = None else: # we have exactly one match. results = results[0] if string: msg_obj.msg(string.strip()) return results def at_multimatch_input(ostring): """ Parse number-identifiers. This parser will be called by the engine when a user supplies a search term. The search term must be analyzed to determine if the user wants to differentiate between multiple matches (usually found during a previous search). This method should separate out any identifiers from the search string used to differentiate between same-named objects. The result should be a tuple (index, search_string) where the index gives which match among multiple matches should be used (1 being the lowest number, rather than 0 as in Python). This parser version will identify search strings on the following forms 2-object This will be parsed to (2, "object") and, if applicable, will tell the engine to pick the second from a list of same-named matches of objects called "object". Ex for use in a game session: > look You see: ball, ball, ball and ball. > get ball There where multiple matches for ball: 1-ball 2-ball 3-ball 4-ball > get 3-ball You get the ball. """ if not isinstance(ostring, basestring): return (None, ostring) if not '-' in ostring: return (None, ostring) try: index = ostring.find('-') number = int(ostring[:index])-1 return (number, ostring[index+1:]) except ValueError: #not a number; this is not an identifier. return (None, ostring) except IndexError: return (None, ostring) def at_multimatch_cmd(caller, matches): """ Format multiple command matches to a useful error. """ string = "There where multiple matches:" for num, match in enumerate(matches): # each match is a tuple (candidate, cmd) cmdname, arg, cmd, dum, dum = match is_channel = hasattr(cmd, "is_channel") and cmd.is_channel if is_channel: is_channel = " (channel)" else: is_channel = "" is_exit = hasattr(cmd, "is_exit") and cmd.is_exit if is_exit and cmd.destination: is_exit = " (exit to %s)" % cmd.destination else: is_exit = "" id1 = "" id2 = "" if not (is_channel or is_exit) and (hasattr(cmd, 'obj') and cmd.obj != caller): # the command is defined on some other object id1 = "%s-%s" % (num + 1, cmdname) id2 = " (%s)" % (cmd.obj.key) else: id1 = "%s-%s" % (num + 1, cmdname) id2 = "" string += "\n %s%s%s%s" % (id1, id2, is_channel, is_exit) return string
Python
""" The base Command class. All commands in Evennia inherit from the 'Command' class in this module. """ from src.locks.lockhandler import LockHandler from src.utils.utils import is_iter class CommandMeta(type): """ This metaclass makes some minor on-the-fly convenience fixes to the command class in case the admin forgets to put things in lowercase etc. """ def __init__(mcs, *args, **kwargs): """ Simply make sure all data are stored as lowercase and do checking on all properties that should be in list form. Sets up locks to be more forgiving. """ mcs.key = mcs.key.lower() if mcs.aliases and not is_iter(mcs.aliases): try: mcs.aliases = mcs.aliases.split(',') except Exception: mcs.aliases = [] mcs.aliases = [str(alias).strip() for alias in mcs.aliases] # pre-process locks as defined in class definition temp = [] if hasattr(mcs, 'permissions'): mcs.locks = mcs.permissions if not hasattr(mcs, 'locks'): # default if one forgets to define completely mcs.locks = "cmd:all()" for lockstring in mcs.locks.split(';'): if lockstring and not ':' in lockstring: lockstring = "cmd:%s" % lockstring temp.append(lockstring) mcs.lock_storage = ";".join(temp) mcs.help_category = mcs.help_category.lower() super(CommandMeta, mcs).__init__(*args, **kwargs) # The Command class is the basic unit of an Evennia command; when # defining new commands, the admin subclass this class and # define their own parser method to handle the input. The # advantage of this is inheritage; commands that have similar # structure can parse the input string the same way, minimizing # parsing errors. class Command(object): """ Base command Usage: command [args] This is the base command class. Inherit from this to create new commands. The cmdhandler makes the following variables available to the command methods (so you can always assume them to be there): self.caller - the game object calling the command self.cmdstring - the command name used to trigger this command (allows you to know which alias was used, for example) cmd.args - everything supplied to the command following the cmdstring (this is usually what is parsed in self.parse()) cmd.cmdset - the cmdset from which this command was matched (useful only seldomly, notably for help-type commands, to create dynamic help entries and lists) cmd.obj - the object on which this command is defined. If a default command, this is usually the same as caller. (Note that this initial string is also used by the system to create the help entry for the command, so it's a good idea to format it similar to this one) """ # Tie our metaclass, for some convenience cleanup __metaclass__ = CommandMeta # the main way to call this command (e.g. 'look') key = "command" # alternative ways to call the command (e.g. 'l', 'glance', 'examine') aliases = [] # a list of lock definitions on the form cmd:[NOT] func(args) [ AND|OR][ NOT] func2(args) locks = "" # used by the help system to group commands in lists. help_category = "general" # There is also the property 'obj'. This gets set by the system # on the fly to tie this particular command to a certain in-game entity. # self.obj should NOT be defined here since it will not be overwritten # if it already exists. def __init__(self): self.lockhandler = LockHandler(self) def __str__(self): "Print the command" return self.key def __eq__(self, cmd): """ Compare two command instances to each other by matching their key and aliases. input can be either a cmd object or the name of a command. """ try: return self.match(cmd.key) except AttributeError: # got a string return self.match(cmd) def __contains__(self, query): """ This implements searches like 'if query in cmd'. It's a fuzzy matching used by the help system, returning True if query can be found as a substring of the commands key or its aliases. input can be either a command object or a command name. """ try: query = query.key except AttributeError: # we got a string pass return (query in self.key) or any(query in alias for alias in self.aliases) def match(self, cmdname): """ This is called by the system when searching the available commands, in order to determine if this is the one we wanted. cmdname was previously extracted from the raw string by the system. cmdname is always lowercase when reaching this point. """ return cmdname and ((cmdname == self.key) or (cmdname in self.aliases)) def access(self, srcobj, access_type="cmd", default=False): """ This hook is called by the cmdhandler to determine if srcobj is allowed to execute this command. It should return a boolean value and is not normally something that need to be changed since it's using the Evennia permission system directly. """ return self.lockhandler.check(srcobj, access_type, default=default) # Common Command hooks def at_pre_cmd(self): """ This hook is called before self.parse() on all commands """ pass def at_post_cmd(self): """ This hook is called after the command has finished executing (after self.func()). """ pass def parse(self): """ Once the cmdhandler has identified this as the command we want, this function is run. If many of your commands have a similar syntax (for example 'cmd arg1 = arg2') you should simply define this once and just let other commands of the same form inherit from this. See the docstring of this module for which object properties are available to use (notably self.args). """ pass def func(self): """ This is the actual executing part of the command. It is called directly after self.parse(). See the docstring of this module for which object properties are available (beyond those set in self.parse()) """ # a simple test command to show the available properties string = "-" * 50 string += "\n{w%s{n - Command variables from evennia:\n" % self.key string += "-" * 50 string += "\nname of cmd (self.key): {w%s{n\n" % self.key string += "cmd aliases (self.aliases): {w%s{n\n" % self.aliases string += "cmd perms (self.permissions): {w%s{n\n" % self.permissions string += "help category (self.help_category): {w%s{n\n" % self.help_category string += "object calling (self.caller): {w%s{n\n" % self.caller string += "object storing cmdset (self.obj): {w%s{n\n" % self.obj string += "command string given (self.cmdstring): {w%s{n\n" % self.cmdstring # show cmdset.key instead of cmdset to shorten output string += utils.fill("current cmdset (self.cmdset): {w%s{n\n" % self.cmdset) self.caller.msg(string)
Python
""" Command handler This module contains the infrastructure for accepting commands on the command line. The process is as follows: 1) The calling object (caller) inputs a string and triggers the command parsing system. 2) The system checks the state of the caller - loggedin or not 3) If no command string was supplied, we search the merged cmdset for system command CMD_NOINPUT and branches to execute that. --> Finished 4) Cmdsets are gathered from different sources (in order of dropping priority): channels - all available channel names are auto-created into a cmdset, to allow for giving the channel name and have the following immediately sent to the channel. The sending is performed by the CMD_CHANNEL system command. object cmdsets - all objects at caller's location are scanned for non-empty cmdsets. This includes cmdsets on exits. caller - the caller is searched for its own currently active cmdset. player - lastly the cmdsets defined on caller.player are added. 5) All the gathered cmdsets (if more than one) are merged into one using the cmdset priority rules. 6) If merged cmdset is empty, raise NoCmdSet exception (this should not happen, at least the player should have a default cmdset available at all times). --> Finished 7) The raw input string is parsed using the parser defined by settings.COMMAND_PARSER. It uses the available commands from the merged cmdset to know which commands to look for and returns one or many matches. 8) If match list is empty, branch to system command CMD_NOMATCH --> Finished 9) If match list has more than one element, branch to system command CMD_MULTIMATCH --> Finished 10) A single match was found. If this is a channel-command (i.e. the command name is that of a channel), branch to CMD_CHANNEL --> Finished 11) At this point we have found a normal command. We assign useful variables to it that will be available to the command coder at run-time. 12) We have a unique cmdobject, primed for use. Call all hooks: at_pre_cmd(), cmdobj.parse(), cmdobj.func() and finally at_post_cmd(). """ from traceback import format_exc from django.conf import settings from src.comms.channelhandler import CHANNELHANDLER from src.commands.cmdsethandler import import_cmdset from src.utils import logger, utils from src.commands.cmdparser import at_multimatch_cmd #This switches the command parser to a user-defined one. # You have to restart the server for this to take effect. COMMAND_PARSER = utils.mod_import(*settings.COMMAND_PARSER.rsplit('.', 1)) # There are a few system-hardcoded command names. These # allow for custom behaviour when the command handler hits # special situations -- it then calls a normal Command # that you can customize! # Import these variables and use them rather than trying # to remember the actual string constants. CMD_NOINPUT = "__noinput_command" CMD_NOMATCH = "__nomatch_command" CMD_MULTIMATCH = "__multimatch_command" CMD_CHANNEL = "__send_to_channel_command" # this is the name of the command the engine calls when the player # connects. It is expected to show the login screen. CMD_LOGINSTART = "__unloggedin_look_command" class NoCmdSets(Exception): "No cmdsets found. Critical error." pass class ExecSystemCommand(Exception): "Run a system command" def __init__(self, syscmd, sysarg): self.args = (syscmd, sysarg) # needed by exception error handling self.syscmd = syscmd self.sysarg = sysarg def get_and_merge_cmdsets(caller): """ Gather all relevant cmdsets and merge them. Note that this is only relevant for logged-in callers. """ # The calling object's cmdset try: caller.at_cmdset_get() except Exception: logger.log_trace() try: caller_cmdset = caller.cmdset.current except AttributeError: caller_cmdset = None # Create cmdset for all player's available channels channel_cmdset = None if not caller_cmdset.no_channels: channel_cmdset = CHANNELHANDLER.get_cmdset(caller) # Gather cmdsets from location, objects in location or carried local_objects_cmdsets = [None] location = None if hasattr(caller, "location"): location = caller.location if location and not caller_cmdset.no_objs: # Gather all cmdsets stored on objects in the room and # also in the caller's inventory and the location itself local_objlist = location.contents_get(exclude=caller.dbobj) + caller.contents + [location] for obj in local_objlist: try: # call hook in case we need to do dynamic changing to cmdset obj.at_cmdset_get() except Exception: logger.log_trace() local_objects_cmdsets = [obj.cmdset.current for obj in local_objlist if (obj.cmdset.current and obj.locks.check(caller, 'call', no_superuser_bypass=True))] for cset in local_objects_cmdsets: #This is necessary for object sets, or we won't be able to separate #the command sets from each other in a busy room. cset.old_duplicates = cset.duplicates cset.duplicates = True # Player object's commandsets try: player_cmdset = caller.player.cmdset.current except AttributeError: player_cmdset = None cmdsets = [caller_cmdset] + [player_cmdset] + [channel_cmdset] + local_objects_cmdsets # weed out all non-found sets cmdsets = [cmdset for cmdset in cmdsets if cmdset] # sort cmdsets after reverse priority (highest prio are merged in last) cmdsets = sorted(cmdsets, key=lambda x: x.priority) if cmdsets: # Merge all command sets into one, beginning with the lowest-prio one cmdset = cmdsets.pop(0) for merging_cmdset in cmdsets: #print "<%s(%s,%s)> onto <%s(%s,%s)>" % (merging_cmdset.key, merging_cmdset.priority, merging_cmdset.mergetype, # cmdset.key, cmdset.priority, cmdset.mergetype) cmdset = merging_cmdset + cmdset else: cmdset = None for cset in (cset for cset in local_objects_cmdsets if cset): cset.duplicates = cset.old_duplicates return cmdset # Main command-handler function def cmdhandler(caller, raw_string, testing=False): """ This is the main function to handle any string sent to the engine. caller - calling object raw_string - the command string given on the command line testing - if we should actually execute the command or not. if True, the command instance will be returned instead. """ try: # catch bugs in cmdhandler itself try: # catch special-type commands cmdset = get_and_merge_cmdsets(caller) # print cmdset if not cmdset: # this is bad and shouldn't happen. raise NoCmdSets raw_string = raw_string.strip() if not raw_string: # Empty input. Test for system command instead. syscmd = cmdset.get(CMD_NOINPUT) sysarg = "" raise ExecSystemCommand(syscmd, sysarg) # Parse the input string and match to available cmdset. # This also checks for permissions, so all commands in match # are commands the caller is allowed to call. matches = COMMAND_PARSER(raw_string, cmdset, caller) # Deal with matches if not matches: # No commands match our entered command syscmd = cmdset.get(CMD_NOMATCH) if syscmd: sysarg = raw_string else: sysarg = "Huh? (Type \"help\" for help)" raise ExecSystemCommand(syscmd, sysarg) if len(matches) > 1: # We have a multiple-match syscmd = cmdset.get(CMD_MULTIMATCH) sysarg = "There where multiple matches." if syscmd: syscmd.matches = matches else: sysarg = at_multimatch_cmd(caller, matches) raise ExecSystemCommand(syscmd, sysarg) # At this point, we have a unique command match. match = matches[0] cmdname, args, cmd = match[0], match[1], match[2] # Check if this is a Channel match. if hasattr(cmd, 'is_channel') and cmd.is_channel: # even if a user-defined syscmd is not defined, the # found cmd is already a system command in its own right. syscmd = cmdset.get(CMD_CHANNEL) if syscmd: # replace system command with custom version cmd = syscmd sysarg = "%s:%s" % (cmdname, args) raise ExecSystemCommand(cmd, sysarg) # A normal command. # Assign useful variables to the instance cmd.caller = caller cmd.cmdstring = cmdname cmd.args = args cmd.cmdset = cmdset if hasattr(cmd, 'obj') and hasattr(cmd.obj, 'scripts'): # cmd.obj are automatically made available. # we make sure to validate its scripts. cmd.obj.scripts.validate() if testing: # only return the command instance return cmd # pre-command hook cmd.at_pre_cmd() # Parse and execute cmd.parse() # (return value is normally None) ret = cmd.func() # post-command hook cmd.at_post_cmd() # Done! By default, Evennia does not use this return at all return ret except ExecSystemCommand, exc: # Not a normal command: run a system command, if available, # or fall back to a return string. syscmd = exc.syscmd sysarg = exc.sysarg if syscmd: syscmd.caller = caller syscmd.cmdstring = syscmd.key syscmd.args = sysarg syscmd.cmdset = cmdset if hasattr(syscmd, 'obj') and hasattr(syscmd.obj, 'scripts'): # cmd.obj is automatically made available. # we make sure to validate its scripts. syscmd.obj.scripts.validate() if testing: # only return the command instance return syscmd # parse and run the command syscmd.parse() syscmd.func() elif sysarg: caller.msg(exc.sysarg) except NoCmdSets: # Critical error. string = "No command sets found! This is a sign of a critical bug.\n" string += "The error was logged.\n" string += "If logging out/in doesn't solve the problem, try to " string += "contact the server admin through some other means " string += "for assistance." caller.msg(string) logger.log_errmsg("No cmdsets found: %s" % caller) except Exception: # We should not end up here. If we do, it's a programming bug. string = "%s\nAbove traceback is from an untrapped error." string += " Please file a bug report." logger.log_trace(string) caller.msg(string % format_exc()) except Exception: # This catches exceptions in cmdhandler exceptions themselves string = "%s\nAbove traceback is from a Command handler bug." string += " Please contact an admin." logger.log_trace(string) caller.msg(string % format_exc()) #----------------------------------------------------- end cmdhandler
Python
# # This file defines global variables that will always be # available in a view context without having to repeatedly # include it. For this to work, this file is included in # the settings file, in the TEMPLATE_CONTEXT_PROCESSORS # tuple. # from django.db import models from django.conf import settings from src.utils.utils import get_evennia_version # Determine the site name and server version try: GAME_NAME = settings.SERVERNAME.strip() except AttributeError: GAME_NAME = "Evennia" SERVER_VERSION = get_evennia_version() # Setup lists of the most relevant apps so # the adminsite becomes more readable. USER_RELATED = ['Players', 'Auth'] GAME_ENTITIES = ['Objects', 'Scripts', 'Comms', 'Help'] GAME_SETUP = ['Permissions', 'Config'] CONNECTIONS = ['Irc', 'Imc2'] WEBSITE = ['Flatpages', 'News', 'Sites'] # The main context processor function def general_context(request): """ Returns common Evennia-related context stuff, which is automatically added to context of all views. """ return { 'game_name': GAME_NAME, 'game_slogan': SERVER_VERSION, 'evennia_userapps': USER_RELATED, 'evennia_entityapps': GAME_ENTITIES, 'evennia_setupapps': GAME_SETUP, 'evennia_connectapps': CONNECTIONS, 'evennia_websiteapps':WEBSITE, "webclient_enabled" : settings.WEBCLIENT_ENABLED }
Python
""" This file contains the generic, assorted views that don't fall under one of the other applications. Views are django's way of processing e.g. html templates on the fly. """ from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.models import User from django.conf import settings from src.server.models import ServerConfig from src.objects.models import ObjectDB from src.typeclasses.models import TypedObject from src.players.models import PlayerDB from src.web.news.models import NewsEntry def page_index(request): """ Main root page. """ # Some misc. configurable stuff. # TODO: Move this to either SQL or settings.py based configuration. fpage_player_limit = 4 fpage_news_entries = 2 # A QuerySet of recent news entries. news_entries = NewsEntry.objects.all().order_by('-date_posted')[:fpage_news_entries] # A QuerySet of the most recently connected players. recent_users = PlayerDB.objects.get_recently_connected_players()[:fpage_player_limit] exits = ObjectDB.objects.filter(db_destination__isnull=False) rooms = [room for room in ObjectDB.objects.filter(db_home__isnull=True) if room not in exits] pagevars = { "page_title": "Front Page", "news_entries": news_entries, "players_connected_recent": recent_users, "num_players_connected": ServerConfig.objects.conf('nr_sessions'),#len(PlayerDB.objects.get_connected_players()), "num_players_registered": PlayerDB.objects.num_total_players(), "num_players_connected_recent": len(PlayerDB.objects.get_recently_connected_players()), "num_players_registered_recent": len(PlayerDB.objects.get_recently_created_players()), "num_rooms": len(rooms), "num_exits": len(exits), "num_objects" : ObjectDB.objects.all().count() } context_instance = RequestContext(request) return render_to_response('index.html', pagevars, context_instance) def to_be_implemented(request): """ A notice letting the user know that this particular feature hasn't been implemented yet. """ pagevars = { "page_title": "To Be Implemented...", } context_instance = RequestContext(request) return render_to_response('tbi.html', pagevars, context_instance)
Python
# # Define database entities for the app. # from django.db import models
Python
""" This structures the (simple) structure of the webpage 'application'. """ from django.conf.urls.defaults import * urlpatterns = patterns('src.web.website.views', (r'^$', 'page_index'), )
Python
# # This makes the news model visible in the admin web interface # so one can add/edit/delete news items etc. # from django.contrib import admin from src.web.news.models import NewsTopic, NewsEntry class NewsTopicAdmin(admin.ModelAdmin): list_display = ('name', 'icon') admin.site.register(NewsTopic, NewsTopicAdmin) class NewsEntryAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'topic', 'date_posted') list_filter = ('topic',) search_fields = ['title'] admin.site.register(NewsEntry, NewsEntryAdmin)
Python
""" This is a very simple news application, with most of the expected features like news-categories/topics and searchable archives. """ import django.views.generic.list_detail as gv_list_detail from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.conf import settings from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django import forms from django.db.models import Q from src.web.news.models import NewsTopic, NewsEntry # The sidebar text to be included as a variable on each page. There's got to # be a better, cleaner way to include this on every page. sidebar = """ <p class='doNotDisplay doNotPrint'>This page&rsquo;s menu:</p> <ul id='side-bar'> <li><a href='/news/archive'>News Archive</a></li> <li><a href='/news/search'>Search News</a></li> </ul> """ class SearchForm(forms.Form): """ Class to represent a news search form under Django's newforms. This is used to validate the input on the search_form view, as well as the search_results view when we're picking the query out of GET. This makes searching safe via the search form or by directly inputing values via GET key pairs. """ search_terms = forms.CharField(max_length=100, min_length=3, required=True) def show_news(request, entry_id): """ Show an individual news entry. Display some basic information along with the title and content. """ news_entry = get_object_or_404(NewsEntry, id=entry_id) pagevars = { "page_title": "News Entry", "news_entry": news_entry, "sidebar": sidebar } context_instance = RequestContext(request) return render_to_response('news/show_entry.html', pagevars, context_instance) def news_archive(request): """ Shows an archive of news entries. TODO: Expand this a bit to allow filtering by month/year. """ news_entries = NewsEntry.objects.all().order_by('-date_posted') # TODO: Move this to either settings.py or the SQL configuration. entries_per_page = 15 pagevars = { "page_title": "News Archive", "browse_url": "/news/archive", "sidebar": sidebar } return gv_list_detail.object_list(request, news_entries, template_name='news/archive.html', extra_context=pagevars, paginate_by=entries_per_page) def search_form(request): """ Render the news search form. Don't handle much validation at all. If the user enters a search term that meets the minimum, send them on their way to the results page. """ if request.method == 'GET': # A GET request was sent to the search page, load the value and # validate it. search_form = SearchForm(request.GET) if search_form.is_valid(): # If the input is good, send them to the results page with the # query attached in GET variables. return HttpResponseRedirect('/news/search/results/?search_terms='+ search_form.cleaned_data['search_terms']) else: # Brand new search, nothing has been sent just yet. search_form = SearchForm() pagevars = { "page_title": "Search News", "search_form": search_form, "debug": settings.DEBUG, "sidebar": sidebar } context_instance = RequestContext(request) return render_to_response('news/search_form.html', pagevars, context_instance) def search_results(request): """ Shows an archive of news entries. Use the generic news browsing template. """ # TODO: Move this to either settings.py or the SQL configuration. entries_per_page = 15 # Load the form values from GET to validate against. search_form = SearchForm(request.GET) # You have to call is_valid() or cleaned_data won't be populated. valid_search = search_form.is_valid() # This is the safe data that we can pass to queries without huge worry of # badStuff(tm). cleaned_get = search_form.cleaned_data # Perform searches that match the title and contents. # TODO: Allow the user to specify what to match against and in what # topics/categories. news_entries = NewsEntry.objects.filter(Q(title__contains=cleaned_get['search_terms']) | Q(body__contains=cleaned_get['search_terms'])) pagevars = { "game_name": settings.SERVERNAME, "page_title": "Search Results", "searchtext": cleaned_get['search_terms'], "browse_url": "/news/search/results", "sidebar": sidebar } return gv_list_detail.object_list(request, news_entries, template_name='news/archive.html', extra_context=pagevars, paginate_by=entries_per_page)
Python
# # This module implements a simple news entry system # for the evennia website. One needs to use the # admin interface to add/edit/delete entries. # from django.db import models from django.contrib.auth.models import User class NewsTopic(models.Model): """ Represents a news topic. """ name = models.CharField(max_length=75, unique=True) description = models.TextField(blank=True) icon = models.ImageField(upload_to='newstopic_icons', default='newstopic_icons/default.png', blank=True, help_text="Image for the news topic.") def __str__(self): try: return self.name except: return "Invalid" class Meta: ordering = ['name'] class NewsEntry(models.Model): """ An individual news entry. """ author = models.ForeignKey(User, related_name='author') title = models.CharField(max_length=255) body = models.TextField() topic = models.ForeignKey(NewsTopic, related_name='newstopic') date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ('-date_posted',) verbose_name_plural = "News entries"
Python
""" This structures the url tree for the news application. It is imported from the root handler, game.web.urls.py. """ from django.conf.urls.defaults import * urlpatterns = patterns('src.web.news.views', (r'^show/(?P<entry_id>\d+)/$', 'show_news'), (r'^archive/$', 'news_archive'), (r'^search/$', 'search_form'), (r'^search/results/$', 'search_results'), )
Python
""" This contains a simple view for rendering the webclient page and serve it eventual static content. """ from django.shortcuts import render_to_response from django.template import RequestContext from django.conf import settings from src.server.sessionhandler import SESSIONS def webclient(request): """ Webclient page template loading. """ # as an example we send the number of connected players to the template pagevars = {'num_players_connected': SESSIONS.player_count()} context_instance = RequestContext(request) return render_to_response('webclient.html', pagevars, context_instance)
Python
# # Define database entities for the app. # from django.db import models
Python
""" This structures the (simple) structure of the webpage 'application'. """ from django.views.generic.simple import direct_to_template from django.conf.urls.defaults import * urlpatterns = patterns('', url(r'^$', 'src.web.webclient.views.webclient'),) #url(r'^$', direct_to_template, {'template': 'webclient.html'}),)
Python
# # File that determines what each URL points to. This uses _Python_ regular # expressions, not Perl's. # # See: # http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3 # from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin # fix to resolve lazy-loading bug # https://code.djangoproject.com/ticket/10405#comment:11 from django.db.models.loading import cache as model_cache if not model_cache.loaded: model_cache.get_models() # loop over all settings.INSTALLED_APPS and execute code in # files named admin.py in each such app (this will add those # models to the admin site) admin.autodiscover() # Setup the root url tree from / urlpatterns = patterns('', # User Authentication url(r'^accounts/login', 'django.contrib.auth.views.login'), url(r'^accounts/logout', 'django.contrib.auth.views.logout'), # Front page url(r'^', include('src.web.website.urls')), # News stuff url(r'^news/', include('src.web.news.urls')), # Page place-holder for things that aren't implemented yet. url(r'^tbi/', 'src.web.website.views.to_be_implemented'), # Admin interface url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), # favicon url(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url':'/media/images/favicon.ico'}), # ajax stuff url(r'^webclient/',include('src.web.webclient.urls')), ) # This sets up the server if the user want to run the Django # test server (this should normally not be needed). if settings.SERVE_MEDIA: urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
Python
""" This defines how to edit help entries in Admin. """ from django import forms from django.contrib import admin from src.help.models import HelpEntry class HelpEntryForm(forms.ModelForm): "Defines how to display the help entry" class Meta: model = HelpEntry db_help_category = forms.CharField(label="Help category", initial='General', help_text="organizes help entries in lists") db_lock_storage = forms.CharField(label="Locks", initial='view:all()',required=False, widget=forms.TextInput(attrs={'size':'40'}),) class HelpEntryAdmin(admin.ModelAdmin): "Sets up the admin manaager for help entries" list_display = ('id', 'db_key', 'db_help_category', 'db_lock_storage') list_display_links = ('id', 'db_key') search_fields = ['^db_key', 'db_entrytext'] ordering = ['db_help_category', 'db_key'] save_as = True save_on_top = True list_select_related = True form = HelpEntryForm fieldsets = ( (None, {'fields':(('db_key', 'db_help_category'), 'db_entrytext', 'db_lock_storage'), 'description':"Sets a Help entry. Set lock to <i>view:all()</I> unless you want to restrict it."}),) admin.site.register(HelpEntry, HelpEntryAdmin)
Python