コード例 #1
0
ファイル: things.py プロジェクト: NickF40/upstage
 def add_mediafile(self, key):
     """try to find the mdia with key in self.globalmedia.
     If successful, add the corresponding media object,
     returning the approriate Thing"""
     try:
         media = self.globalmedia[key]
     except KeyError:
         for k in self.globalmedia:
             log.msg('in: %s' % (k))
         raise UpstageError('no such media as %s in %s thing collection' %
                            (key, self.typename))
     return self.add_media(media)
コード例 #2
0
ファイル: player.py プロジェクト: NickF40/upstage
    def update_password(self, form, player):
        def _value(x):
            return form.get(x, [None])[0]

        user = _value('username')
        newpass = _value('password')
        newpass2 = _value('password2')
        log.msg(
            "-----------------------Setting new password--------------------------"
        )

        if newpass != newpass2:
            raise UpstageError('Password did not match!')

        self[user].set_password(newpass)

        self.save()
コード例 #3
0
ファイル: player.py プロジェクト: NickF40/upstage
    def update_from_form(self, form, player):
        """Three modes either Add, delete or change password depending on form information.
        NOT fully checked for security."""

        log.msg(form)

        def _option(x):
            return x in form and form[x]

        def _value(x):
            return form.get(x, [None])[0]

        # Get information from form
        user = _value('username')
        newpass = _value('password')
        newpass2 = _value('password2')

        # if username already exists
        checkP = self.getPlayer(user)
        if checkP.name == user:
            raise UpstageError("User %s already exists" % user)

        # Nic k R 01/02/10: Added if'else to seperate between password changing and player creation.
        if 'date' and 'email' in form:
            newdate = time.strftime("%A, %d %B %Y %I:%M%p %Z")
            newemail = _value('email')
            if newemail == None:
                newemail = 'unset'
        else:
            newdate = 'newdate'
            newemail = 'newemail'
        #Nick R 01/02/10: For some reason refuses to accept more than three params.
        #    Should be expanded later to include saving the date/email info.
        log.msg('user: %s, password: %s/%s' % (user, newpass, newpass2))
        if newpass2 != newpass:
            raise UpstageError("Passwords did not match")
        if not user.isalnum():
            raise UpstageError("Username must be alphanumeric characters")

        log.msg('passwords match')

        # Normal Super Admin edit players details
        if player.can_admin():
            delete = _option('remove players')
            changepw = _option('changepassword')

            if delete:
                for x in tuple(self.keys()):
                    if form.get(x) == ['delete']:
                        xp = self.pop(x)
                        log.msg("Removing player %s (%s)" % (x, xp))
                self.save()

            rights = [
                x for x in ('player', 'maker', 'unlimitedmaker', 'admin',
                            'creator') if _value(x)
            ]

            if user in self:
                self[user].set_rights(rights)
                # Change password
                if (changepw):
                    self[user].set_password(newpass)

            elif user:
                # Create player
                newplayer = _Player(user, None, rights, newdate, newemail)
                newplayer.set_password(newpass)
                self[user] = newplayer

        # Admin self password change
        elif player.can_make():

            if 'saveemail' in form:
                self[user].set_email(newemail)

            elif user in self:
                # Change password only for admin users (their own password only)
                self[user].set_password(newpass)

        # Not allowed any
        else:
            raise UpstageError("not allowed")

        self.save()
コード例 #4
0
ファイル: player.py プロジェクト: NickF40/upstage
 def set_rights(self, rights=()):
     if rights == ():
         raise UpstageError("rights can't be set to %s" % (rights, ))
     self.rights = rights
コード例 #5
0
ファイル: player.py プロジェクト: NickF40/upstage
 def set_email(self, raw_email=None):
     """Set email, using plaintext string"""
     if raw_email is None:
         raise UpstageError("Empty email address!  Please re-enter!")
     self.email = raw_email
コード例 #6
0
ファイル: player.py プロジェクト: NickF40/upstage
 def set_password(self, raw_password=None):
     """Set password, using plaintext string"""
     if raw_password is None:
         raise UpstageError("What a useless password! Think again!")
     self.password = raw_password
     log.msg("Password saved as:" + raw_password)
コード例 #7
0
ファイル: web.py プロジェクト: NickF40/upstage
    def render(self, request):
        """Don't actually render, but calls a process which returns a
        deferred.

        Callbacks on the deferred do the rendering, which is actually
        achieved through redirection.

        """
        # natasha convert
        # turn form into simple dictionary, dropping multiple values.  
        reqargs = request.args
        
        self.assignedstages = reqargs.get('assigned')
        form = dict([(k, v[0]) for k,v in request.args.iteritems()])
        
        # DEBUG: print form sent by request
        for key in form.iterkeys():
            if 'contents' in key:
                value = "[ binary data: %s Bytes ]" % len(form[key])
            else:
                value = form[key]
                if(len(value)>256):
                    value = value[:256] + " ... " # limit length to 256 chars
                value = "'" + value + "'"
            log.msg("SwfConversionWrapper render(): form: '%s' = %s" % (key, value))
        
        # FIXME: trim spaces from form values? (#104)
        
        # handle kind of images: upload or library:
        imagetype = form.get('imagetype','unknown')
        
        # handle upload imagetype
        if imagetype == 'upload':
            
            log.msg('SwfConversionWrapper: render(): imagetype UPLOAD')
            
            # natasha: added prefix value
            prefix = ''
            try:
                self.mediatype = form.pop('type', None)
                if not self.mediatype in self.mediatypes:
                    raise UpstageError('Not a real kind of thing: %s' % self.mediatype)
                self.media_dict = self.mediatypes[self.mediatype] #self.media_dict = self.collections
                # change to starswith 'avcontents'
                if self.mediatype == 'avatar':
                    prefix = 'av'
                    # self.media_dict = self.collection.avatars
                elif self.mediatype == 'prop':
                    prefix = 'pr'
                elif self.mediatype == 'backdrop':
                    prefix = 'bk'
                elif self.mediatype == 'audio': # remem audio not included as things
                    prefix = 'au'
                
                # imgs = [ (k, v) for k, v in form.iteritems() if k.startswith('contents') and v ]
                contentname = prefix + 'contents'
                imgs = [ (k, v) for k, v in form.iteritems() if k.startswith(contentname) and v ]
                imgs.sort()
                
                # DEBUG:
                #log.msg("SwfConversionWrapper: imgs = %s" % imgs);
     
                # save input files in /tmp, also save file names
                tfns = [ save_tempfile(x[1]) for x in imgs ]
    
                # Alan (12/09/07) ==> Gets the size of image files using the previously created temp filenames.
                # natasha getfilesize
                fileSizes = getFileSizes(tfns)
                
                swf = unique_custom_string(suffix='.swf')
                if form.get('mode', '') == 'replace':
                    oldfile = form.get('oldfile')
                    try:
                        self.media_dict.deleteFile(oldfile)
                    except KeyError:
                        log.msg('the file does not exist. nothing was deleted.')
                        request.write(errorpage(request, 'The file you want to replace does not exist. Accidentally pressed the back button? Tut, tut..', 'mediaedit'))
                        request.finish()

                thumbnail = swf.replace('.swf', '.jpg')         # FIXME: see #20 (Uploaded media is not converted to JPEG)
                swf_full = os.path.join(config.MEDIA_DIR, swf)
                thumbnail_full = os.path.join(config.THUMBNAILS_DIR, thumbnail)
    
            except UpstageError, e:            
                return errorpage(request, e, 'mediaupload')
    
            """ Alan (13/09/07) ==> Check the file sizes of avatar frame """
            # natasha continue conversion
            if not (fileSizes is None):
                if validSizes(fileSizes, self.player.can_upload_big_file()):
                    # call the process with swf filename and temp image filenames 
                    d = getProcessValue(config.IMG2SWF_SCRIPT, args=[swf_full, thumbnail_full] + tfns)
                    args = (swf, thumbnail, form, request)
                    d.addCallbacks(self.success_upload, self.failure_upload, args, {}, args, {})
                    d.addBoth(self.cleanup_upload, tfns)
                    d.setTimeout(config.MEDIA_TIMEOUT, timeoutFunc=d.errback)
                    d.addErrback(log.err)   # Make sure errors get logged - TODO is this working?
                else:
                    redirect = 'mediaupload'
                    if form.get('mode', '') == 'replace':
                        redirect = 'mediaedit'
                        self.media_dict.restoreOldFile(form.get('oldfile'))
                    ''' Send new avatar page back containing error message '''
                    self.player.set_setError(True)
                    self.cleanup_upload(None, tfns)
                    request.write(errorpage(request, 'You do not have the permission to upload a file over 1MB in size.', redirect))
                    # request.redirect('/admin/new/%s' %(self.mediatype))
                    request.finish()
コード例 #8
0
ファイル: web.py プロジェクト: NickF40/upstage
class SwfConversionWrapper(Resource):
    """Start a subprocess to convert an image into swf.
    Upon completion of the process, redirect to NewAvatar page.
    Form should contain these elements:
       - name      - name of the uploaded thing
       - contents  - file contents of uploaded thing
       - type      - media type
     May have:
       - voice     - avatar voice
       - editmode  - ' merely editing' signals non conversion, just
                     metadata changes.
    """
    isLeaf = True
    
    def __init__(self, mediatypes, player, stages):
        Resource.__init__(self)
        self.mediatypes = mediatypes
        # Alan (14/09/07) - Gets the player trying to upload
        self.player = player
        self.assignedstages = '' #natasha
        self.mediatype = '' # Natasha trying to make it a global variable
        self.stages = stages
                 
    def render(self, request):
        """Don't actually render, but calls a process which returns a
        deferred.

        Callbacks on the deferred do the rendering, which is actually
        achieved through redirection.

        """
        # natasha convert
        # turn form into simple dictionary, dropping multiple values.  
        reqargs = request.args
        
        self.assignedstages = reqargs.get('assigned')
        form = dict([(k, v[0]) for k,v in request.args.iteritems()])
        
        # DEBUG: print form sent by request
        for key in form.iterkeys():
            if 'contents' in key:
                value = "[ binary data: %s Bytes ]" % len(form[key])
            else:
                value = form[key]
                if(len(value)>256):
                    value = value[:256] + " ... " # limit length to 256 chars
                value = "'" + value + "'"
            log.msg("SwfConversionWrapper render(): form: '%s' = %s" % (key, value))
        
        # FIXME: trim spaces from form values? (#104)
        
        # handle kind of images: upload or library:
        imagetype = form.get('imagetype','unknown')
        
        # handle upload imagetype
        if imagetype == 'upload':
            
            log.msg('SwfConversionWrapper: render(): imagetype UPLOAD')
            
            # natasha: added prefix value
            prefix = ''
            try:
                self.mediatype = form.pop('type', None)
                if not self.mediatype in self.mediatypes:
                    raise UpstageError('Not a real kind of thing: %s' % self.mediatype)
                self.media_dict = self.mediatypes[self.mediatype] #self.media_dict = self.collections
                # change to starswith 'avcontents'
                if self.mediatype == 'avatar':
                    prefix = 'av'
                    # self.media_dict = self.collection.avatars
                elif self.mediatype == 'prop':
                    prefix = 'pr'
                elif self.mediatype == 'backdrop':
                    prefix = 'bk'
                elif self.mediatype == 'audio': # remem audio not included as things
                    prefix = 'au'
                
                # imgs = [ (k, v) for k, v in form.iteritems() if k.startswith('contents') and v ]
                contentname = prefix + 'contents'
                imgs = [ (k, v) for k, v in form.iteritems() if k.startswith(contentname) and v ]
                imgs.sort()
                
                # DEBUG:
                #log.msg("SwfConversionWrapper: imgs = %s" % imgs);
     
                # save input files in /tmp, also save file names
                tfns = [ save_tempfile(x[1]) for x in imgs ]
    
                # Alan (12/09/07) ==> Gets the size of image files using the previously created temp filenames.
                # natasha getfilesize
                fileSizes = getFileSizes(tfns)
                
                swf = unique_custom_string(suffix='.swf')
                if form.get('mode', '') == 'replace':
                    oldfile = form.get('oldfile')
                    try:
                        self.media_dict.deleteFile(oldfile)
                    except KeyError:
                        log.msg('the file does not exist. nothing was deleted.')
                        request.write(errorpage(request, 'The file you want to replace does not exist. Accidentally pressed the back button? Tut, tut..', 'mediaedit'))
                        request.finish()

                thumbnail = swf.replace('.swf', '.jpg')         # FIXME: see #20 (Uploaded media is not converted to JPEG)
                swf_full = os.path.join(config.MEDIA_DIR, swf)
                thumbnail_full = os.path.join(config.THUMBNAILS_DIR, thumbnail)
    
            except UpstageError, e:            
                return errorpage(request, e, 'mediaupload')
    
            """ Alan (13/09/07) ==> Check the file sizes of avatar frame """
            # natasha continue conversion
            if not (fileSizes is None):
                if validSizes(fileSizes, self.player.can_upload_big_file()):
                    # call the process with swf filename and temp image filenames 
                    d = getProcessValue(config.IMG2SWF_SCRIPT, args=[swf_full, thumbnail_full] + tfns)
                    args = (swf, thumbnail, form, request)
                    d.addCallbacks(self.success_upload, self.failure_upload, args, {}, args, {})
                    d.addBoth(self.cleanup_upload, tfns)
                    d.setTimeout(config.MEDIA_TIMEOUT, timeoutFunc=d.errback)
                    d.addErrback(log.err)   # Make sure errors get logged - TODO is this working?
                else:
                    redirect = 'mediaupload'
                    if form.get('mode', '') == 'replace':
                        redirect = 'mediaedit'
                        self.media_dict.restoreOldFile(form.get('oldfile'))
                    ''' Send new avatar page back containing error message '''
                    self.player.set_setError(True)
                    self.cleanup_upload(None, tfns)
                    request.write(errorpage(request, 'You do not have the permission to upload a file over 1MB in size.', redirect))
                    # request.redirect('/admin/new/%s' %(self.mediatype))
                    request.finish()
            #return server.NOT_DONE_YET
        
        # handle library imagetype
        elif imagetype == 'library':
            
            log.msg('SwfConversionWrapper: render(): imagetype LIBRARY')
            
            name = form.get('name', '')
            while self.name_is_used(name):
                name += random.choice('1234567890')
            
            tags = form.get('tags','')
            
            has_streaming = form.get('hasstreaming','false')
            streamtype = form.get('streamtype','auto')
            streamserver = form.get('streamserver','')
            streamname = form.get('streamname','')
            
            medium = ''
            if (has_streaming.lower() == 'true'):
                medium = 'stream'
            
            now = datetime.datetime.now()
            voice = form.get('voice','')
            
            # create random strings for library items
            random_swf_id = util.random_string(config.LIBRARY_ID_LENGTH)
            random_thumbnail_id = util.random_string(config.LIBRARY_ID_LENGTH)
            
            # FIXME test if generated strings already exist, so choose another
            
            # set thumbnail according to streamtype
            thumbnail_image = 'IconLiveStream'   # default
            if streamtype == 'audio':
                thumbnail_image = 'IconAudioStream'
            elif streamtype == 'video':
                thumbnail_image = 'IconVideoStream'
            
            thumbnail = config.LIBRARY_PREFIX + random_thumbnail_id + ":" + thumbnail_image
            
            swf_image = 'VideoOverlay' 
            swf = config.LIBRARY_PREFIX + random_swf_id + ":" + swf_image
            
            log.msg("render(): has streaming? %s" % has_streaming)
            log.msg("render(): streamtype: %s" % streamtype)
            log.msg("render(): streamserver: %s" % streamserver)
            log.msg("render(): streamname: %s" % streamname)    
            log.msg("render(): swf (file): %s" % swf)
            log.msg("render(): name: %s" % name)
            log.msg("render(): voice: %s" % voice)
            log.msg("render(): now: %s" % now)
            log.msg("render(): tags: %s" % tags)
            log.msg("render(): medium: %s" % medium)
            log.msg("render(): thumbnail: %s" % thumbnail)
            log.msg("render(): swf: %s" % swf)
            
            try:
                self.mediatype = form.pop('type', None)
                if not self.mediatype in self.mediatypes:
                    raise UpstageError('Not a real kind of thing: %s' % self.mediatype)
                self.media_dict = self.mediatypes[self.mediatype]
                
                key = unique_custom_string(prefix=self.mediatype+'_', suffix='')
                # add avatar
                self.media_dict.add(file=swf,
                                    name=name,
                                    voice=voice,
                                    uploader=self.player.name,
                                    dateTime=(now.strftime("%d/%m/%y @ %I:%M %p")),
                                    tags=tags,
                                    streamserver=streamserver,
                                    streamname=streamname,
                                    medium=medium,
                                    thumbnail=thumbnail,
                                    key=key
                                    )
                
                # assign to stage?
                if self.assignedstages is not None:
                    log.msg("render(): assigning to stages: %s" % self.assignedstages)
                    self.assign_media_to_stages(self.assignedstages, key, self.mediatype)
                    
            except UpstageError, e:            
                return errorpage(request, e, 'mediaupload')
コード例 #9
0
ファイル: things.py プロジェクト: NickF40/upstage
 def remove_mediafile(self, key):
     try:
         media = self.globalmedia[key]
     except KeyError:
         raise UpstageError('Media file does not exist in thing collection')
     self.remove_media(media)
コード例 #10
0
ファイル: globalmedia.py プロジェクト: NickF40/upstage
    def update_from_form(self, form, player):
        """Process an http form. depending on the form,
        either delete or modify an item
        @param form the form on the web page
        @param player the user that requested update

        There are two modes.  If the form has the key 'delete', then
        any keys in the form delete_??? will attempt to delete the
        thing called ???.  If there is a key 'force', the deleted
        thing will be removed from all stages it is on.  Otherwise it
        will *not* be deleted if the thing is on a stage.

        If 'delete' is not a key, then the form is assumed to be
        editing a particular thing's details.
        """
        if player.is_player():
            return
        if 'delete' in form.get('action',[None])[0]: #Shaun Narayan (02/14/10) - arg names changed in URL so have been refelcted here.
            log.msg("Deleting, form is: %s" %form)
            # AC (05.02.08) - Added correct exception handling.
            try:
                msg = self._delete_things(form)
                if msg:
                    log.msg('saving post-deletion')
                    self.save()
                    log.msg('\n%s\n' %msg)
            except:
                raise UpstageError("Could not delete selected items") 
                
        else: #editing a thing
            log.msg("Attempting update")
            ID = form.get('mediaName', [None])[0] #Shaun Narayan (02/14/10) - arg names changed in URL so have been refelcted here.
            try:
                thing = self[ID]
            except KeyError:
                log.msg("Can't edit %s (not in %s)" % (ID, self))
                raise UpstageError("<b>There is no such thing as %s</b>" % ID)
            def _update(x):
                _attr = form.get(x)
                if _attr is not None:
                    if(x == 'tags'):
                        #Added by Heath / Vibhu 24/08/2011 - new tags to the current tags.
                        setattr(thing, x, _attr[0])
                    else:
                        setattr(thing, x, _attr[0])
                    #Added by Heath Behrens 17/06/2011 - Fix so that avatar voice is updated without server restart...
                    collections = self._get_stage_collections() # retrieve the collections for each stage
                    for col in collections: #loop over the collections
                        things = col[0] # extract the things collection
                        if(things.contains_thing(thing)): # check if it contains this thing
                            things.add_media(thing) #if it does add it to media.
            #Heath Behrens 16/08/2011 - Added to extract assigned and unassigned stages from form                
            assigned = form.get('assigned')
            unassigned = form.get('unassigned')
            name = form.get('mediaName')
            # loop over the assigned stages which are comma separated
            for s in assigned[0].split(','):
                st = self.stages.get(s) #get reference to the stage object
                if st is not None:
                    st.add_mediato_stage(name[0])
            for us in unassigned[0].split(','):
                st = self.stages.get(us)
                if st is not None:
                    st.remove_media_from_stage(name[0])
            _update('tags') #call to update the collection with the new tags
            _update('name')
            _update('voice')
            
            # TODO add stream parameters?
            
            if 'audio_type' in form:
                audiotype = form.get('audio_type')[0];

                setattr(thing, 'medium', form.get('audio_type')[0])
                if audiotype == 'sfx':
                    setattr(thing, 'thumbnail', config.SFX_ICON_IMAGE_URL);
                    setattr(thing, 'web_thumbnail', config.SFX_ICON_IMAGE_URL);
                else:
                    setattr(thing, 'thumbnail', config.MUSIC_ICON_IMAGE_URL);
                    setattr(thing, 'web_thumbnail', config.MUSIC_ICON_IMAGE_URL);
                log.msg('thing\'s thumbnail has been changed to %s' %(thing.thumbnail))
        self.save()
コード例 #11
0
ファイル: globalmedia.py プロジェクト: NickF40/upstage
 def set_stages(self, stages):
     """StageDict lets us know it wants to use this"""
     if self.stages is not None:
         # could maintain list, if there is ever a need.
         raise UpstageError("stageDict is already set")
     self.stages = stages