Ejemplo n.º 1
0
class Tap(WigoModel):
    TTL = timedelta(days=2)

    indexes = (('user:{user_id}:tapped={tapped_id}', False, True), )

    user_id = LongType(required=True)
    tapped_id = LongType(required=True)

    def ttl(self):
        return self.tapped.group.get_day_end(self.created) - datetime.utcnow()

    @property
    @field_memoize('tapped_id')
    def tapped(self):
        return User.find(self.tapped_id)

    def validate(self, partial=False, strict=False):
        super(Tap, self).validate(partial, strict)

        if not self.user.is_friend(self.tapped_id):
            raise ValidationException('Not friends')

        if Configuration.ENVIRONMENT != 'dev' and self.user.is_tapped(
                self.tapped_id):
            raise ValidationException('Already tapped')
Ejemplo n.º 2
0
class DeviceInfo(Model):
    device_id = IntType(required=True)
    device_sn = StringType(required=True)
    software_ver = LongType(required=True)
    hardware_ver = LongType(required=True)
    system_len = IntType(required=True)
    memory_len = IntType(required=True)
    channel_count = IntType(required=True, default=2)
    cell_count = IntType(required=True, default=0)
    ch1_status = ModelType(DeviceInfoStatus, default=DeviceInfoStatus())
    ch2_status = ModelType(DeviceInfoStatus, default=DeviceInfoStatus())

    def __init__(self, modbus_data=None):
        super(DeviceInfo, self).__init__()
        if modbus_data is not None:
            self.set_from_modbus_data(modbus_data)

    def get_status(self, channel):
        return self.ch1_status if channel == 0 else self.ch2_status

    def set_from_modbus_data(self, data):
        self.device_id = data[0]
        self.device_sn = data[1].split('\0')[0]
        self.software_ver = data[2]
        self.hardware_ver = data[3]
        self.system_len = data[4]
        self.memory_len = data[5]
        self.ch1_status = DeviceInfoStatus(data[6])
        self.ch2_status = DeviceInfoStatus(data[7])

        for (device_id, cell_count) in DeviceIdCellCount:
            if device_id == self.device_id:
                self.cell_count = cell_count
Ejemplo n.º 3
0
class Block(WigoModel):
    indexes = (('user:{user_id}:blocked={blocked_id}', False, False), )

    user_id = LongType(required=True)
    blocked_id = LongType(required=True)
    type = StringType()

    @property
    @field_memoize('tapped_id')
    def blocked(self):
        return User.find(self.blocked_id)

    def validate(self, partial=False, strict=False):
        super(Block, self).validate(partial, strict)
        if self.user.is_blocked(self.blocked):
            raise ValidationException('Already blocked')

    def save(self):
        super(Block, self).save()

        Friend({
            'user_id': self.user_id,
            'blocked_id': self.blocked_id
        }).delete()

        if self.type:
            self.db.sorted_set_incr_score(skey('blocked', self.type),
                                          self.blocked_id)

        return self
Ejemplo n.º 4
0
Archivo: embed.py Proyecto: mlys/gsapi
class Pth(Embs):
    d_c = StringType(description='Target document class "_c".')
    lnkTypId = LongType(description='Link Type Id.')
    lnkTitle = StringType(description='Link Title.')
    lnkNote = StringType(description='Link Note.')
    lnks = ListType(ModelType(Lnk))
    ids = ListType(LongType())
Ejemplo n.º 5
0
class NewPublicKey(Model):
    """Input structure for a new public key."""

    resource_id = UUIDType(required=True)
    resource_type = StringType(required=True)
    key_id = UUIDType()

    expire_date = DateTimeType(serialized_format=helpers.RFC3339Milli,
                               tzd=u'utc')
    label = StringType(required=True)
    fingerprint = StringType()
    key = StringType()
    type = StringType()

    # JWT parameters
    kty = StringType()  # rsa / ec
    use = StringType()  # sig / enc
    alg = StringType()  # algorithm
    # Elliptic curve public key parameters (rfc7518 6.2.1)
    crv = StringType()
    x = LongType()
    y = LongType()

    class Options:
        serialize_when_none = False
Ejemplo n.º 6
0
class EventAttendee(WigoModel):
    user_id = LongType(required=True)
    event_id = LongType(required=True)

    def validate(self, partial=False, strict=False):
        super(EventAttendee, self).validate(partial, strict)
        if not self.user.can_see_event(self.event):
            raise ValidationException('Not invited')

    def index(self):
        super(EventAttendee, self).index()

        user = self.user
        event = self.event

        # check if the user is switching events for the date the event is on
        current_event_id = user.get_attending_id(event)
        if current_event_id and current_event_id != event.id:
            EventAttendee({'event_id': current_event_id, 'user_id': user.id}).delete()

        with self.db.transaction(commit_on_select=False):
            # first update the global state of the event
            attendees_key = skey(event, 'attendees')
            self.db.sorted_set_add(attendees_key, user.id, epoch(self.created))
            self.db.expire(attendees_key, event.ttl())

            # now update the users view of the events
            # record the exact event the user is currently attending
            user.set_attending(event)

            # record current user as an attendee
            attendees_key = user_attendees_key(user, event)
            self.db.sorted_set_add(attendees_key, user.id, 'inf')
            self.db.expire(attendees_key, event.ttl())

        # record the event into the events the user can see
        with self.db.transaction(commit_on_select=False):
            event.update_global_events()
            event.update_user_events(user)

    def remove_index(self):
        super(EventAttendee, self).remove_index()
        user = self.user
        event = self.event

        # the event may have been deleted
        if event:
            with self.db.transaction(commit_on_select=True):
                user.remove_attending(event)
                self.db.sorted_set_remove(skey(event, 'attendees'), user.id)
                self.db.sorted_set_remove(user_attendees_key(user, event), user.id)

            with self.db.transaction(commit_on_select=True):
                event.update_global_events()
                event.update_user_events(user)
        else:
            user.remove_attending(event)
Ejemplo n.º 7
0
class MultipleThreadListResponse(PaginationResponse):
    forum = ModelType(ForumResponse)
    subforum = ListType(ModelType(ForumResponse))
    tags = ListType(StringType)
    thread = ListType(ModelType(ThreadResponse))
    thread_num = LongType()
    top_feature = ListType(ModelType(HighlightResponse))
    top_thread = ListType(ModelType(ThreadResponse))
    total_thread = LongType()
Ejemplo n.º 8
0
class AdditionalItemResponse(Model):
    dateline = LongType()
    discount = FloatType()
    discounted_price = LongType()
    item_price = LongType()
    last_post = LongType()
    post_title = StringType()
    thread_id = StringType()
    thread_title = StringType()
    thread_type = IntType()
    thumbnail = StringType()
Ejemplo n.º 9
0
Archivo: rdt.py Proyecto: mlys/gsapi
class Rdt(Mod):
    '''
        Robust datetime
        Date, given in format YYYY-MM-DD (with the year), or --MM-DD (without the year).
        Example:
            July 4, 1980: 
                1980-07-04
            December 13th, with no year specified: 
                '--12-13'
    '''
    # make yaml Rdt.log, Rdt.event, Rdt.todo, Rdt.anniverary, etc

    y = IntType(description="Year ie, 2012")
    ym = IntType(description="YearMonth year+month, ie, 201207 or -60710")
    ymd = IntType(description="YearMonthDay year+month+day, ie, 20120730")
    isoDate = StringType(description="Date in ISO yyyymmdd")
    isoTime = StringType(description="Time in ISO hhss")
    tz = StringType(description="Timezone ISO UTC UTC in form of: [+-]hh:mm")

    instance = StringType(
        description="Instance b=begin, e=end, l=lap, m=milestone")
    period = StringType(description="Period b=before, a=after, c=circa/close")

    note = StringType()

    valDelta0 = LongType()  # in secs +/- year zero
    valDelta1970 = LongType()  # in secs +/- year 1970

    @property
    def vValDelta1970(self):
        '''Generate datetime, delta 1970'''
        pass

    @property
    def vValDelta0(self):
        '''Generate datetime, delta 0'''
        pass

    @property
    def vDatetimeDelta1970(self):
        '''Generate datetime, delta 1970'''
        pass

    @property
    def vDatetimeDelta0(self):
        '''Generate datetime, delta 0'''
        pass

    # todo
    ''' create method to generate val based on supplied values'''
    meta = {
        '_c': 'Rdt',
    }
Ejemplo n.º 10
0
class Message(WigoPersistentModel):
    indexes = (
        ('user:{user_id}:messages', False, False),
        ('user:{user_id}:conversations={to_user_id}', False, False),
        ('user:{user_id}:conversation:{to_user_id}', False, False),
        ('user:{to_user_id}:conversations={user_id}', False, False),
        ('user:{to_user_id}:conversation:{user_id}', False, False),
    )

    user_id = LongType(required=True)
    to_user_id = LongType(required=True)
    message = StringType(required=True)

    @property
    @field_memoize('to_user_id')
    def to_user(self):
        try:
            return User.find(self.to_user_id)
        except DoesNotExist:
            logger.warn('user {} not found'.format(self.to_user_id))
        return None

    @serializable(serialized_name='to_user', serialize_when_none=False)
    def to_user_ref(self):
        return self.ref_field(User, 'to_user_id')

    def validate(self, partial=False, strict=False):
        super(Message, self).validate(partial, strict)
        if not self.user.is_friend(self.to_user_id):
            raise ValidationException('Not friends')

    def index(self):
        super(Message, self).index()
        with self.db.transaction(commit_on_select=False):
            self.db.set(
                skey(self.user, 'conversation', self.to_user.id,
                     'last_message'), self.id)
            self.db.set(
                skey(self.to_user, 'conversation', self.user.id,
                     'last_message'), self.id)

    @classmethod
    def delete_conversation(cls, user, to_user):
        from server.db import wigo_db

        with wigo_db.transaction(commit_on_select=False):
            wigo_db.sorted_set_remove(skey(user, 'conversations'), to_user.id)
            wigo_db.delete(skey(user, 'conversation', to_user.id))
            user.track_meta('last_message_change')
            to_user.track_meta('last_message_change')
Ejemplo n.º 11
0
class ModMixin(_Model):
    count = LongType()

    liked = ListType(ObjectIdType(ObjectId))
    # create RatingType
    # https   ://developers.google.com/gdata/docs/2.0/elements#gdRating
    rating = IntType()
    followers = ListType(ObjectIdType(ObjectId))
    favorited = ListType(ObjectIdType(ObjectId))

    reviews = ListType(ModelType(Review))

    tags = ListType(ModelType(Tag))

    tels = ListType(ModelType(Tel), description='Telephones')
    emails = ListType(ModelType(Email), description='Emails')
    ims = ListType(ModelType(Im), description='Instant Message Network')

    urls = ListType(URLType(), description='Urls associated with this doc.')
    rdts = ListType(ModelType(Rdt))
    desc = StringType(description='Description')
    notes = ListType(ModelType(Note))

    shrs = ListType(
        ModelType(Shr),
        description=
        'Share List of Share docs that describe who and at what level/role this doc is shared with.'
    )

    # tos     : ie, parents
    tos = ListType(ModelType(Pth))

    # frs     : froms, ie, children
    frCount = IntType()
    frs = ListType(ModelType(Pth))
Ejemplo n.º 12
0
class UserDTO(Model):
    """ DTO for User """
    validation_message = BooleanType(default=True)
    id = LongType()
    username = StringType()
    role = StringType()
    mapping_level = StringType(serialized_name='mappingLevel',
                               validators=[is_known_mapping_level])
    date_registered = StringType(serialized_name='dateRegistered')
    total_time_spent = IntType(serialized_name='totalTimeSpent')
    time_spent_mapping = IntType(serialized_name='timeSpentMapping')
    time_spent_validating = IntType(serialized_name='timeSpentValidating')
    projects_mapped = IntType(serialized_name='projectsMapped')
    tasks_mapped = IntType(serialized_name='tasksMapped')
    tasks_validated = IntType(serialized_name='tasksValidated')
    tasks_invalidated = IntType(serialized_name='tasksInvalidated')
    email_address = EmailType(serialized_name='emailAddress',
                              serialize_when_none=False)
    is_email_verified = EmailType(serialized_name='isEmailVerified',
                                  serialize_when_none=False)
    is_expert = BooleanType(serialized_name='isExpert',
                            serialize_when_none=False)
    twitter_id = StringType(serialized_name='twitterId')
    facebook_id = StringType(serialized_name='facebookId')
    linkedin_id = StringType(serialized_name='linkedinId')
Ejemplo n.º 13
0
    class Player(Model):
        id = LongType()
        display_name = StringType()

        class Options:
            roles = {
                "default": blacklist("id")
            }
Ejemplo n.º 14
0
class ListedUser(Model):
    """ Describes a user within the User List """

    id = LongType()
    username = StringType()
    role = StringType()
    mapping_level = StringType(serialized_name="mappingLevel")
    picture_url = StringType(serialized_name="pictureUrl")
Ejemplo n.º 15
0
class SliceProfile(Model):
    sliceProfileId = StringType(required=True)
    sNSSAIList = ListType(StringType(required=True))
    pLMNIdList = ListType(StringType(required=True))
    perfReq = ModelType(PerfReq, required=True)
    maxNumberofUEs = LongType()
    coverageAreaTAList = ListType(IntType())
    latency = IntType()
    uEMobilityLevel = StringType()
    resourceSharingLevel = StringType()
Ejemplo n.º 16
0
class StatementLegacyData(BetfairModel):
    avg_price = FloatType()
    bet_size = FloatType()
    bet_type = StringType()
    bet_category_type = StringType()
    commission_rate = StringType()
    event_id = LongType()
    event_type_id = LongType()
    full_market_name = StringType()
    gross_bet_amount = FloatType()
    market_name = StringType()
    market_type = StringType()
    placed_date = DateTimeType()
    selection_id = LongType()
    selection_name = StringType()
    start_date = DateTimeType()
    transaction_type = StringType()
    transaction_id = LongType()
    win_lose = StringType()
Ejemplo n.º 17
0
class SliceProfile(Model):
    """Reference 3GPP TS 28.541 V16.5.0, Section 6.3.4."""
    sliceProfileId = StringType(required=True)
    sNSSAIList = ListType(StringType(required=True))
    pLMNIdList = ListType(StringType(required=True))
    perfReq = ModelType(PerfReq, required=True)
    maxNumberofUEs = LongType()
    coverageAreaTAList = ListType(IntType())
    latency = IntType()
    uEMobilityLevel = StringType()
    resourceSharingLevel = StringType()
Ejemplo n.º 18
0
class UserDTO(Model):
    """ DTO for User """

    validation_message = BooleanType(default=True)
    id = LongType()
    username = StringType()
    role = StringType()
    mapping_level = StringType(
        serialized_name="mappingLevel", validators=[is_known_mapping_level]
    )
    date_registered = UTCDateTimeType(serialized_name="dateRegistered")
    tasks_mapped = IntType(serialized_name="tasksMapped")
    tasks_validated = IntType(serialized_name="tasksValidated")
    tasks_invalidated = IntType(serialized_name="tasksInvalidated")
    email_address = EmailType(serialized_name="emailAddress")
    is_email_verified = EmailType(
        serialized_name="isEmailVerified", serialize_when_none=False
    )
    is_expert = BooleanType(serialized_name="isExpert", serialize_when_none=False)
    twitter_id = StringType(serialized_name="twitterId")
    facebook_id = StringType(serialized_name="facebookId")
    linkedin_id = StringType(serialized_name="linkedinId")
    slack_id = StringType(serialized_name="slackId")
    irc_id = StringType(serialized_name="ircId")
    skype_id = StringType(serialized_name="skypeId")
    city = StringType(serialized_name="city")
    country = StringType(serialized_name="country")
    name = StringType(serialized_name="name")
    picture_url = StringType(serialized_name="pictureUrl")
    default_editor = StringType(serialized_name="defaultEditor")
    mentions_notifications = BooleanType(serialized_name="mentionsNotifications")
    comments_notifications = BooleanType(serialized_name="commentsNotifications")
    projects_notifications = BooleanType(serialized_name="projectsNotifications")

    # these are read only
    missing_maps_profile = StringType(serialized_name="missingMapsProfile")
    osm_profile = StringType(serialized_name="osmProfile")
    gender = StringType(
        serialized_name="gender",
        choices=("MALE", "FEMALE", "SELF_DESCRIBE", "PREFER_NOT"),
    )
    self_description_gender = StringType(
        serialized_name="selfDescriptionGender", default=None
    )

    def validate_self_description(self, data, value):
        if (
            data["gender"] == "SELF_DESCRIBE"
            and data["self_description_gender"] is None
        ):
            raise ValueError("selfDescription field is not defined")
        return value
Ejemplo n.º 19
0
class NewTeamDTO(Model):
    """ Describes a JSON model to create a new team """

    creator = LongType(required=True)
    organisation_id = IntType(required=True)
    name = StringType(required=True)
    description = StringType()
    invite_only = BooleanType(default=False,
                              serialized_name="inviteOnly",
                              required=True)
    visibility = StringType(required=True,
                            validators=[validate_team_visibility],
                            serialize_when_none=False)
Ejemplo n.º 20
0
class UpdateTeamDTO(Model):
    """ Describes a JSON model to update a team """

    creator = LongType()
    organisation = StringType()
    organisation_id = IntType()
    name = StringType()
    logo = StringType()
    description = StringType()
    invite_only = BooleanType(default=False, serialized_name="inviteOnly")
    visibility = StringType(validators=[validate_team_visibility],
                            serialize_when_none=False)
    members = ListType(ModelType(TeamMembersDTO), serialize_when_none=False)
Ejemplo n.º 21
0
class Invite(WigoModel):
    TTL = timedelta(days=2)

    indexes = (
        ('event:{event_id}:invited={invited_id}', False, True),
        ('event:{event_id}:user:{user_id}:invited={invited_id}', False, True),
    )

    event_id = LongType(required=True)
    user_id = LongType(required=True)
    invited_id = LongType(required=True)

    def ttl(self):
        if self.event and self.event.expires:
            return (self.event.expires + timedelta(days=2)) - datetime.utcnow()
        else:
            return super(Invite, self).ttl()

    @property
    @field_memoize('invited_id')
    def invited(self):
        return User.find(self.invited_id)

    def validate(self, partial=False, strict=False):
        super(Invite, self).validate(partial, strict)

        inviter = self.user
        invited = self.invited
        event = self.event

        if not inviter.is_friend(invited):
            raise ValidationException('Not friend')

        if not inviter.is_attending(event):
            raise ValidationException('Must be attending the event')

    def delete(self):
        pass
Ejemplo n.º 22
0
class Notification(WigoModel):
    TTL = timedelta(days=15)

    id = LongType()
    user_id = LongType(required=True)
    type = StringType(required=True)
    from_user_id = LongType()
    navigate = StringType()
    message = StringType(required=True)
    badge = StringType()

    properties = JsonType()

    @property
    @field_memoize('from_user_id')
    def from_user(self):
        try:
            return User.find(self.from_user_id)
        except DoesNotExist:
            logger.warn('user {} not found'.format(self.from_user_id))
        return None

    @serializable(serialized_name='from_user', serialize_when_none=False)
    def from_user_ref(self):
        return self.ref_field(User, 'from_user_id')

    def index(self):
        super(Notification, self).index()
        key = skey('user', self.user_id, 'notifs')
        primitive = self.to_primitive()
        self.db.sorted_set_add(key,
                               primitive,
                               epoch(self.created),
                               dt=dict,
                               replicate=False)
        self.db.clean_old(key, self.TTL)
Ejemplo n.º 23
0
Archivo: wdg.py Proyecto: mlys/gsapi
class Event(Wdg):
    '''https://developers.google.com/places/documentation/actions#event_details'''
    duration = LongType(description="Duration in seconds.")

    # start_time
    begOn = DateTimeType(description="Duration Duration in seconds.")
    url = URLType(description="A URL pointing to details about the event.")
    summary = StringType(
        description=
        "A textual description of the event. This property contains a string, the contents of which are not sanitized by the server. Your application should be prepared to prevent or deal with attempted exploits, if necessary."
    )

    meta = {
        'collection': 'wdgs',
        '_c': 'Event',
    }
Ejemplo n.º 24
0
class UserDTO(Model):
    """ DTO for User """
    id = LongType()
    username = StringType()
    role = StringType()
    mapping_level = StringType(serialized_name='mappingLevel',
                               validators=[is_known_mapping_level])
    tasks_mapped = IntType(serialized_name='tasksMapped')
    tasks_validated = IntType(serialized_name='tasksValidated')
    email_address = EmailType(serialized_name='emailAddress',
                              serialize_when_none=False)
    is_email_verified = EmailType(serialized_name='isEmailVerified',
                                  serialize_when_none=False)
    twitter_id = StringType(serialized_name='twitterId')
    facebook_id = StringType(serialized_name='facebookId')
    linkedin_id = StringType(serialized_name='linkedinId')
Ejemplo n.º 25
0
class WigoPersistentModel(WigoModel):
    id = LongType()

    @classmethod
    def memory_ttl(cls):
        return 60 * 60

    @serializable(serialized_name='$id')
    def id_for_ref(self):
        if self.id:
            return '{}:{}'.format(self.__class__.__name__, self.id)
        return None

    def persist(self):
        primitive = self.to_primitive()
        self.db.set(skey(self), primitive, self.ttl())
        model_cache.put(self.id, primitive, self.memory_ttl())

    def track_meta(self, key, value=None, expire=timedelta(days=60)):
        from server.db import wigo_db

        if value is None:
            value = time()

        meta_key = skey(self, 'meta')
        wigo_db.get_redis(True).hset(meta_key, key, value)
        if expire:
            wigo_db.get_redis(True).expire(meta_key, timedelta(days=60))

    def remove_meta(self, key):
        from server.db import wigo_db

        wigo_db.get_redis(True).hdel(skey(self, 'meta'), key)

    def get_meta(self, key):
        from server.db import wigo_db

        return wigo_db.get_redis().hget(skey(self, 'meta'), key)

    def __cmp__(self, other):
        return cmp(self.id, other.id)

    def __hash__(self):
        return hash(self.id)

    def __eq__(self, other):
        return other.__class__ == self.__class__ and self.id is not None and other.id == self.id
Ejemplo n.º 26
0
class PostResponse(Model):
    dateline = LongType()
    decoded = StringType()
    display_name = StringType()
    enable_reputation = IntType()
    is_donatur = BooleanType()
    is_vsl = BooleanType()
    pagetext = StringType()
    pagetext_noquote = StringType()
    post_id = StringType()
    post_userid = StringType()
    post_username = StringType()
    profilepicture = StringType()
    reputation_box = IntType()
    text = StringType()
    title = StringType()
    usertitle = StringType()
Ejemplo n.º 27
0
class HotThreadResponse(Model):
    display_name = StringType()
    first_post_id = StringType()
    forum_id = StringType()
    forum_name = StringType()
    hot_thread_start_timestamp = LongType()
    image = StringType()
    image_compact = StringType()
    is_subscribed = BooleanType()
    last_post_id = StringType()
    rating = FloatType()
    reply_count = LongType()
    shared_count = LongType()
    short_url = StringType()
    thread_id = StringType()
    thread_type = IntType()
    title = StringType()
    user_id = StringType()
    username = StringType()
    views = LongType()
    vote_num = LongType()
    vote_total = LongType()
Ejemplo n.º 28
0
        class Player(Model):
            id = LongType()

            @serializable(type=PlayerIdType())
            def player_id(self):
                return self.id
Ejemplo n.º 29
0
 class PlayerInfo(Model):
     id = LongType()
     display_name = StringType()
Ejemplo n.º 30
0
 class QuestionPack(Model):
     id = LongType()
     questions = ListType(ModelType(Question))
Ejemplo n.º 31
0
 def test_raises_error(self):
     field = LongType(required=True)
     with self.assertRaises(ConversionError):
         field.to_native(None)