class SignupForm(BaseForm): username = TextField( _('Username'), validators=[ DataRequired(), Length(min=3, max=20), Regexp(r'^[a-z0-9A-Z]+$') ], description=_('English Characters Only.'), ) email = EmailField(_('Email'), validators=[DataRequired(), Email()]) password = PasswordField(_('Password'), validators=[DataRequired()]) def validate_username(self, field): data = field.data.lower() if data in RESERVED_WORDS: raise ValueError(_('This name is a reserved name.')) if data in current_app.config.get('RESERVED_WORDS', []): raise ValueError(_('This name is a reserved name.')) if Account.query.filter_by(username=data).count(): raise ValueError(_('This name has been registered.')) def validate_email(self, field): if Account.query.filter_by(email=field.data.lower()).count(): raise ValueError(_('This email has been registered.')) def save(self, role=None): user = Account(**self.data) if role: user.role = role user.save() return user
class NodeForm(BaseForm): title = TextField( _('Title'), validators=[DataRequired()], description=_('The screen title of the node') ) urlname = TextField( _('URL'), validators=[DataRequired()], description=_('The url name of the node') ) description = TextAreaField(_('Description')) role = SelectField( description=_('Required role'), choices=[ ('user', _('User')), ('staff', _('Staff')), ('admin', _('Admin')) ], default='user', ) def validate_urlname(self, field): if self._obj and self._obj.urlname == field.data: return if Node.query.filter_by(urlname=field.data).count(): raise ValueError(_('The node exists')) def save(self): node = Node(**self.data) node.save() return node
class SignupForm(Form): username = StringField('Username', validators=[ DataRequired(), Regexp('^[A-Za-z0-9\-_]+$', message='Only alphabets, numbers, hyphen, and underscore are allowed.'), Unique(lambda: db.session, User, User.username) ]) password = PasswordField('Password', validators=[DataRequired()]) password_confirmation = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password', 'Password confirmation is different from password.') ])
class ResetForm(BaseForm): password = PasswordField(_('Password'), validators=[DataRequired()], description=_('Remember your password')) confirm = PasswordField(_('Confirm'), validators=[DataRequired()], description=_('Confirm your password')) def validate_confirm(self, field): if field.data != self.password.data: raise ValueError(_("Passwords don't match."))
class DesktopReleaseForm(ReleaseForm): partials = StringField( 'Partial versions:', validators=[ Regexp(PARTIAL_VERSIONS_REGEX, message='Invalid partials format.') ], filters=[collapseSpaces], ) promptWaitTime = NullableIntegerField('Update prompt wait time:') l10nChangesets = PlainChangesetsField( 'L10n Changesets:', validators=[DataRequired('L10n Changesets are required.')]) def addSuggestions(self): ReleaseForm.addSuggestions(self) table = getReleaseTable(self.product.data) recentReleases = table.getRecentShipped() seenVersions = [] partials = {} # The UI will suggest any versions which are on the same branch as # the one given, but only the highest build number for that version. for release in reversed(recentReleases): if release.branch not in partials: partials[release.branch] = [] if release.version not in seenVersions: partials[release.branch].append( '%sbuild%d' % (release.version, release.buildNumber)) seenVersions.append(release.version) self.partials.suggestions = json.dumps(partials)
class DesktopReleaseForm(ReleaseForm): partials = StringField( 'Partial versions:', validators=[ Regexp(PARTIAL_VERSIONS_REGEX, message='Invalid partials format.') ], filters=[collapseSpaces], ) promptWaitTime = NullableIntegerField('Update prompt wait time:') l10nChangesets = PlainChangesetsField( 'L10n Changesets:', validators=[DataRequired('L10n Changesets are required.')]) def addSuggestions(self): ReleaseForm.addSuggestions(self) table = getReleaseTable(self.product.data) recentReleases = table.getRecentShipped() seenVersions = [] partials = defaultdict(list) # The UI will suggest any versions which are on the same branch as # the one given, but only the highest build number for that version. # One exception is Firefox RC builds (version X.0), which should be added # to the list of betas for release in reversed(recentReleases): if release.version not in seenVersions: partials[release.branch].append( '%sbuild%d' % (release.version, release.buildNumber)) seenVersions.append(release.version) # here's the exception if release.product == 'firefox' and \ release.branch == 'releases/mozilla-release' and \ re.match('^\d+\.0$', release.version): partials['releases/mozilla-beta'].append( '%sbuild%d' % (release.version, release.buildNumber)) self.partials.suggestions = json.dumps(partials)
class FennecReleaseForm(ReleaseForm): product = HiddenField('product') l10nChangesets = JSONField( 'L10n Changesets:', validators=[DataRequired('L10n Changesets are required.')]) def __init__(self, *args, **kwargs): ReleaseForm.__init__(self, prefix='fennec', product='fennec', *args, **kwargs) def updateFromRow(self, row): self.version.data = row.version self.buildNumber.data = row.buildNumber self.branch.data = row.branch # Revision is a disabled field if relbranch is present, so we shouldn't # put any data in it. if not row.mozillaRelbranch: self.mozillaRevision.data = row.mozillaRevision self.dashboardCheck.data = row.dashboardCheck self.l10nChangesets.data = row.l10nChangesets self.mozillaRelbranch.data = row.mozillaRelbranch self.mh_changeset.data = row.mh_changeset
class UserForm(SettingForm): username = TextField( _('Username'), validators=[ DataRequired(), Length(min=3, max=20), Regexp(r'^[a-z0-9A-Z]+$') ], description=_('English Characters Only.'), ) email = EmailField(_('Email'), validators=[DataRequired(), Email()]) role = SelectField( _('Role'), choices=[('spam', _('Spam')), ('user', _('User')), ('staff', _('Staff')), ('admin', _('Admin'))], default='user', )
class FennecReleaseForm(ReleaseForm): product = HiddenField('product') l10nChangesets = JSONField( 'L10n Changesets:', validators=[DataRequired('L10n Changesets are required.')]) def __init__(self, *args, **kwargs): ReleaseForm.__init__(self, prefix='fennec', product='fennec', *args, **kwargs)
class SigninForm(BaseForm): account = TextField(_('Account'), validators=[DataRequired(), Length(min=3, max=20)], description=_('Username or Email')) password = PasswordField(_('Password'), validators=[DataRequired()]) permanent = BooleanField(_('Remember me for a month.')) def validate_password(self, field): account = self.account.data if '@' in account: user = Account.query.filter_by(email=account).first() else: user = Account.query.filter_by(username=account).first() if not user: raise ValueError(_('Wrong account or password')) if user.check_password(field.data): self.user = user return user raise ValueError(_('Wrong account or password'))
class TopicForm(BaseForm): title = TextField( _('Title'), validators=[DataRequired()], description=_('Title of the topic') ) content = TextAreaField( _('Content'), description=_('Content of the topic') ) def save(self, user, node): topic = Topic(**self.data) return topic.save(user=user, node=node)
class FindForm(BaseForm): account = TextField(_('Account'), validators=[DataRequired()], description=_('Username or Email')) def validate_account(self, field): account = field.data if '@' in account: user = Account.query.filter_by(email=account).first() else: user = Account.query.filter_by(username=account).first() if not user: raise ValueError(_('This account does not exist.')) self.user = user
class LoginForm(Form): username = StringField('Username', validators=[ DataRequired(), Regexp('^[A-Za-z0-9\-_]+$', message='Only alphabets, numbers, hyphen, and underscore are allowed.') ]) password = PasswordField('Password', validators=[DataRequired()])
class ReleaseForm(Form): version = StringField('Version:', validators=[ Regexp(ANY_VERSION_REGEX, message='Invalid version format.') ]) buildNumber = IntegerField( 'Build Number:', validators=[DataRequired('Build number is required.')]) branch = StringField('Branch:', validators=[DataRequired('Branch is required')]) mozillaRevision = StringField('Mozilla Revision:') dashboardCheck = BooleanField('Dashboard check?', default=False) mozillaRelbranch = StringField('Mozilla Relbranch:', filters=[noneFilter]) comment = TextAreaField('Extra information to release-drivers:') description = TextAreaField('Description:') isSecurityDriven = BooleanField('Is a security driven release?', default=False) mh_changeset = StringField('Mozharness Revision:') def __init__(self, suggest=True, *args, **kwargs): Form.__init__(self, *args, **kwargs) if suggest: self.addSuggestions() def validate(self, *args, **kwargs): valid = Form.validate(self, *args, **kwargs) # If a relbranch has been passed revision is ignored. if self.mozillaRelbranch.data: self.mozillaRevision.data = self.mozillaRelbranch.data # However, if a relbranch hasn't been passed, revision is required. else: if not self.mozillaRevision.data: valid = False self.errors['mozillaRevision'] = [ 'Mozilla revision is required' ] return valid def addSuggestions(self): table = getReleaseTable(self.product.data) recentReleases = table.getRecent() # Before we make any suggestions we need to do some preprocessing of # the data to get it into useful structures. Specifically, we need a # set containing all of the recent versions, and a dict that associates # them with the branch they were built on. recentVersions = set() recentBranches = defaultdict(list) for release in recentReleases: recentVersions.add(release.version) recentBranches[release.branch].append(LooseVersion( release.version)) # Now that we have the data in the format we want it in we can start # making suggestions. suggestedVersions = set() buildNumbers = {} # This wrapper method is used to centralize the build number suggestion # logic in one place, because there's more than one spot below that # adds a version suggestion. def addVersionSuggestion(version): suggestedVersions.add(version) # We want the UI to be able to automatically set build number # to the next available one for whatever version is entered. # To make this work we need to tell it what the next available # one is for all existing versions. We don't need to add versions # that are on build1, because it uses that as the default. maxBuildNumber = table.getMaxBuildNumber(version) if maxBuildNumber: buildNumbers[version] = maxBuildNumber + 1 else: buildNumbers[version] = 1 # Every version we see will have its potential next versions # suggested, except if we already have that version. # Note that we don't look through the entire table for every # version (because that could be expensive) but any versions # which are suggested and have already happened should be in # 'recentVersions', so it's unlikely we'll be suggesting # something that has already happened. for version in recentVersions: for v in getPossibleNextVersions(version): if v not in recentVersions: addVersionSuggestion(v) # Additional, we need to suggest the most recent version for each # branch, because we may want a build2 (or higher) of it. for branchVersions in recentBranches.values(): addVersionSuggestion(str(max(branchVersions))) # Finally, attach the suggestions to their fields. self.branch.suggestions = json.dumps(list(recentBranches.keys())) self.version.suggestions = json.dumps(list(suggestedVersions)) self.buildNumber.suggestions = json.dumps(buildNumbers)
class ReleaseForm(Form): version = StringField('Version:', validators=[ Regexp(ANY_VERSION_REGEX, message='Invalid version format.') ]) buildNumber = IntegerField( 'Build Number:', validators=[DataRequired('Build number is required.')]) branch = StringField('Branch:', validators=[DataRequired('Branch is required')]) mozillaRevision = StringField('Mozilla Revision:') mozillaRelbranch = StringField('Mozilla Relbranch:', filters=[noneFilter]) comment = TextAreaField('Extra information to release-drivers:') description = TextAreaField('Description:') isSecurityDriven = BooleanField('Is a security driven release?', default=False) mh_changeset = StringField('Mozharness Revision:') release_eta_date = DateField('Release ETA date:', format='%Y-%m-%d', validators=[validators.optional()]) release_eta_time = StringField('Release ETA time:') VALID_VERSION_PATTERN = re.compile( r"""^(\d+)\.( # Major version number (0)(a1|a2|b(\d+)|esr)? # 2-digit-versions (like 46.0, 46.0b1, 46.0esr) |( # Here begins the 3-digit-versions. ([1-9]\d*)\.(\d+)|(\d+)\.([1-9]\d*) # 46.0.0 is not correct )(esr)? # Neither is 46.2.0b1 )(build(\d+))?$""", re.VERBOSE) # See more examples of (in)valid versions in the tests def __init__(self, suggest=True, *args, **kwargs): Form.__init__(self, *args, **kwargs) if suggest: self.addSuggestions() def validate(self, *args, **kwargs): valid = Form.validate(self, *args, **kwargs) # If a relbranch has been passed revision is ignored. if self.mozillaRelbranch.data: self.mozillaRevision.data = self.mozillaRelbranch.data # However, if a relbranch hasn't been passed, revision is required. else: if not self.mozillaRevision.data: valid = False self.errors['mozillaRevision'] = [ 'Mozilla revision is required' ] if self.VALID_VERSION_PATTERN.match(self.version.data) is None: valid = False self.errors['version'] = ['Version must match either X.0 or X.Y.Z'] return valid def addSuggestions(self): table = getReleaseTable(self.product.data) recentReleases = table.getRecent() # Before we make any suggestions we need to do some preprocessing of # the data to get it into useful structures. Specifically, we need a # set containing all of the recent versions, and a dict that associates # them with the branch they were built on. recentVersions = set() recentBranches = defaultdict(list) for release in recentReleases: recentVersions.add(release.version) recentBranches[release.branch].append(MozVersion(release.version)) # Now that we have the data in the format we want it in we can start # making suggestions. suggestedVersions = set() buildNumbers = {} # This wrapper method is used to centralize the build number suggestion # logic in one place, because there's more than one spot below that # adds a version suggestion. def addVersionSuggestion(version): suggestedVersions.add(version) # We want the UI to be able to automatically set build number # to the next available one for whatever version is entered. # To make this work we need to tell it what the next available # one is for all existing versions. We don't need to add versions # that are on build1, because it uses that as the default. maxBuildNumber = table.getMaxBuildNumber(version) if maxBuildNumber: buildNumbers[version] = maxBuildNumber + 1 else: buildNumbers[version] = 1 # Every version we see will have its potential next versions # suggested, except if we already have that version. # Note that we don't look through the entire table for every # version (because that could be expensive) but any versions # which are suggested and have already happened should be in # 'recentVersions', so it's unlikely we'll be suggesting # something that has already happened. for version in recentVersions: for v in getPossibleNextVersions(version): if v not in recentVersions: addVersionSuggestion(v) # Additional, we need to suggest the most recent version for each # branch, because we may want a build2 (or higher) of it. for branchVersions in recentBranches.values(): addVersionSuggestion(str(max(branchVersions))) # Finally, attach the suggestions to their fields. self.branch.suggestions = json.dumps(list(recentBranches.keys())) self.version.suggestions = json.dumps(list(suggestedVersions)) self.buildNumber.suggestions = json.dumps(buildNumbers) def updateFromRow(self, row): self.version.data = row.version self.buildNumber.data = row.buildNumber self.branch.data = row.branch # Revision is a disabled field if relbranch is present, so we shouldn't # put any data in it. if not row.mozillaRelbranch: self.mozillaRevision.data = row.mozillaRevision self.l10nChangesets.data = row.l10nChangesets self.mozillaRelbranch.data = row.mozillaRelbranch self.mh_changeset.data = row.mh_changeset if row.release_eta: release_eta = parse_iso8601_to_date_time(row.release_eta) self.release_eta_date.data = release_eta.date() # Conversion needed because release_eta_time is a StringField self.release_eta_time.data = release_eta.strftime('%H:%M %Z') @property def release_eta(self): if self.release_eta_date.data and self.release_eta_time.data: dt = self.release_eta_date.data tm = datetime.strptime(self.release_eta_time.data, '%H:%M %Z').time() return datetime.combine(dt, tm) else: return None
class CreateUserForm(Form): name = TextField('name', validators=[DataRequired()]) uid = TextField('uid', validators=[DataRequired()])
class CategoryForm(Form): name = StringField('Name', validators=[DataRequired()]) slug = SlugField('name', label='Slug', validators=[ Regexp('^[0-9a-z\-]+$', message='Only lowercase alphabets, numbers, and hyphen are allowed.'), Unique(lambda: db.session, Category, Category.slug) ])
class ReplyForm(BaseForm): content = TextAreaField(_('Content'), validators=[DataRequired()]) def save(self, user, topic): item = Reply(**self.data) return item.save(user=user, topic=topic)
class ResetForm(BaseForm): password = PasswordField(_('Password'), validators=[DataRequired()], description=_('Remember your password'))