desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Sets the active alternate setting of the current interface.
Arguments:
alternate: an alternate setting number or an Interface object.'
| def setAltInterface(self, alternate):
| if isinstance(alternate, Interface):
alternate = alternate.alternateSetting
self.dev.set_interface_altsetting(self.__claimed_interface, alternate)
|
'Retrieve the string descriptor specified by index
and langid from a device.
Arguments:
index: index of descriptor in the device.
length: number of bytes of the string (ignored)
langid: Language ID. If it is omitted, the first
language will be used.'
| def getString(self, index, length, langid=None):
| return util.get_string(self.dev, index, langid).encode('ascii')
|
'Retrieves a descriptor from the device identified by the type
and index of the descriptor.
Arguments:
desc_type: descriptor type.
desc_index: index of the descriptor.
len: descriptor length.
endpoint: ignored.'
| def getDescriptor(self, desc_type, desc_index, length, endpoint=(-1)):
| return control.get_descriptor(self.dev, length, desc_type, desc_index)
|
'Detach a kernel driver from the interface (if one is attached,
we have permission and the operation is supported by the OS)
Arguments:
interface: interface number or an Interface object.'
| def detachKernelDriver(self, interface):
| if isinstance(interface, Interface):
interface = interface.interfaceNumber
self.dev.detach_kernel_driver(interface)
|
'Open the device for use.
Returns a DeviceHandle object'
| def open(self):
| return DeviceHandle(self.dev)
|
'This function is required to return an iterable object which
yields an implementation defined device identification for each
USB device found in the system.
The device identification object is used as argument to other methods
of the interface.'
| def enumerate_devices(self):
| _not_implemented(self.enumerate_devices)
|
'Return the device descriptor of the given device.
The object returned is required to have all the Device Descriptor
fields accessible as member variables. They must be convertible (but
not required to be equal) to the int type.
dev is an object yielded by the iterator returned by the enumerate_devices()
method.'
| def get_device_descriptor(self, dev):
| _not_implemented(self.get_device_descriptor)
|
'Return a configuration descriptor of the given device.
The object returned is required to have all the Configuration Descriptor
fields acessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The dev parameter is the device identification object.
config is the logical index of the configuration (not the bConfigurationValue
field). By "logical index" we mean the relative order of the configurations
returned by the peripheral as a result of GET_DESCRIPTOR request.'
| def get_configuration_descriptor(self, dev, config):
| _not_implemented(self.get_configuration_descriptor)
|
'Return an interface descriptor of the given device.
The object returned is required to have all the Interface Descriptor
fields accessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The dev parameter is the device identification object.
The intf parameter is the interface logical index (not the bInterfaceNumber field)
and alt is the alternate setting logical index (not the bAlternateSetting value).
Not every interface has more than one alternate setting. In this case, the alt
parameter should be zero. config is the configuration logical index (not the
bConfigurationValue field).'
| def get_interface_descriptor(self, dev, intf, alt, config):
| _not_implemented(self.get_interface_descriptor)
|
'Return an endpoint descriptor of the given device.
The object returned is required to have all the Endpoint Descriptor
fields acessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The ep parameter is the endpoint logical index (not the bEndpointAddress
field) of the endpoint descriptor desired. dev, intf, alt and config are the same
values already described in the get_interface_descriptor() method.'
| def get_endpoint_descriptor(self, dev, ep, intf, alt, config):
| _not_implemented(self.get_endpoint_descriptor)
|
'Open the device for data exchange.
This method opens the device identified by the dev parameter for communication.
This method must be called before calling any communication related method, such
as transfer methods.
It returns a handle identifying the communication instance. This handle must be
passed to the communication methods.'
| def open_device(self, dev):
| _not_implemented(self.open_device)
|
'Close the device handle.
This method closes the device communication channel and releases any
system resources related to it.'
| def close_device(self, dev_handle):
| _not_implemented(self.close_device)
|
'Set the active device configuration.
This method should be called to set the active configuration
of the device. The dev_handle parameter is the value returned
by the open_device() method and the config_value parameter is the
bConfigurationValue field of the related configuration descriptor.'
| def set_configuration(self, dev_handle, config_value):
| _not_implemented(self.set_configuration)
|
'Get the current active device configuration.
This method returns the bConfigurationValue of the currently
active configuration. Depending on the backend and the OS,
either a cached value may be returned or a control request may
be issued. The dev_handle parameter is the value returned by
the open_device method.'
| def get_configuration(self, dev_handle):
| _not_implemented(self.get_configuration)
|
'Set the interface alternate setting.
This method should only be called when the interface has more than
one alternate setting. The dev_handle is the value returned by the
open_device() method. intf and altsetting are respectivelly the
bInterfaceNumber and bAlternateSetting fields of the related interface.'
| def set_interface_altsetting(self, dev_handle, intf, altsetting):
| _not_implemented(self.set_interface_altsetting)
|
'Claim the given interface.
Interface claiming is not related to USB spec itself, but it is
generally an necessary call of the USB libraries. It requests exclusive
access to the interface on the system. This method must be called
before using one of the transfer methods.
dev_handle is the value returned by the open_device() method and
intf is the bInterfaceNumber field of the desired interface.'
| def claim_interface(self, dev_handle, intf):
| _not_implemented(self.claim_interface)
|
'Release the claimed interface.
dev_handle and intf are the same parameters of the claim_interface
method.'
| def release_interface(self, dev_handle, intf):
| _not_implemented(self.release_interface)
|
'Perform a bulk write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written.'
| def bulk_write(self, dev_handle, ep, intf, data, timeout):
| _not_implemented(self.bulk_write)
|
'Perform a bulk read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is the buffer to receive the data read, the length of the buffer
tells how many bytes should be read. The timeout parameter
specifies a time limit to the operation in miliseconds.
The method returns the number of bytes actually read.'
| def bulk_read(self, dev_handle, ep, intf, buff, timeout):
| _not_implemented(self.bulk_read)
|
'Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written.'
| def intr_write(self, dev_handle, ep, intf, data, timeout):
| _not_implemented(self.intr_write)
|
'Perform an interrut read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is the buffer to receive the data read, the length of the buffer
tells how many bytes should be read. The timeout parameter
specifies a time limit to the operation in miliseconds.
The method returns the number of bytes actually read.'
| def intr_read(self, dev_handle, ep, intf, size, timeout):
| _not_implemented(self.intr_read)
|
'Perform an isochronous write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written.'
| def iso_write(self, dev_handle, ep, intf, data, timeout):
| _not_implemented(self.iso_write)
|
'Perform an isochronous read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is buffer to receive the data read, the length of the buffer tells
how many bytes should be read. The timeout parameter specifies
a time limit to the operation in miliseconds.
The method returns the number of bytes actually read.'
| def iso_read(self, dev_handle, ep, intf, size, timeout):
| _not_implemented(self.iso_read)
|
'Perform a control transfer on the endpoint 0.
The direction of the transfer is inferred from the bmRequestType
field of the setup packet.
dev_handle is the value returned by the open_device() method.
bmRequestType, bRequest, wValue and wIndex are the same fields
of the setup packet. data is an array object, for OUT requests
it contains the bytes to transmit in the data stage and for
IN requests it is the buffer to hold the data read. The number
of bytes requested to transmit or receive is equal to the length
of the array times the data.itemsize field. The timeout parameter
specifies a time limit to the operation in miliseconds.
Return the number of bytes written (for OUT transfers) or the data
read (for IN transfers), as an array.array object.'
| def ctrl_transfer(self, dev_handle, bmRequestType, bRequest, wValue, wIndex, data, timeout):
| _not_implemented(self.ctrl_transfer)
|
'Clear the halt/stall condition for the endpoint.'
| def clear_halt(self, dev_handle, ep):
| _not_implemented(self.clear_halt)
|
'Reset the device.'
| def reset_device(self, dev_handle):
| _not_implemented(self.reset_device)
|
'Determine if a kernel driver is active on an interface.
If a kernel driver is active, you cannot claim the interface,
and the backend will be unable to perform I/O.'
| def is_kernel_driver_active(self, dev_handle, intf):
| _not_implemented(self.is_kernel_driver_active)
|
'Detach a kernel driver from an interface.
If successful, you will then be able to claim the interface
and perform I/O.'
| def detach_kernel_driver(self, dev_handle, intf):
| _not_implemented(self.detach_kernel_driver)
|
'Re-attach an interface\'s kernel driver, which was previously
detached using detach_kernel_driver().'
| def attach_kernel_driver(self, dev_handle, intf):
| _not_implemented(self.attach_kernel_driver)
|
'Returns a Form for all settings found in :class:`SettingsGroup`.
:param group: The settingsgroup name. It is used to get the settings
which are in the specified group.'
| @classmethod
def get_form(cls, group):
| class SettingsForm(FlaskForm, ):
pass
for setting in group.settings:
field_validators = []
if (setting.value_type in ('integer', 'float')):
validator_class = validators.NumberRange
elif (setting.value_type == 'string'):
validator_class = validators.Length
if ('min' in setting.extra):
field_validators.append(validator_class(min=setting.extra['min']))
if ('max' in setting.extra):
field_validators.append(validator_class(max=setting.extra['max']))
if (setting.value_type == 'integer'):
setattr(SettingsForm, setting.key, IntegerField(setting.name, validators=field_validators, description=setting.description))
elif (setting.value_type == 'float'):
setattr(SettingsForm, setting.key, FloatField(setting.name, validators=field_validators, description=setting.description))
elif (setting.value_type == 'string'):
setattr(SettingsForm, setting.key, TextField(setting.name, validators=field_validators, description=setting.description))
elif (setting.value_type == 'selectmultiple'):
if ('coerce' in setting.extra):
coerce_to = setting.extra['coerce']
else:
coerce_to = text_type
setattr(SettingsForm, setting.key, SelectMultipleField(setting.name, choices=setting.extra['choices'](), coerce=coerce_to, description=setting.description))
elif (setting.value_type == 'select'):
if ('coerce' in setting.extra):
coerce_to = setting.extra['coerce']
else:
coerce_to = text_type
setattr(SettingsForm, setting.key, SelectField(setting.name, coerce=coerce_to, choices=setting.extra['choices'](), description=setting.description))
elif (setting.value_type == 'boolean'):
setattr(SettingsForm, setting.key, BooleanField(setting.name, description=setting.description))
return SettingsForm
|
'Updates the cache and stores the changes in the
database.
:param settings: A dictionary with setting items.'
| @classmethod
def update(cls, settings, app=None):
| for (key, value) in iteritems(settings):
setting = cls.query.filter((Setting.key == key.lower())).first()
setting.value = value
db.session.add(setting)
db.session.commit()
cls.invalidate_cache()
|
'This will return all settings with the key as the key for the dict
and the values are packed again in a dict which contains
the remaining attributes.
:param from_group: Optionally - Returns only the settings from a group.'
| @classmethod
def get_settings(cls, from_group=None):
| result = None
if (from_group is not None):
result = from_group.settings
else:
result = cls.query.all()
settings = {}
for setting in result:
settings[setting.key] = {'name': setting.name, 'description': setting.description, 'value': setting.value, 'value_type': setting.value_type, 'extra': setting.extra}
return settings
|
'Returns all settings as a dict. This method is cached. If you want
to invalidate the cache, simply execute ``self.invalidate_cache()``.
:param from_group: Returns only the settings from the group as a dict.
:param upper: If upper is ``True``, the key will use upper-case
letters. Defaults to ``False``.'
| @classmethod
@cache.cached(key_prefix='settings')
def as_dict(cls, from_group=None, upper=True):
| settings = {}
result = None
if (from_group is not None):
result = SettingsGroup.query.filter_by(key=from_group).first_or_404()
result = result.settings
else:
result = cls.query.all()
for setting in result:
if upper:
setting_key = setting.key.upper()
else:
setting_key = setting.key
settings[setting_key] = setting.value
return settings
|
'Invalidates this objects cached metadata.'
| @classmethod
def invalidate_cache(cls):
| cache.delete_memoized(cls.as_dict, cls)
|
'Set to a unique key specific to the object in the database.
Required for cache.memoize() to work across requests.'
| def __repr__(self):
| return '<{} {} {}>'.format(self.__class__.__name__, self.id, self.name)
|
'Returns the first member group.'
| @classmethod
def get_member_group(cls):
| return cls.query.filter((cls.admin == False), (cls.super_mod == False), (cls.mod == False), (cls.guest == False), (cls.banned == False)).first()
|
'Returns the state of the account.
If the ``ACTIVATE_ACCOUNT`` option has been disabled, it will always
return ``True``. Is the option activated, it will, depending on the
state of the account, either return ``True`` or ``False``.'
| @property
def is_active(self):
| if flaskbb_config['ACTIVATE_ACCOUNT']:
if self.activated:
return True
return False
return True
|
'Returns the latest post from the user.'
| @property
def last_post(self):
| return Post.query.filter((Post.user_id == self.id)).order_by(Post.date_created.desc()).first()
|
'Returns the url for the user.'
| @property
def url(self):
| return url_for('user.profile', username=self.username)
|
'Returns the permissions for the user.'
| @property
def permissions(self):
| return self.get_permissions()
|
'Returns the user groups.'
| @property
def groups(self):
| return self.get_groups()
|
'Returns the unread messages for the user.'
| @property
def unread_messages(self):
| return self.get_unread_messages()
|
'Returns the unread message count for the user.'
| @property
def unread_count(self):
| return len(self.unread_messages)
|
'Returns the amount of days the user is registered.'
| @property
def days_registered(self):
| days_registered = (time_utcnow() - self.date_joined).days
if (not days_registered):
return 1
return days_registered
|
'Returns the thread count.'
| @property
def topic_count(self):
| return Topic.query.filter((Topic.user_id == self.id)).count()
|
'Returns the posts per day count.'
| @property
def posts_per_day(self):
| return round((float(self.post_count) / float(self.days_registered)), 1)
|
'Returns the topics per day count.'
| @property
def topics_per_day(self):
| return round((float(self.topic_count) / float(self.days_registered)), 1)
|
'Set to a unique key specific to the object in the database.
Required for cache.memoize() to work across requests.'
| def __repr__(self):
| return '<{} {}>'.format(self.__class__.__name__, self.username)
|
'Returns the hashed password.'
| def _get_password(self):
| return self._password
|
'Generates a password hash for the provided password.'
| def _set_password(self, password):
| if (not password):
return
self._password = generate_password_hash(password)
|
'Check passwords. If passwords match it returns true, else false.'
| def check_password(self, password):
| if (self.password is None):
return False
return check_password_hash(self.password, password)
|
'A classmethod for authenticating users.
It returns the user object if the user/password combination is ok.
If the user has entered too often a wrong password, he will be locked
out of his account for a specified time.
:param login: This can be either a username or a email address.
:param password: The password that is connected to username and email.'
| @classmethod
def authenticate(cls, login, password):
| user = cls.query.filter(db.or_((User.username == login), (User.email == login))).first()
if (user is not None):
if user.check_password(password):
user.login_attempts = 0
user.save()
return user
if (user.login_attempts is None):
user.login_attempts = 1
else:
user.login_attempts += 1
user.last_failed_login = time_utcnow()
user.save()
check_password_hash('dummy password', password)
raise AuthenticationError
|
'Recalculates the post count from the user.'
| def recalculate(self):
| post_count = Post.query.filter_by(user_id=self.id).count()
self.post_count = post_count
self.save()
return self
|
'Returns a paginated result with all topics the user has created.
:param page: The page which should be displayed.
:param viewer: The user who is viewing this user. It will return a
list with topics that the *viewer* has access to and
thus it will not display all topics from
the requested user.'
| def all_topics(self, page, viewer):
| group_ids = [g.id for g in viewer.groups]
topics = Topic.query.filter((Topic.user_id == self.id), (Forum.id == Topic.forum_id), Forum.groups.any(Group.id.in_(group_ids))).paginate(page, flaskbb_config['TOPICS_PER_PAGE'], False)
return topics
|
'Returns a paginated result with all posts the user has created.
:param page: The page which should be displayed.
:param viewer: The user who is viewing this user. It will return a
list with posts that the *viewer* has access to and
thus it will not display all posts from
the requested user.'
| def all_posts(self, page, viewer):
| group_ids = [g.id for g in viewer.groups]
posts = Post.query.filter((Post.user_id == self.id), (Post.topic_id == Topic.id), (Topic.forum_id == Forum.id), Forum.groups.any(Group.id.in_(group_ids))).paginate(page, flaskbb_config['TOPICS_PER_PAGE'], False)
return posts
|
'Tracks the specified topic.
:param topic: The topic which should be added to the topic tracker.'
| def track_topic(self, topic):
| if (not self.is_tracking_topic(topic)):
self.tracked_topics.append(topic)
return self
|
'Untracks the specified topic.
:param topic: The topic which should be removed from the
topic tracker.'
| def untrack_topic(self, topic):
| if self.is_tracking_topic(topic):
self.tracked_topics.remove(topic)
return self
|
'Checks if the user is already tracking this topic.
:param topic: The topic which should be checked.'
| def is_tracking_topic(self, topic):
| return (self.tracked_topics.filter((topictracker.c.topic_id == topic.id)).count() > 0)
|
'Adds the user to the `group` if he isn\'t in it.
:param group: The group which should be added to the user.'
| def add_to_group(self, group):
| if (not self.in_group(group)):
self.secondary_groups.append(group)
return self
|
'Removes the user from the `group` if he is in it.
:param group: The group which should be removed from the user.'
| def remove_from_group(self, group):
| if self.in_group(group):
self.secondary_groups.remove(group)
return self
|
'Returns True if the user is in the specified group.
:param group: The group which should be checked.'
| def in_group(self, group):
| return (self.secondary_groups.filter((groups_users.c.group_id == group.id)).count() > 0)
|
'Returns all the groups the user is in.'
| @cache.memoize()
def get_groups(self):
| return ([self.primary_group] + list(self.secondary_groups))
|
'Returns a dictionary with all permissions the user has'
| @cache.memoize()
def get_permissions(self, exclude=None):
| if exclude:
exclude = set(exclude)
else:
exclude = set()
exclude.update(['id', 'name', 'description'])
perms = {}
for group in self.groups:
columns = (set(group.__table__.columns.keys()) - set(exclude))
for c in columns:
perms[c] = (getattr(group, c) or perms.get(c, False))
return perms
|
'Returns all unread messages for the user.'
| @cache.memoize()
def get_unread_messages(self):
| unread_messages = Conversation.query.filter(Conversation.unread, (Conversation.user_id == self.id)).all()
return unread_messages
|
'Invalidates this objects cached metadata.
:param permissions_only: If set to ``True`` it will only invalidate
the permissions cache. Otherwise it will
also invalidate the user\'s unread message
cache.'
| def invalidate_cache(self, permissions=True, messages=True):
| if messages:
cache.delete_memoized(self.get_unread_messages, self)
if permissions:
cache.delete_memoized(self.get_permissions, self)
cache.delete_memoized(self.get_groups, self)
|
'Bans the user. Returns True upon success.'
| def ban(self):
| if (not self.get_permissions()['banned']):
banned_group = Group.query.filter((Group.banned == True)).first()
self.primary_group = banned_group
self.save()
self.invalidate_cache()
return True
return False
|
'Unbans the user. Returns True upon success.'
| def unban(self):
| if self.get_permissions()['banned']:
member_group = Group.query.filter((Group.admin == False), (Group.super_mod == False), (Group.mod == False), (Group.guest == False), (Group.banned == False)).first()
self.primary_group = member_group
self.save()
self.invalidate_cache()
return True
return False
|
'Saves a user. If a list with groups is provided, it will add those
to the secondary groups from the user.
:param groups: A list with groups that should be added to the
secondary groups from user.'
| def save(self, groups=None):
| if (groups is not None):
secondary_groups = self.secondary_groups.all()
for group in secondary_groups:
self.remove_from_group(group)
db.session.commit()
for group in groups:
if (group == self.primary_group):
continue
self.add_to_group(group)
self.invalidate_cache()
db.session.add(self)
db.session.commit()
return self
|
'Deletes the User.'
| def delete(self):
| Conversation.query.filter_by(user_id=self.id).delete()
ForumsRead.query.filter_by(user_id=self.id).delete()
TopicsRead.query.filter_by(user_id=self.id).delete()
from flaskbb.forum.models import Forum
last_post_forums = Forum.query.filter_by(last_post_user_id=self.id).all()
for forum in last_post_forums:
forum.last_post_user_id = None
forum.save()
db.session.delete(self)
db.session.commit()
return self
|
'Returns a dictionary with all permissions the user has'
| @cache.memoize()
def get_permissions(self, exclude=None):
| if exclude:
exclude = set(exclude)
else:
exclude = set()
exclude.update(['id', 'name', 'description'])
perms = {}
for group in self.groups:
columns = (set(group.__table__.columns.keys()) - set(exclude))
for c in columns:
perms[c] = (getattr(group, c) or perms.get(c, False))
return perms
|
'Invalidates this objects cached metadata.'
| @classmethod
def invalidate_cache(cls):
| cache.delete_memoized(cls.get_permissions, cls)
|
'Returns the first message object.'
| @property
def first_message(self):
| return self.messages[0]
|
'Returns the last message object.'
| @property
def last_message(self):
| return self.messages[(-1)]
|
'Saves a conversation and returns the saved conversation object.
:param message: If given, it will also save the message for the
conversation. It expects a Message object.'
| def save(self, message=None):
| if (message is not None):
self.date_created = time_utcnow()
db.session.add(self)
db.session.commit()
message.save(self)
return self
self.date_modified = time_utcnow()
db.session.add(self)
db.session.commit()
return self
|
'Saves a private message.
:param conversation: The conversation to which the message
belongs to.'
| def save(self, conversation=None):
| if (conversation is not None):
self.conversation = conversation
conversation.date_modified = time_utcnow()
self.date_created = time_utcnow()
db.session.add(self)
db.session.commit()
return self
|
'Saves the form data to the model.
:param conversation: The Conversation object.
:param user_id: The id from the user who sent the message.
:param reciever: If the message should also be stored in the recievers
inbox.'
| def save(self, conversation, user_id, unread=False):
| message = Message(message=self.message.data, user_id=user_id)
if unread:
conversation.unread = True
conversation.save()
return message.save(conversation)
|
'Saves a report.
:param post: The post that should be reported
:param user: The user who has reported the post
:param reason: The reason why the user has reported the post'
| def save(self, post=None, user=None):
| if self.id:
db.session.add(self)
db.session.commit()
return self
if (post and user):
self.reporter = user
self.reported = time_utcnow()
self.post = post
db.session.add(self)
db.session.commit()
return self
|
'Returns the url for the post.'
| @property
def url(self):
| return url_for('forum.view_post', post_id=self.id)
|
'Creates a post object with some initial values.
:param content: The content of the post.
:param user: The user of the post.
:param topic: Can either be the topic_id or the topic object.'
| def __init__(self, content=None, user=None, topic=None):
| if content:
self.content = content
if user:
self.user_id = user.id
self.username = user.username
if topic:
self.topic_id = (topic if isinstance(topic, int) else topic.id)
self.date_created = time_utcnow()
|
'Set to a unique key specific to the object in the database.
Required for cache.memoize() to work across requests.'
| def __repr__(self):
| return '<{} {}>'.format(self.__class__.__name__, self.id)
|
'Saves a new post. If no parameters are passed we assume that
you will just update an existing post. It returns the object after the
operation was successful.
:param user: The user who has created the post
:param topic: The topic in which the post was created'
| def save(self, user=None, topic=None):
| if self.id:
db.session.add(self)
db.session.commit()
return self
if (user and topic):
created = time_utcnow()
self.user = user
self.username = user.username
self.topic = topic
self.date_created = created
topic.last_updated = created
topic.last_post = self
topic.forum.last_post = self
topic.forum.last_post_user = self.user
topic.forum.last_post_title = topic.title
topic.forum.last_post_username = user.username
topic.forum.last_post_created = created
user.post_count += 1
topic.post_count += 1
topic.forum.post_count += 1
db.session.add(topic)
db.session.commit()
return self
|
'Deletes a post and returns self.'
| def delete(self):
| if (self.topic.first_post == self):
self.topic.delete()
return self
if (self.topic.last_post == self):
if (self.topic.last_post == self.topic.forum.last_post):
second_last_post = Post.query.filter((Post.topic_id == Topic.id), (Topic.forum_id == self.topic.forum.id)).order_by(Post.id.desc()).limit(2).offset(0).all()
last_post = second_last_post[1]
self.topic.forum.last_post = last_post
self.topic.forum.last_post_title = last_post.topic.title
self.topic.forum.last_post_user = last_post.user
self.topic.forum.last_post_username = last_post.username
self.topic.forum.last_post_created = last_post.date_created
if self.topic.second_last_post:
self.topic.last_post_id = self.topic.second_last_post
else:
self.topic.last_post = self.topic.first_post
self.topic.last_updated = self.topic.last_post.date_created
self.user.post_count -= 1
self.topic.post_count -= 1
self.topic.forum.post_count -= 1
db.session.delete(self)
db.session.commit()
return self
|
'Returns the second last post.'
| @property
def second_last_post(self):
| return self.posts[(-2)].id
|
'Returns a slugified version of the topic title.'
| @property
def slug(self):
| return slugify(self.title)
|
'Returns the slugified url for the topic.'
| @property
def url(self):
| return url_for('forum.view_topic', topic_id=self.id, slug=self.slug)
|
'Returns the url to the first unread post. If no unread posts exist
it will return the url to the topic.
:param topicsread: The topicsread object for the topic
:param user: The user who should be checked if he has read the
last post in the topic
:param forumsread: The forumsread object in which the topic is. If you
also want to check if the user has marked the forum as
read, than you will also need to pass an forumsread
object.'
| def first_unread(self, topicsread, user, forumsread=None):
| if topic_is_unread(self, topicsread, user, forumsread):
query = Post.query.filter((Post.topic_id == self.id))
if (topicsread is not None):
query = query.filter((Post.date_created > topicsread.last_read))
post = query.order_by(Post.id.asc()).first()
if (post is not None):
return post.url
return self.url
|
'Creates a topic object with some initial values.
:param title: The title of the topic.
:param user: The user of the post.'
| def __init__(self, title=None, user=None):
| if title:
self.title = title
if user:
self.user_id = user.id
self.username = user.username
self.date_created = self.last_updated = time_utcnow()
|
'Set to a unique key specific to the object in the database.
Required for cache.memoize() to work across requests.'
| def __repr__(self):
| return '<{} {}>'.format(self.__class__.__name__, self.id)
|
'Returns True if the topicsread tracker needs an update.
Also, if the ``TRACKER_LENGTH`` is configured, it will just recognize
topics that are newer than the ``TRACKER_LENGTH`` (in days) as unread.
:param forumsread: The ForumsRead object is needed because we also
need to check if the forum has been cleared
sometime ago.
:param topicsread: The topicsread object is used to check if there is
a new post in the topic.'
| def tracker_needs_update(self, forumsread, topicsread):
| read_cutoff = None
if (flaskbb_config['TRACKER_LENGTH'] > 0):
read_cutoff = (time_utcnow() - timedelta(days=flaskbb_config['TRACKER_LENGTH']))
if (read_cutoff is None):
return False
elif (read_cutoff > self.last_post.date_created):
return False
if (forumsread and (forumsread.cleared is not None) and (forumsread.cleared >= self.last_post.date_created)):
return False
if (topicsread and (topicsread.last_read >= self.last_post.date_created)):
return False
return True
|
'Updates the topicsread and forumsread tracker for a specified user,
if the topic contains new posts or the user hasn\'t read the topic.
Returns True if the tracker has been updated.
:param user: The user for whom the readstracker should be updated.
:param forum: The forum in which the topic is.
:param forumsread: The forumsread object. It is used to check if there
is a new post since the forum has been marked as
read.'
| def update_read(self, user, forum, forumsread):
| if (not user.is_authenticated):
return False
topicsread = TopicsRead.query.filter((TopicsRead.user_id == user.id), (TopicsRead.topic_id == self.id)).first()
if (not self.tracker_needs_update(forumsread, topicsread)):
return False
updated = False
if topicsread:
topicsread.last_read = time_utcnow()
topicsread.save()
updated = True
elif (not topicsread):
topicsread = TopicsRead()
topicsread.user = user
topicsread.topic = self
topicsread.forum = self.forum
topicsread.last_read = time_utcnow()
topicsread.save()
updated = True
else:
updated = False
updated = forum.update_read(user, forumsread, topicsread)
return updated
|
'Recalculates the post count in the topic.'
| def recalculate(self):
| post_count = Post.query.filter_by(topic_id=self.id).count()
self.post_count = post_count
self.save()
return self
|
'Moves a topic to the given forum.
Returns True if it could successfully move the topic to forum.
:param new_forum: The new forum for the topic'
| def move(self, new_forum):
| if (self.forum == new_forum):
return False
old_forum = self.forum
self.forum.post_count -= self.post_count
self.forum.topic_count -= 1
self.forum = new_forum
new_forum.post_count += self.post_count
new_forum.topic_count += 1
db.session.commit()
new_forum.update_last_post()
old_forum.update_last_post()
TopicsRead.query.filter_by(topic_id=self.id).delete()
return True
|
'Saves a topic and returns the topic object. If no parameters are
given, it will only update the topic.
:param user: The user who has created the topic
:param forum: The forum where the topic is stored
:param post: The post object which is connected to the topic'
| def save(self, user=None, forum=None, post=None):
| if self.id:
db.session.add(self)
db.session.commit()
return self
self.forum = forum
self.user = user
self.username = user.username
self.date_created = self.last_updated = time_utcnow()
db.session.add(self)
db.session.commit()
post.save(user, self)
self.last_post = self.first_post = post
forum.topic_count += 1
db.session.commit()
return self
|
'Deletes a topic with the corresponding posts. If a list with
user objects is passed it will also update their post counts
:param users: A list with user objects'
| def delete(self, users=None):
| topic = Topic.query.filter_by(forum_id=self.forum_id).order_by(Topic.last_post_id.desc()).limit(2).offset(0).all()
if (topic and (topic[0] == self)):
try:
self.forum.last_post = topic[1].last_post
self.forum.last_post_title = topic[1].title
self.forum.last_post_user = topic[1].user
self.forum.last_post_username = topic[1].username
self.forum.last_post_created = topic[1].last_updated
except IndexError:
self.forum.last_post = None
self.forum.last_post_title = None
self.forum.last_post_user = None
self.forum.last_post_username = None
self.forum.last_post_created = None
forum = self.forum
TopicsRead.query.filter_by(topic_id=self.id).delete()
db.session.delete(self)
if users:
for user in users:
user.post_count = Post.query.filter_by(user_id=user.id).count()
forum.topic_count = Topic.query.filter_by(forum_id=self.forum_id).count()
forum.post_count = Post.query.filter((Post.topic_id == Topic.id), (Topic.forum_id == self.forum_id)).count()
db.session.commit()
return self
|
'Returns a slugified version from the forum title'
| @property
def slug(self):
| return slugify(self.title)
|
'Returns the slugified url for the forum'
| @property
def url(self):
| if self.external:
return self.external
return url_for('forum.view_forum', forum_id=self.id, slug=self.slug)
|
'Returns the url for the last post in the forum'
| @property
def last_post_url(self):
| return url_for('forum.view_post', post_id=self.last_post_id)
|
'Set to a unique key specific to the object in the database.
Required for cache.memoize() to work across requests.'
| def __repr__(self):
| return '<{} {}>'.format(self.__class__.__name__, self.id)
|
'Updates the last post in the forum.'
| def update_last_post(self):
| last_post = Post.query.filter((Post.topic_id == Topic.id), (Topic.forum_id == self.id)).order_by(Post.date_created.desc()).limit(1).first()
if (last_post is not None):
if (last_post != self.last_post):
self.last_post = last_post
self.last_post_title = last_post.topic.title
self.last_post_user_id = last_post.user_id
self.last_post_username = last_post.username
self.last_post_created = last_post.date_created
else:
self.last_post = None
self.last_post_title = None
self.last_post_user = None
self.last_post_username = None
self.last_post_created = None
db.session.commit()
|
'Updates the ForumsRead status for the user. In order to work
correctly, be sure that `topicsread is **not** `None`.
:param user: The user for whom we should check if he has read the
forum.
:param forumsread: The forumsread object. It is needed to check if
if the forum is unread. If `forumsread` is `None`
and the forum is unread, it will create a new entry
in the `ForumsRead` relation, else (and the forum
is still unread) we are just going to update the
entry in the `ForumsRead` relation.
:param topicsread: The topicsread object is used in combination
with the forumsread object to check if the
forumsread relation should be updated and
therefore is unread.'
| def update_read(self, user, forumsread, topicsread):
| if ((not user.is_authenticated) or (topicsread is None)):
return False
read_cutoff = None
if (flaskbb_config['TRACKER_LENGTH'] > 0):
read_cutoff = (time_utcnow() - timedelta(days=flaskbb_config['TRACKER_LENGTH']))
unread_count = Topic.query.outerjoin(TopicsRead, db.and_((TopicsRead.topic_id == Topic.id), (TopicsRead.user_id == user.id))).outerjoin(ForumsRead, db.and_((ForumsRead.forum_id == Topic.forum_id), (ForumsRead.user_id == user.id))).filter((Topic.forum_id == self.id), (Topic.last_updated > read_cutoff), db.or_((TopicsRead.last_read == None), (TopicsRead.last_read < Topic.last_updated))).count()
if (unread_count == 0):
if (forumsread and (forumsread.last_read > topicsread.last_read)):
return False
elif forumsread:
forumsread.last_read = time_utcnow()
forumsread.save()
return True
forumsread = ForumsRead()
forumsread.user = user
forumsread.forum = self
forumsread.last_read = time_utcnow()
forumsread.save()
return True
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.