Esempio n. 1
0
    def mutate(self, info, id):
        with ScopedSession() as local_db_session:
            id = from_global_id(id)[1]
            stage = local_db_session.query(StageModel).filter(
                StageModel.id == id).first()
            if stage:
                code, error, user, timezone = current_user()
                if not user.role in (ADMIN, SUPER_ADMIN):
                    if not user.id == stage.owner_id:
                        raise Exception(
                            "Only stage owner or admin can delete this stage!")

                local_db_session.query(ParentStage).filter(
                    ParentStage.stage_id == id).delete(
                        synchronize_session=False)
                local_db_session.query(StageAttributeModel).filter(
                    StageAttributeModel.stage_id == id).delete(
                        synchronize_session=False)
                for performance in local_db_session.query(
                        PerformanceModel).filter(
                            PerformanceModel.stage_id == id).all():
                    local_db_session.query(EventModel).filter(
                        EventModel.performance_id == performance.id).delete(
                            synchronize_session=False)
                    local_db_session.delete(performance)
                local_db_session.delete(stage)
                local_db_session.flush()
                local_db_session.commit()
            else:
                raise Exception("Stage not found!")

        return DeleteStage(success=True)
Esempio n. 2
0
    def mutate(self, info, stage_id, name=None, description=None):
        if not name:
            raise Exception("Please pick a name!")

        current_user_id = get_jwt_identity()
        with ScopedSession() as local_db_session:
            id = from_global_id(stage_id)[1]
            stage = local_db_session.query(Stage).filter(
                Stage.id == id).first()

            if stage:
                code, error, user, timezone = current_user()
                if not user.role in (ADMIN, SUPER_ADMIN):
                    if not user.id == stage.owner_id:
                        raise Exception(
                            "Only stage owner or Admin can start a recording on this stage!"
                        )
            else:
                raise Exception("Stage does not exist!")

            performance = PerformanceModel(stage=stage,
                                           name=name,
                                           description=description,
                                           recording=True)
            local_db_session.add(performance)
            local_db_session.flush()
            local_db_session.commit()

            recording = local_db_session.query(PerformanceModel).filter(
                PerformanceModel.id == performance.id).first()
            return StartRecording(recording=recording)
Esempio n. 3
0
    def mutate(self, info, inbound):
        data = graphql_utils.input_to_dictionary(inbound)
        code,error,user,timezone = current_user()
        if not user.role in (ADMIN,SUPER_ADMIN) :
            if not user.id == int(data['id']):
                raise Exception("Permission denied!")
        
        if not data['email'] and data['role'] != GUEST:
            raise Exception("Email is required!")

        with ScopedSession() as local_db_session:
            user = local_db_session.query(UserModel)\
                .filter(UserModel.id==data['id']).first()
            if (data['password']):
                data['password'] = encrypt(data['password'])
            else:
                del data['password']
            for key, value in data.items():
                if key == 'active':
                    if value and not user.active and not user.deactivated_on:
                        send(user.email, f"Registration approved for user {user.username}", user_approved(user))
                    if not value and user.active:
                        user.deactivated_on = datetime.now()

                if hasattr(user, key):
                    setattr(user, key, value)

        user = DBSession.query(UserModel).filter(UserModel.id==data['id']).first()
        return UpdateUser(user=user)
Esempio n. 4
0
    def mutate(self, info, subject, body, recipients):
        code, error, user, timezone = current_user()
        if not user.role in (ADMIN, SUPER_ADMIN):
            raise Exception(
                "Only Admin can send notification emails!")

        send(recipients, subject, body)
        return SendEmail(success=True)
Esempio n. 5
0
    def mutate(self, info, id):
        with ScopedSession() as local_db_session:
            id = from_global_id(id)[1]
            asset = local_db_session.query(AssetModel).filter(
                AssetModel.id == id).first()
            if asset:
                code, error, user, timezone = current_user()
                if not user.role in (ADMIN, SUPER_ADMIN):
                    if not user.id == asset.owner_id:
                        return DeleteMedia(success=False, message="Only media owner or admin can delete this media!")

                if asset.description:
                    attributes = json.loads(asset.description)
                    if 'frames' in attributes and attributes['frames']:
                        # Delete frames that was assigned only to this media
                        for frame in attributes['frames']:
                            frame_asset = local_db_session.query(AssetModel).filter(
                                or_(AssetModel.file_location == frame, AssetModel.description.contains(frame))).first()
                            if not frame_asset:
                                physical_path = os.path.join(
                                    absolutePath, storagePath, frame)
                                if os.path.exists(physical_path):
                                    os.remove(physical_path)

                physical_path = os.path.join(
                    absolutePath, storagePath, asset.file_location)
                local_db_session.query(ParentStage).filter(
                    ParentStage.child_asset_id == id).delete(synchronize_session=False)
                local_db_session.query(MediaTag).filter(
                    MediaTag.asset_id == id).delete(synchronize_session=False)
                local_db_session.query(AssetLicense).filter(
                    AssetLicense.asset_id == id).delete(synchronize_session=False)
                local_db_session.query(AssetUsage).filter(
                    AssetUsage.asset_id == id).delete(synchronize_session=False)

                for multiframe_media in local_db_session.query(AssetModel).filter(AssetModel.description.like(f"%{asset.file_location}%")).all():
                    attributes = json.loads(multiframe_media.description)
                    for i, frame in enumerate(attributes['frames']):
                        if "?" in frame:
                            attributes['frames'][i] = frame[:frame.index("?")]
                    if asset.file_location in attributes['frames']:
                        attributes['frames'].remove(asset.file_location)
                    multiframe_media.description = json.dumps(attributes)
                    local_db_session.flush()

                local_db_session.delete(asset)
                local_db_session.flush()
                local_db_session.commit()
            else:
                return DeleteMedia(success=False, message="Media not found!")

            if os.path.exists(physical_path):
                os.remove(physical_path)
            else:
                return DeleteMedia(success=True, message="Media deleted successfully but file not existed on storage!")

        return DeleteMedia(success=True, message="Media deleted successfully!")
Esempio n. 6
0
def role_super_admin(fn, instance, args, kwargs):
    code, error, user, x, y, t = current_user()
    if code != 200:
        abort(code, error)

    if (user.role & SUPER_ADMIN) != 0:
        return fn(*args, **kwargs)
    app.logger.warning(
        "Denied access to fn {0} for user {1}:{2}, user is not role {3}".
        format(str(fn), user.id, user.email, ROLES[SUPER_ADMIN]))
Esempio n. 7
0
def role_participant(fn, instance, args, kwargs):
    code, error, user, x, y, t = current_user()
    if code != 200:
        abort(code, error)

    if (user.role & PARTICIPANT) != 0:
        return fn(*args, **kwargs)
    app.logger.warning(
        "Denied access to fn {0} for user {1}:{2}, user is not role {3}".
        format(str(fn), user.id, user.email, ROLES[PROVIDER]))
Esempio n. 8
0
def role_attendee(fn, instance, args, kwargs):
    code, error, user, x, y, t = current_user()
    if code != 200:
        abort(code, error)

    if (user.role & ATTENDEE) != 0:
        return fn(*args, **kwargs)
    app.logger.warning(
        "Denied access to fn {0} for user {1}:{2}, user is not role {3}".
        format(str(fn), user.id, user.email, ROLES[RESIDENT]))
Esempio n. 9
0
def resolve_notifications(self, info):
    code, error, user, timezone = current_user()
    notifications = []
    if user:
        mediaUsages = [
            Notification(type=NotificationType.MEDIA_USAGE, mediaUsage=x)
            for x in DBSession.query(AssetUsageModel).filter(
                AssetUsageModel.approved == False).filter(
                    AssetUsageModel.asset.has(owner_id=user.id)).all()
        ]
        notifications += mediaUsages
    return notifications
Esempio n. 10
0
 def mutate(self, info, id, stage_id):
     id = from_global_id(id)[1]
     with ScopedSession() as local_db_session:
         asset = local_db_session.query(AssetModel).get(id)
         if asset:
             code, error, user, timezone = current_user()
             stage = local_db_session.query(StageModel).get(stage_id)
             if stage:
                 asset.stages.append(ParentStage(stage_id=stage_id))
                 local_db_session.flush()
                 local_db_session.commit()
                 return QuickAssignMutation(success=True)
     return QuickAssignMutation(success=False, message="Stage not found")
Esempio n. 11
0
    def mutate(self, info, id, name):
        with ScopedSession() as local_db_session:
            code, error, user, timezone = current_user()
            id = from_global_id(id)[1]
            stage = local_db_session.query(StageModel).filter(
                StageModel.id == id).first()
            if stage:
                local_db_session.expunge(stage)
                make_transient(stage)
                original_stage_id = id
                stage.id = None
                stage.name = name
                stage.owner_id = user.id
                shortname = re.sub('\s+', '-',
                                   re.sub('[^A-Za-z0-9 ]+', '', name)).lower()

                suffix = ""
                while True:
                    existedStages = DBSession.query(StageModel).filter(
                        StageModel.file_location ==
                        f"{shortname}{suffix}").first()
                    if existedStages:
                        suffix = int(suffix or 0) + 1
                    else:
                        break
                stage.file_location = f"{shortname}{suffix}"
                local_db_session.add(stage)
                local_db_session.flush()
                new_stage_id = stage.id

                # Clone media and attributes, player accesses,...
                for ps in local_db_session.query(ParentStage).filter(
                        ParentStage.stage_id == original_stage_id).all():
                    local_db_session.add(
                        ParentStage(stage_id=new_stage_id,
                                    child_asset_id=ps.child_asset_id))
                for attribute in local_db_session.query(
                        StageAttributeModel).filter(
                            StageAttributeModel.stage_id ==
                            original_stage_id).all():
                    local_db_session.add(
                        StageAttributeModel(stage_id=new_stage_id,
                                            name=attribute.name,
                                            description=attribute.description))
                local_db_session.flush()
                local_db_session.commit()
                return DuplicateStage(success=True,
                                      new_stage_id=to_global_id(
                                          'Stage', new_stage_id))
            else:
                raise Exception("Stage not found!")
Esempio n. 12
0
 def mutate(self, info, asset_id, note=None):
     asset_id = from_global_id(asset_id)[1]
     with ScopedSession() as local_db_session:
         asset = local_db_session.query(AssetModel).get(asset_id)
         if asset:
             code, error, user, timezone = current_user()
             asset_usage = AssetUsageModel(user_id=user.id,
                                           asset_id=asset_id,
                                           note=note)
             if asset.copyright_level == 2:
                 asset_usage.approved = False
             else:
                 asset_usage.approved = True
             local_db_session.add(asset_usage)
             local_db_session.flush()
             local_db_session.commit()
     return ConfirmPermission(success=True)
Esempio n. 13
0
    def mutate(self, info, base64, filename):
        code, error, user, timezone = current_user()
        if not user.role in (ADMIN, SUPER_ADMIN, PLAYER):
            raise Exception("You don't have permission to upload media")

        # Save base64 to file
        filename, file_extension = os.path.splitext(filename)
        unique_filename = uuid.uuid4().hex + file_extension
        subpath = 'media'
        mediaDirectory = os.path.join(absolutePath, storagePath, subpath)
        if not os.path.exists(mediaDirectory):
            os.makedirs(mediaDirectory)
        with open(os.path.join(mediaDirectory, unique_filename), "wb") as fh:
            fh.write(b64decode(base64.split(',')[1]))

        file_location = os.path.join(subpath, unique_filename)
        return UploadFile(url=file_location)
Esempio n. 14
0
 def mutate(self, info, inbound):
     data = graphql_utils.input_to_dictionary(inbound)
     code,error,user,timezone = current_user()
     if not user.role in (ADMIN,SUPER_ADMIN) :
             raise Exception("Permission denied!")
     with ScopedSession() as local_db_session:
         # Delete all existed user's sessions
         local_db_session.query(UserSession).filter(UserSession.user_id==data['id']).delete()
         # Delete all stages created by this user
         local_db_session.query(StageAttributeModel).filter(StageAttributeModel.stage.has(StageModel.owner_id==data['id'])).delete(synchronize_session='fetch')
         local_db_session.query(StageModel).filter(StageModel.owner_id==data['id']).delete()
         # Change the owner of media uploaded by this user to the one who process the delete
         # Because delete the media would cause impact to other stage, this would be a workaround for now
         local_db_session.query(AssetModel).filter(AssetModel.owner_id==data['id']).update({AssetModel.owner_id: user.id})
         # Delete the actual user
         local_db_session.query(UserModel).filter(UserModel.id==data['id']).delete()
         local_db_session.commit()
     return DeleteUser(success=True)
Esempio n. 15
0
    def mutate(self, info, users, stageIds=[]):
        code,error,user,timezone = current_user()
        if not user.role in (ADMIN,SUPER_ADMIN) :
            raise Exception("Permission denied!")
        ids = []
        with ScopedSession() as local_db_session:
            duplicated = []
            for i in range(len(users) - 1):
                for j in range(i + 1, len(users)):
                    if users[i].username == users[j].username:
                        duplicated.append(users[i].username)
            if duplicated:
                raise Exception('Duplicated username: '******', '.join(duplicated))

            existed = [user.username for user in DBSession.query(UserModel).filter(UserModel.username.in_([x.username for x in users])).all()]
            if existed:
                raise Exception('Username already existed: ' + ', '.join(existed))
            for item in users:
                user = UserModel(
                    username=item.username,
                    active=True,
                    role=GUEST
                )
                # Add validation for non-empty passwords, etc.
                user.password = encrypt(item.password)
                local_db_session.add(user)
                local_db_session.flush()
                ids.append(user.id)
            
            # Now assigns users into stages
            stages = DBSession.query(StageModel).filter(StageModel.id.in_(stageIds)).all()
            for stage in stages:
                player_access = stage.attributes.filter(StageAttributeModel.name == 'playerAccess').first()
                if player_access:
                    accesses = json.loads(player_access.description)
                    for user_id in ids:
                        if user_id not in accesses[0]:
                            accesses[0].append(user_id) # append user id to player ids
                    player_access.description = json.dumps(accesses)
                    local_db_session.flush()

            local_db_session.commit()
        users = DBSession.query(UserModel).filter(UserModel.id.in_(ids)).all()
        return BatchUserCreation(users=users)
Esempio n. 16
0
    def resolve_search(self, info, inbound):
        """ Get user from JWT token. """
        code,error,this_user,timezone = current_user()
        if code != 200:
            raise Exception(error)

        """ Compare it with params. If current user is an admin, allow lookup
            of other users. 
        """
        if inbound:
            data = graphql_utils.input_to_dictionary(inbound)
            lookup_user = DBSession.query(UserModel).filter_by(data).first()

        access_token = request.headers.get(app.config['JWT_HEADER_NAME'],None)
        #app.logger.info("access token:{0}".format(access_token))

        # If latest user session access token doesn't match, kick them out.
        user_session = DBSession.query(UserSession).filter(
            UserSession.user_id==user.id).order_by(
            UserSession.recorded_time.desc()).first()

        if not user_session:
            raise Exception('Bad user session')

        if (user_session.access_token != access_token):
            TNL.add(access_token)
            # No. user session may be valid, from a newer login on a different device.
            #TNL.add(user_session.refresh_token)
            #TNL.add(user_session.access_token)
            raise Exception('Access token is invalid')

        self.result = {
            'user_id':user.id,'role':user.role,
            'phone':user.phone,
            'first_name':user.first_name, 'last_name': user.last_name,
            'email':user.email,
            'timezone':timezone,
            'groups':[],
            'username':user.username,
            }
        #return result
        return graphql_utils.json2obj(self.result)
Esempio n. 17
0
    def mutate(self, info, id):
        with ScopedSession() as local_db_session:
            scene = local_db_session.query(SceneModel).filter(
                SceneModel.id == id).first()
            if scene:
                code, error, user, timezone = current_user()
                if not user.role in (ADMIN, SUPER_ADMIN):
                    if not user.id == scene.owner_id:
                        return DeleteScene(
                            success=False,
                            message=
                            "Only scene owner or admin can delete this scene!")

                scene.active = False
                local_db_session.flush()
                local_db_session.commit()
            else:
                return DeleteScene(success=False, message="Scene not found!")

        return DeleteScene(success=True, message="Scene deleted successfully!")
Esempio n. 18
0
    def mutate(self, info, id):
        with ScopedSession() as local_db_session:
            performance = local_db_session.query(PerformanceModel).filter(
                PerformanceModel.id == id).first()
            if performance:
                code, error, user, timezone = current_user()
                if not user.role in (ADMIN, SUPER_ADMIN):
                    if not user.id == performance.owner_id:
                        raise Exception(
                            "Only stage owner or Admin can delete this record!"
                        )

                local_db_session.query(Event).filter(
                    Event.performance_id == id).delete(
                        synchronize_session=False)
                local_db_session.delete(performance)
                local_db_session.flush()
                local_db_session.commit()
            else:
                raise Exception("Performance not found!")

        return DeletePerformance(success=True)
Esempio n. 19
0
    def mutate(self, info, id):
        current_user_id = get_jwt_identity()
        with ScopedSession() as local_db_session:
            performance = local_db_session.query(PerformanceModel).filter(
                PerformanceModel.id == id).first()
            if performance:
                code, error, user, timezone = current_user()
                if not user.role in (ADMIN, SUPER_ADMIN):
                    if not user.id == performance.stage.owner_id:
                        raise Exception(
                            "Only stage owner or Admin can save a recording!")

                saved_on = datetime.utcnow()

                events = local_db_session.query(Event)\
                    .filter(Event.topic.like("%/{}/%".format(performance.stage.file_location)))\
                    .filter(Event.created > performance.created_on)\
                    .filter(Event.created < saved_on)

                if events.count() > 0:
                    # Clone each events that happend between the recording session
                    for event in events.all():
                        local_db_session.expunge(event)
                        make_transient(event)
                        event.id = None
                        event.performance_id = performance.id
                        local_db_session.add(event)
                else:
                    raise Exception("Nothing to record!")

                performance.saved_on = saved_on
                local_db_session.flush()
                local_db_session.commit()
            else:
                raise Exception("Performance not found!")

            recording = local_db_session.query(PerformanceModel).filter(
                PerformanceModel.id == performance.id).first()
            return SaveRecording(recording=recording)
Esempio n. 20
0
 def mutate(self, info, id, approved):
     id = from_global_id(id)[1]
     with ScopedSession() as local_db_session:
         asset_usage = local_db_session.query(AssetUsageModel).get(id)
         asset_id = asset_usage.asset_id
         if asset_usage:
             code, error, user, timezone = current_user()
             if not user.role in (ADMIN, SUPER_ADMIN):
                 if not user.id == asset_usage.asset.owner_id:
                     return ConfirmPermission(
                         success=False,
                         message=
                         "Only media owner or admin can delete this media!")
             if approved:
                 asset_usage.approved = True
                 asset_usage.seen = True
             else:
                 local_db_session.delete(asset_usage)
             local_db_session.flush()
     permissions = DBSession.query(AssetUsageModel).filter(
         AssetUsageModel.asset_id == asset_id).all()
     return ConfirmPermission(success=True, permissions=permissions)
Esempio n. 21
0
    def mutate(self, info, id, name=None, description=None):
        if not name:
            raise Exception("Please pick a name!")

        current_user_id = get_jwt_identity()
        with ScopedSession() as local_db_session:
            performance = local_db_session.query(PerformanceModel).filter(
                PerformanceModel.id == id).first()
            if performance:
                code, error, user, timezone = current_user()
                if not user.role in (ADMIN, SUPER_ADMIN):
                    if not user.id == performance.stage.owner_id:
                        raise Exception(
                            "Only stage owner or Admin can update archived performance information!"
                        )

                performance.name = name
                performance.description = description
                local_db_session.flush()
                local_db_session.commit()
            else:
                raise Exception("Performance not found!")

            return UpdatePerformance(success=True)
Esempio n. 22
0
 def resolve_whoami(self, info):
     code, error, user, timezone = current_user()
     return user
Esempio n. 23
0
 def resolve_currentUser(self, info):
     code,error,user,timezone = current_user()
     if error:
         raise Exception(error)
     return user
Esempio n. 24
0
    def mutate(self, info, input):
        name, urls, media_type, copyright_level, user_ids, stage_ids, tags, w, h = itemgetter(
            'name', 'urls', 'media_type', 'copyright_level', 'user_ids',
            'stage_ids', 'tags', 'w', 'h')(input)
        current_user_id = get_jwt_identity()
        with ScopedSession() as local_db_session:
            asset_type = local_db_session.query(AssetTypeModel).filter(
                AssetTypeModel.name == media_type).first()
            if not asset_type:
                asset_type = AssetTypeModel(name=media_type,
                                            file_location=media_type)
                local_db_session.add(asset_type)
                local_db_session.flush()

            if 'id' in input:
                id = from_global_id(input['id'])[1]
                asset = local_db_session.query(AssetModel).filter(
                    AssetModel.id == id).first()

                if asset:
                    code, error, user, timezone = current_user()
                    if not user.role in (ADMIN, SUPER_ADMIN):
                        if not user.id == asset.owner_id:
                            raise Exception(
                                "You don't have permission to edit this media")

            else:
                asset = AssetModel(owner_id=current_user_id)
                local_db_session.add(asset)

            if asset:
                asset.name = name
                asset.asset_type = asset_type
                file_location = urls[0]
                if file_location:
                    if "?" in file_location:
                        file_location = file_location[:file_location.index("?"
                                                                           )]
                    if asset.id and file_location != asset.file_location and '/' not in file_location:
                        existedAsset = local_db_session.query(
                            AssetModel).filter(
                                AssetModel.file_location == file_location
                            ).filter(AssetModel.id != asset.id).first()
                        if existedAsset:
                            raise Exception(
                                "Stream with the same key already existed, please pick another unique key!"
                            )
                    asset.file_location = file_location
                else:
                    asset.file_location = uuid.uuid4()
                asset.copyright_level = copyright_level
                asset.updated_on = datetime.utcnow()
                local_db_session.flush()

            if urls:
                if not asset.description:
                    asset.description = "{}"
                attributes = json.loads(asset.description)
                if not 'frame' in attributes or attributes['frames']:
                    attributes['frames'] = []

                asset.size = 0
                for url in urls:
                    attributes['frames'].append(url)
                    full_path = os.path.join(absolutePath, storagePath, url)
                    try:
                        size = os.path.getsize(full_path)
                    except:
                        size = 0  # file not exist
                    asset.size += size

                if len(urls) > 1:
                    attributes['multi'] = True
                else:
                    attributes['multi'] = False
                    attributes['frames'] = []
                attributes['w'] = w
                attributes['h'] = h
                if asset_type.name == 'stream' and '/' not in file_location:
                    attributes['isRTMP'] = True

                if 'voice' in input:
                    voice = input['voice']
                    if voice and voice.voice:
                        attributes['voice'] = voice
                    elif 'voice' in attributes:
                        del attributes['voice']

                if 'link' in input:
                    link = input['link']
                    if link and link.url:
                        attributes['link'] = link
                    elif 'link' in attributes:
                        del attributes['link']

                asset.description = json.dumps(attributes)
                local_db_session.flush()

            if stage_ids != None:
                asset.stages.delete()
                for id in stage_ids:
                    asset.stages.append(ParentStage(stage_id=id))

            if user_ids != None:
                granted_permissions = asset.permissions.all()
                for permission in granted_permissions:
                    if isinstance(permission, AssetUsageModel):
                        if permission.user_id not in user_ids and permission.approved == True:
                            asset.permissions.remove(permission)
                            local_db_session.delete(permission)
                for user_id in user_ids:
                    permission = local_db_session.query(
                        AssetUsageModel).filter(
                            AssetUsageModel.asset_id == asset.id,
                            AssetUsageModel.user_id == user_id).first()
                    if not permission:
                        permission = AssetUsageModel(user_id=user_id)
                        asset.permissions.append(permission)
                    permission.approved = True
                local_db_session.flush()

            if tags:
                asset.tags.delete()
                for tag in tags:
                    tag_model = local_db_session.query(Tag).filter(
                        Tag.name == tag).first()
                    if not tag_model:
                        tag_model = Tag(name=tag)
                        local_db_session.add(tag_model)
                        local_db_session.flush()
                    asset.tags.append(MediaTag(tag_id=tag_model.id))

            local_db_session.flush()
            local_db_session.commit()
            asset = local_db_session.query(AssetModel).filter(
                AssetModel.id == asset.id).first()
            return SaveMedia(asset=asset)