Example #1
0
def addCustomer():
    form = AddCustomerForm()

    form.recommender.choices = [(0, '')]
    poss_customers = Customer.query\
        .filter(Customer.customer_type == CUSTOMER_TYPES['TYPE_CUSTOMER']).all()
    for cust in poss_customers:
        form.recommender.choices.append((cust.id, cust.name))

    if form.validate_on_submit():
        customer = Customer()

        customer.name = form.name.data
        customer.email = form.email.data
        customer.base_discount = int(form.base_discount.data)/100.0

        if form.recommender.data and form.recommender.data > 0:
                customer.recommender_id = form.recommender.data

        customer.company_name = form.company_name.data
        if form.post_code1.data and form.post_code2.data:
            customer.post_code = int(str(form.post_code1.data) + str(form.post_code2.data))
        else:
            customer.post_code = None
        customer.address1 = form.address1.data
        customer.address2 = form.address2.data
        customer.address3 = form.address3.data

        db.session.add(customer)
        db.session.commit()
        flash(gettext("New customer successfully added."))
        return redirect(url_for("customers"))
    return render_template('settings/addCustomer.html',
                           title=gettext("Add New Customer"),
                           form=form)
Example #2
0
 def registration_notice(sender, user, **extra):
     # site_url = 'https://%s' % app.config['NOI_DEPLOY']
     # sender = app.config['MAIL_USERNAME']
     sender = '*****@*****.**'
     mail.send_message(
         subject=gettext(
             "%(user)s registered on Network of "
             "Innovators!",
             user=user.full_name
             ),
         body=gettext(
             "%(user)s Created a new profile: "
             "\n\n"
             "\nName: %(user)s"
             "\nEmail: %(email)s"
             "\nPosition: %(position)s"
             "\nOrganization: %(organization)s"
             "\nOrganization Type: %(organization_type)s"
             "\nCountry: %(country)s"
             "\nCity: %(city)s"
             "\n\n",
             user=user.full_name,
             email=user.email,
             position=user.position,
             organization=user.organization,
             organization_type=user.organization_type,
             country=user.country,
             city=user.city
             ),
         sender=sender,
         recipients=["*****@*****.**", "*****@*****.**", "*****@*****.**"]
         )
Example #3
0
def hosting(action=None):
    """Change various settings for Helios.
    """
    if action == "confirm":
        current_user.userdb.drop()
        flash(gettext("Deine Datenbank wurde gelöscht."), 'success')
        return redirect(url_for('.hosting'))

    form = HostingForm()

    if form.validate_on_submit():
        if form.action.data == "create":
            current_user.userdb.create(form.password.data)
            flash(gettext("Deine Datenbank wurde erstellt."), 'success')
        else:
            current_user.userdb.change_password(form.password.data)
    elif form.is_submitted():
        flash_formerrors(form)

    try:
        user_has_db = current_user.userdb.has_db
    except NotImplementedError:
        abort(403)

    return render_template('usersuite/hosting.html',
                           form=form, user_has_db=user_has_db, action=action)
Example #4
0
def delete(resource_identifier):
    """delete a resource"""
    resource = Resource.query.filter_by(identifier=resource_identifier).first()
    if g.user.role != 'admin' and g.user.username != resource.owner.username:
        msg = gettext('You do not have access to delete this resource')
        flash(msg, 'danger')
        return redirect(url_for('get_resource_by_id', lang=g.current_lang,
                                identifier=resource_identifier))

    if resource is None:
        flash(gettext('Resource not found'), 'danger')
        return redirect(url_for('home', lang=g.current_lang))

    runs = Run.query.filter_by(resource_identifier=resource_identifier).all()

    for run in runs:
        DB.session.delete(run)
    resource.clear_recipients()
    DB.session.delete(resource)

    try:
        DB.session.commit()
        flash(gettext('Resource deleted'), 'success')
        return redirect(url_for('home', lang=g.current_lang))
    except Exception as err:
        DB.session.rollback()
        flash(str(err), 'danger')
        return redirect(url_for(request.referrer))
Example #5
0
 def create_tasks(self, task_repo, project_id, **form_data):
     """Create tasks."""
     from pybossa.model.task import Task
     """Create tasks from a remote source using an importer object and
     avoiding the creation of repeated tasks"""
     empty = True
     n = 0
     importer = self._create_importer_for(**form_data)
     for task_data in importer.tasks():
         task = Task(project_id=project_id)
         [setattr(task, k, v) for k, v in task_data.iteritems()]
         found = task_repo.get_task_by(project_id=project_id, info=task.info)
         if found is None:
             task_repo.save(task)
             n += 1
             empty = False
     if empty:
         msg = gettext('It looks like there were no new records to import')
         return ImportReport(message=msg, metadata=None, total=n)
     metadata = importer.import_metadata()
     msg = str(n) + " " + gettext('new tasks were imported successfully')
     if n == 1:
         msg = str(n) + " " + gettext('new task was imported successfully')
     report = ImportReport(message=msg, metadata=metadata, total=n)
     return report
Example #6
0
def delete_mail():
    """Resets the users forwarding mail attribute
    in his LDAP entry.
    """
    form = DeleteMailForm()

    if form.validate_on_submit():
        password = form.password.data

        try:
            try:
                del current_user.mail
            except AttributeError:
                with current_user.tmp_authentication(password):
                    del current_user.mail
        except UserNotFound:
            flash(gettext("Nutzer nicht gefunden!"), "error")
        except PasswordInvalid:
            flash(gettext("Passwort war inkorrekt!"), "error")
        except LDAPConnectionError:
            flash(gettext("Nicht genügend LDAP-Rechte!"), "error")
        else:
            flash(gettext("E-Mail-Adresse wurde zurückgesetzt"), "success")
            return redirect(url_for('.index'))
    elif form.is_submitted():
        flash_formerrors(form)

    return render_template('usersuite/delete_mail.html', form=form)
Example #7
0
def change_mac():
    """As user, change the MAC address of your device.
    """
    form = ChangeMACForm()

    if form.validate_on_submit():
        password = form.password.data
        mac = form.mac.data

        try:
            current_user.re_authenticate(password)

        except PasswordInvalid:
            flash(gettext("Passwort war inkorrekt!"), "error")
        else:
            current_user.mac = mac
            logger.info('Successfully changed MAC address',
                        extra={'data': {'mac': mac},
                               'tags': {'rate_critical': True}})

            flash(gettext("MAC-Adresse wurde geändert!"), 'success')
            flash(gettext("Es kann bis zu 10 Minuten dauern, "
                          "bis die Änderung wirksam ist."), 'info')

            return redirect(url_for('.index'))
    elif form.is_submitted():
        flash_formerrors(form)

    form.mac.default = current_user.mac.value

    return render_template('usersuite/change_mac.html', form=form)
Example #8
0
    def put(self, id):
        user = User.get_by_id(id)

        if user is None or not user.can_edit():
            flash(gettext('The user was not found'), 'error')
            return redirect(url_for('UsersView:index'))

        if request.method in ['POST']:
            form = EditUserForm()
            if form.validate_on_submit():
                if form.password.data:
                    user.set_password(form.password.data)
                del form.password
                form.populate_obj(user)
                user.save()
                refresh()
                return resp(url_for('UsersView:get', id=user.id), redirect=True,
                            message=gettext('User was succesfully updated'))
            else:
                return resp('admin/users/edit.html', form=form, user=user,
                            message=gettext('Invalid submission, please check the messages below'))
        else:
            form = EditUserForm(user=user)

        return resp('admin/users/edit.html', form=form, user=user)
Example #9
0
def change_mail():
    """Frontend page to change the user's mail address"""

    form = ChangeMailForm()

    if form.validate_on_submit():
        password = form.password.data
        email = form.email.data

        try:
            try:
                current_user.mail = email
            except AttributeError:
                with current_user.tmp_authentication(password):
                    current_user.mail = email
        except UserNotFound:
            flash(gettext("Nutzer nicht gefunden!"), "error")
        except PasswordInvalid:
            flash(gettext("Passwort war inkorrekt!"), "error")
        except LDAPConnectionError:
            flash(gettext("Nicht genügend LDAP-Rechte!"), "error")
        else:
            flash(gettext("E-Mail-Adresse wurde geändert"), "success")
            return redirect(url_for('.index'))
    elif form.is_submitted():
        flash_formerrors(form)

    return render_template('usersuite/change_mail.html', form=form)
Example #10
0
def group(id):
    group = Group.query.filter_by(id=id).first_or_404()
    if not current_user in group.users:
        abort(404)

    form = None
    if group.changeable:
        form = GroupAddMemberForm()
        if current_user == group.admin and form.validate_on_submit():
            user = User.query.filter(func.lower(User.username) == func.lower(form.member.data)).first()

            if not user:
                flash(gettext("User not found."), "error")
                return redirect(url_for("group", id=group.id))

            if user in group.users:
                flash(gettext("User is already a member of the group."), "info")
                return redirect(url_for("group", id=group.id))

            group.users.append(user)
            db.session.commit()
            flash(gettext("The user was added to the group."), "success")
            return redirect(url_for("group", id=group.id))

    return render_template("user/group.jade", group=group, form=form)
Example #11
0
def pre_request():
    request.errors = []

    preferences = Preferences(themes, list(categories.keys()), engines, plugins)
    request.preferences = preferences
    try:
        preferences.parse_dict(request.cookies)
    except:
        request.errors.append(gettext('Invalid settings, please edit your preferences'))

    # merge GET, POST vars
    # request.form
    request.form = dict(request.form.items())
    for k, v in request.args.items():
        if k not in request.form:
            request.form[k] = v

    if request.form.get('preferences'):
        preferences.parse_encoded_data(request.form['preferences'])
    else:
        try:
            preferences.parse_dict(request.form)
        except Exception as e:
            logger.exception('invalid settings')
            request.errors.append(gettext('Invalid settings'))

    # request.user_plugins
    request.user_plugins = []
    allowed_plugins = preferences.plugins.get_enabled()
    disabled_plugins = preferences.plugins.get_disabled()
    for plugin in plugins:
        if ((plugin.default_on and plugin.id not in disabled_plugins)
                or plugin.id in allowed_plugins):
            request.user_plugins.append(plugin)
Example #12
0
def generate_available_stock_csv(categories=[]):
    path = os.path.join(CSV_PATH, ('axm_stock_' + datetime.utcnow().strftime("%Y%m%d") + '.csv'))
    outfile = open(path, 'wb+')
    outcsv = csv.writer(outfile)
    products = Product.query\
        .filter_by(active_flg=True)
    if categories:
        products = products.filter(Product.category_id.in_(categories))
    products = products.order_by(Product.category_id)\
        .order_by(Product.maker_id)\
        .order_by(Product.code)\
        .all()
    headers = [gettext('Product code'), gettext('Product Name'), gettext('Quantity on stock'), gettext('Planned time of delivery')]
    outcsv.writerow([unicode(header).encode('utf-8') for header in headers])
    for product in products:
        dtd = product.maker.standard_delivery_days if product.maker.standard_delivery_days else None
        month_and_third = days_to_month_and_third(dtd)
        if product.limited_flg:
            text_dtd = gettext('Product with limited number of items')
        else:
            text_dtd = month_and_third_to_text(month_and_third)
        columns = [product.code, product.desc_JP, product.available_qty, text_dtd]
        outcsv.writerow([unicode(column).encode('utf-8') for column in columns])

    outfile.close()

    match = re.search(r"[^a-zA-Z](csv)[^a-zA-Z]", path)
    pos = match.start(1)
    filename = path[pos:]

    return filename
Example #13
0
def register():
    """Provides registering for user"""

    # if register form is submitted
    form = RegisterForm(request.form)

    # verify the register form
    if form.validate_on_submit():
        # create user and add to database
        user = User(
            username=form.username.data,
            password=generate_password_hash(form.password.data),
            email=form.email.data
        )
        db.session.add(user)
        db.session.commit()

        # sending email
        token = generate_confirmation_token(user.email)
        confirm_url = url_for('users.confirm_email', token=token, _external=True)
        html = render_template('users/activate.html', confirm_url=confirm_url)
        subject = gettext(u"Please confirm your email")
        send_email(user.email, subject, html)

        #login_user(user)

        # everything okay so far
        flash(gettext(u'Confirmation email has been sent'), 'info')
        return redirect(url_for('users.login'))

    return render_template('users/register.html', form=form)
Example #14
0
File: app.py Project: janLo/sipa
def usertraffic():
    """For anonymous users with a valid IP
    """
    try:
        ip = request.remote_addr
        trafficdata = query_trafficdata(ip)

        if current_user.is_authenticated():
            if current_user.userid is user_id_from_ip(ip):
                flash(gettext(u"Ein anderer Nutzer als der für diesen Anschluss"
                              u" Eingetragene ist angemeldet!"), "warning")
                flash(gettext("Hier werden die Trafficdaten "
                              "dieses Anschlusses angezeigt"), "info")
    except ForeignIPAccessError:
        flash(gettext(u"Deine IP gehört nicht zum Wohnheim!"), "error")

        if current_user.is_authenticated():
            flash(gettext(u"Da du angemeldet bist, kannst du deinen Traffic "
                          u"hier in der Usersuite einsehen."), "info")
            return redirect(url_for('usersuite.usersuite'))
        else:
            flash(gettext(u"Um deinen Traffic von außerhalb einsehen zu können,"
                          u" musst du dich anmelden."), "info")
            return redirect(url_for('login'))

    # todo test if the template works if called from this position
    return render_template("usertraffic.html", usertraffic=trafficdata)
Example #15
0
    def __init__(self, url, **kwargs):
        """Create a killmail from a CREST killmail link.

        :param str url: the CREST killmail URL.
        :raises ValueError: if ``url`` is not a CREST URL.
        :raises LookupError: if the CREST API response is in an unexpected
            format.
        """
        super(CRESTMail, self).__init__(**kwargs)
        self.url = url
        match = self.crest_regex.search(self.url)
        if match:
            self.kill_id = match.group('kill_id')
        else:
            # TRANS: The %(url)s in this case will be replaced with the
            # offending URL.
            raise ValueError(gettext(u"'%(url)s' is not a valid CREST killmail",
                    url=self.url))
        parsed = urlparse(self.url, scheme='https')
        if parsed.netloc == '':
            parsed = urlparse('//' + url, scheme='https')
            self.url = parsed.geturl()
        # Check if it's a valid CREST URL
        resp = self.requests_session.get(self.url)
        # JSON responses are defined to be UTF-8 encoded
        if resp.status_code != 200:
            # TRANS: The %s here will be replaced with the (non-localized
            # probably) error from CCP.
            raise LookupError(gettext(u"Error retrieving CREST killmail: "
                                      u"%(error)s",
                                      error=resp.json()[u'message']))
        try:
            json = resp.json()
        except ValueError as e:
            # TRANS: The %(code)d in this message will be replaced with the
            # HTTP status code recieved from CCP.
            raise LookupError(gettext(u"Error retrieving killmail data: "
                                      u"%(code)d", code=resp.status_code))
        victim = json[u'victim']
        char = victim[u'character']
        corp = victim[u'corporation']
        ship = victim[u'shipType']
        alliance = victim[u'alliance']
        self.pilot_id = char[u'id']
        self.pilot = char[u'name']
        self.corp_id = corp[u'id']
        self.corp = corp[u'name']
        self.alliance_id = alliance[u'id']
        self.alliance = alliance[u'name']
        self.ship_id = ship[u'id']
        self.ship = ship[u'name']
        solarSystem = json[u'solarSystem']
        self.system_id = solarSystem[u'id']
        self.system = solarSystem[u'name']
        # CREST Killmails are always verified
        self.verified = True
        # Parse the timestamp
        time_struct = time.strptime(json[u'killTime'], '%Y.%m.%d %H:%M:%S')
        self.timestamp = dt.datetime(*(time_struct[0:6]),
                tzinfo=utc)
Example #16
0
def generate_credit_chart(traffic_data, inline=True, max_credit=(63 * 1024 ** 2)):
    """Create a graph object from the input traffic data with pygal.
     If inline is set, the chart is being passed the option to not add an xml
     declaration header to the beginning of the `render()` output, so it can
      be directly included in HTML code (wrapped by a `<figure>`)
    :param traffic_data: The traffic data as given by `user.traffic_history`
    :param inline: Determines the option `disable_xml_declaration`
    :return: The graph object
    """
    raw_max = max_credit
    divisions = max_divisions(raw_max)
    max = reduce_by_base(raw_max, divisions)

    credit_chart = default_chart(
        pygal.Line,
        gettext("Credit (GiB)"),
        inline,
        value_formatter=lambda value: format_as_traffic(value, divisions, divide=False),
    )
    credit_chart.range = (0, max)

    credit_chart.x_labels = (get_weekday(day['day']) for day in traffic_data)
    credit_chart.add(gettext("Credit"),
                     [reduce_by_base(day['credit'], divisions=divisions)
                      for day in traffic_data])
    credit_chart.add(gettext("Maximum"),
                     [max]*len(traffic_data),
                     stroke_style={'dasharray': '7', 'width': '2'},
                     fill=False,
                     show_dots=False)

    return credit_chart
Example #17
0
File: app.py Project: janLo/sipa
def login():
    """Login page for users
    """
    form = LoginForm()

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data

        try:
            user = authenticate(username, password)
        except UserNotFound:
            flash(gettext(u"Nutzer nicht gefunden!"), "error")
        except PasswordInvalid:
            flash(gettext(u"Passwort war inkorrekt!"), "error")
        else:
            if isinstance(user, User):
                login_user(user)
    elif form.is_submitted():
        flash_formerrors(form)

    if current_user.is_authenticated():
        return redirect(url_for('usersuite.usersuite'))

    return render_template('login.html', form=form)
Example #18
0
def set_diceware_password(user, password):
    try:
        user.set_password(password)
    except PasswordError:
        flash(gettext(
            'You submitted a bad password! Password not changed.'), 'error')
        return

    try:
        db_session.commit()
    except Exception:
        flash(gettext(
            'There was an error, and the new password might not have been '
            'saved correctly. To prevent you from getting locked '
            'out of your account, you should reset your password again.'),
            'error')
        current_app.logger.error('Failed to update a valid password.')
        return

    # using Markup so the HTML isn't escaped
    flash(Markup("<p>" + gettext(
        "Password updated. Don't forget to "
        "save it in your KeePassX database. New password:") +
        ' <span><code>{}</code></span></p>'.format(password)),
        'success')
    def update(self, **kwargs):
        """Update contents of this review.

        Returns:
            New revision of this review.
        """
        license_id = kwargs.pop('license_id', None)
        if license_id is not None:
            if not self.is_draft:  # If trying to convert published review into draft.
                raise BadRequest(gettext("Changing license of a published review is not allowed."))
            self.license_id = license_id

        language = kwargs.pop('language', None)
        if language is not None:
            self.language = language

        is_draft = kwargs.pop('is_draft', None)
        if is_draft is not None:  # This should be done after all changes that depend on review being a draft.
            if not self.is_draft and is_draft:  # If trying to convert published review into draft.
                raise BadRequest(gettext("Converting published reviews back to drafts is not allowed."))
            self.is_draft = is_draft

        new_revision = Revision.create(self.id, kwargs.pop('text'))
        cache.invalidate_namespace(Review.CACHE_NAMESPACE)

        if kwargs:
            # FIXME: Revision creation and other changes need to be rolled back
            # there, but there's a `commit` in Revision.create.
            raise TypeError('Unexpected **kwargs: %r' % kwargs)

        return new_revision
Example #20
0
File: auth.py Project: icoz/pysymo
def login():
    form = LoginForm()

    if form.validate_on_submit():
        if app.config['AUTH_TYPE'] == 'ldap':
            user_obj = UserLDAP()
        elif app.config['AUTH_TYPE'] == 'plain':
            user_obj = UserPlain()
        else:
            flash(gettext('Unknown authentication type.'), 'warning')
            return render_template('home.html', login_form=form)

        # find user and check password
        user, error = user_obj.get_by_username_w_password(form.username.data, form.password.data)
        if user is None:
            flash(error, 'warning')
        else:
            if login_user(user, remember=form.remember_me.data):
                flash(gettext('Logged in successfully.'), 'success')
                return redirect(url_for('search'))
            else:
                flash(gettext('Unable to log you in.'), 'warning')
                return redirect(url_for('home'))
    else:
        flash_form_errors(form)

    return render_template('home.html', login_form=form)
Example #21
0
File: auth.py Project: icoz/pysymo
def register():
    if app.config['REGISTRATION_ENABLED'] and app.config['AUTH_TYPE'] == 'plain':
        reg_form = RegistrationForm()
        login_form = LoginForm()

        if reg_form.validate_on_submit():
            user = UserPlain(username=reg_form.username.data,
                             password=reg_form.password.data,
                             email=reg_form.email.data)
            # save user to db
            user_id, save_error = user.save()
            if user_id:
                # try to login
                if login_user(user):
                    flash(gettext('Logged in successfully.'), 'success')
                    return redirect(url_for('search'))
                else:
                    flash(gettext('Unable to log you in.'), 'warning')
                    return redirect(url_for('home'))
            else:
                flash(save_error, 'warning')
                return redirect(url_for('register'))
        else:
            flash_form_errors(reg_form)
            return render_template('register.html', reg_form=reg_form, login_form=login_form)
    else:
        return redirect(url_for('home'))
Example #22
0
def add(form_class=WordForm):
    page = request.args.get('page', 1)
    try:
        page = int(page)
        if page < 1:
            page = 1
    except ValueError:
        page = 1

    form = form_class()

    if form.validate_on_submit():
        word = Word(form.word.data, session['language'])
        db.session.add(word)
        db.session.commit()
        # Clear form
        form = form_class(MultiDict())
        flash(gettext(u'The word sucessfully added.'), 'success')
    else:
        if request.method == 'POST':
            flash(gettext(u'Error while trying to save the word.'), 'error')

    words = Word.query.order_by('word.id DESC')\
                      .slice((page - 1)*PER_PAGE, page*PER_PAGE).all()
    words_count = Word.query.order_by('word.id DESC').count()
    pagination = Pagination(page, PER_PAGE, words_count)

    ctx = {
        'form': form,
        'words': words,
        'pagination': pagination,
    }
    
    return render_template('words/add_words.html', **ctx)
Example #23
0
def lcd_reset_flashing(lcd_id):
    control = DaemonControl()
    return_value, return_msg = control.lcd_flash(lcd_id, False)
    if return_value:
        flash(gettext("%(msg)s", msg=return_msg), "success")
    else:
        flash(gettext("%(msg)s", msg=return_msg), "error")
Example #24
0
def computer_command(action):
    """Execute one of several commands as root"""
    if not utils_general.user_has_permission('edit_settings'):
        return redirect(url_for('routes_general.home'))

    try:
        if action not in ['restart', 'shutdown', 'daemon_restart', 'frontend_reload']:
            flash("Unrecognized command: {action}".format(
                action=action), "success")
            return redirect('/settings')
        cmd = '{path}/mycodo/scripts/mycodo_wrapper {action} 2>&1'.format(
                path=INSTALL_DIRECTORY, action=action)
        subprocess.Popen(cmd, shell=True)
        if action == 'restart':
            flash(gettext("System rebooting in 10 seconds"), "success")
        elif action == 'shutdown':
            flash(gettext("System shutting down in 10 seconds"), "success")
        elif action == 'daemon_restart':
            flash(gettext("Command to restart the daemon sent"), "success")
        elif action == 'frontend_reload':
            flash(gettext("Command to reload the frontend sent"), "success")
        return redirect('/settings')
    except Exception as e:
        logger.error("System command '{cmd}' raised and error: "
                     "{err}".format(cmd=action, err=e))
        flash("System command '{cmd}' raised and error: "
              "{err}".format(cmd=action, err=e), "error")
        return redirect(url_for('routes_general.home'))
Example #25
0
File: views.py Project: tekd/noi2
def activity():
    '''
    View for the activity feed of recent events.
    '''

    events = get_latest_events()
    shared_message_form = SharedMessageForm()

    if request.method == 'POST':
        if not current_user.is_authenticated():
            flash(gettext(u'You must log in to post a message.'), 'error')
        elif not current_user.display_in_search:
            flash(gettext(u'We need your name before you can post a message.'), 'error')
        elif shared_message_form.validate():
            data = shared_message_form.message.data
            msg = SharedMessageEvent.from_user(
                current_user,
                message=data
            )
            db.session.add(msg)
            db.session.commit()
            flash(gettext(u'Message posted!'))
            return redirect(url_for('views.activity'))

    return render_template('activity.html', **{
        'user': current_user,
        'events': events,
        'blog_posts': get_blog_posts(),
        'page_config_json': json_blob(
            LOADING_TEXT=gettext("Loading...")
        ),
        'most_complete_profiles': User.get_most_complete_profiles(limit=5),
        'most_connected_profiles': User.get_most_connected_profiles(limit=5)
    })
Example #26
0
def editCategory(id=0):
    category = Category.query.filter_by(id=id).first()
    if category == None:
        flash(gettext('Category not found.'))
        return redirect(url_for('categories'))
    form = AddCategoryForm(obj=category)
    if form.validate_on_submit():

        #delete category
        if 'delete' in request.form:
            db.session.delete(category)
            db.session.commit()
            return redirect(url_for("categories"))

        #update category
        category.name_CS_ = form.name_CS.data
        category.name_JP = form.name_JP.data
        db.session.add(category)
        db.session.commit()
        flash(gettext("Category successfully changed."))
        return redirect(url_for("categories"))
    return render_template('settings/editCategory.html',
                           title=gettext("Edit Category"),
                           category=category,
                           form=form)
Example #27
0
    def post(self):
        form = PostForm()
        if request.method == 'POST':
            if form.validate_on_submit():
                post = Post.create()
                form.populate_obj(post)
                f = request.files.get('file')
                post.user = current_user

                if f:
                    picture = Picture.create()
                    picture.save_file(f, current_user)
                    post.cover_picture_id = picture.id if picture else 0

                post.update_score(page_view=1)
                post.save()

                if form.remain.data:
                    url = url_for('PostsView:put', id=post.id)
                else:
                    url = url_for('PostsView:get', id=post.id)

                return resp(url, redirect=True,
                            message=gettext('Stamp succesfully created'))
            else:
                return resp('admin/posts/edit.html', status=False, form=form,
                            message=gettext('Invalid submission, please check the message below'))

        return resp('admin/posts/edit.html', form=form)
Example #28
0
def lcd_display_del(lcd_data_id, delete_last=False):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['display']['title'])
    error = []

    lcd_data_this = LCDData.query.filter(
        LCDData.unique_id == lcd_data_id).first()
    lcd_data_all = LCDData.query.filter(
        LCDData.lcd_id == lcd_data_this.lcd_id).all()
    lcd = LCD.query.filter(
        LCD.unique_id == lcd_data_this.lcd_id).first()

    if lcd.is_activated:
        error.append(gettext("Deactivate LCD controller before modifying"
                             " its settings"))
    if not delete_last and len(lcd_data_all) < 2:
        error.append(gettext("The last display cannot be deleted"))

    if not error:
        try:
            delete_entry_with_id(LCDData,
                                 lcd_data_id)
            db.session.commit()
        except Exception as except_msg:
            error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_page.page_lcd'))
Example #29
0
def recover():
    """recover"""
    if request.method == 'GET':
        return render_template('recover_password.html')
    username = request.form['username']
    registered_user = User.query.filter_by(username=username, ).first()
    if registered_user is None:
        flash(gettext('Invalid username'), 'danger')
        return redirect(url_for('recover', lang=g.current_lang))

    fromaddr = '%s <%s>' % (CONFIG['GHC_SITE_TITLE'],
                            CONFIG['GHC_ADMIN_EMAIL'])
    toaddr = registered_user.email

    template_vars = {
        'config': CONFIG,
        'password': registered_user.password
    }
    msg = render_template2('recover_password_email.txt', template_vars)

    send_email(CONFIG['GHC_SMTP'], fromaddr, toaddr, msg)

    flash(gettext('Password sent via email'), 'success')

    if 'next' in request.args:
        return redirect(request.args.get('next'))
    return redirect(url_for('home', lang=g.current_lang))
Example #30
0
def registration():
    if not current_app.config['REGISTRATION_OPEN']:
        return render_template('registration/registration_closed.html', page_title=gettext('Registration is closed'))

    page_title = gettext('Registration in library')

    captcha = None
    captcha_error = None
    if current_app.captcha:
        captcha = current_app.captcha.generate()

    form = AuthorRegistrationForm()
    if form.validate_on_submit():
        data = dict(form.data)
        if current_app.captcha:
            data = current_app.captcha.copy_fields(data, request.form)
        try:
            Author.bl.register(data)
        except CaptchaError:
            captcha_error = 'Вы не доказали, что вы не робот'
        except ValidationError as exc:
            form.set_errors(exc.errors)
        else:
            if current_app.config['AUTH_LOG']:
                current_app.logger.info('%s requested registration (ID: N/A, IP: %s)', data.get('username'), request.remote_addr)
            return redirect(url_for('auth.registration_complete'))

    return render_template(
        'registration/registration_form.html',
        form=form,
        captcha=captcha,
        captcha_error=captcha_error,
        page_title=page_title,
        username_help=current_app.config['USERNAME_HELP'],
    )
Example #31
0
def update_url():
    """
    更新修改 url权限
    :return:
    """
    tid = request.argget.all("id")
    method = request.argget.all("method")
    login_auth = str_to_num(request.argget.all("login_auth", 0))
    custom_permission = json_to_pyseq(
        request.argget.all("custom_permission", []))
    s, r = arg_verify([("id", tid)], required=True)
    if not s:
        return r

    s, r = arg_verify(
        [(gettext("method"), method)],
        required=True,
        only=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"])
    if not s:
        return r

    permission = 0x0
    for i in custom_permission:
        try:
            i = int(i)
            permission = permission | int(i)
        except BaseException:
            pass

    # 修改权限验证
    data = {
        "msg":
        gettext(
            "The current user permissions are lower than the permissions you want to modify,"
            " without permission to modify"),
        "msg_type":
        "w",
        "http_status":
        401
    }
    user_role = mdb_user.db.role.find_one(
        {"_id": ObjectId(current_user.role_id)})
    # 如果当前用户的权限最高位 小于 要修改成的权重的最高位,是不可以的
    if get_num_digits(user_role["permissions"]) <= get_num_digits(permission):
        return data

    old_permission = 0
    old_url_per = mdb_sys.db.sys_urls.find_one({"_id": ObjectId(tid)})
    if old_url_per and method in old_url_per["custom_permission"]:
        old_permission = old_url_per["custom_permission"][method]

    # 如果当前用户的权限最高位 小于 要修改url请求的权限,也是不可以
    if get_num_digits(
            user_role["permissions"]) <= get_num_digits(old_permission):
        return data

    r = mdb_sys.db.sys_urls.update_one({"_id": ObjectId(tid)}, {
        "$set": {
            "custom_permission.{}".format(method): permission,
            "login_auth.{}".format(method): login_auth
        }
    })
    if r.modified_count:
        # 清除缓存
        r = mdb_sys.db.sys_urls.find_one({"_id": ObjectId(tid)})
        if r:
            cache.delete_autokey(fun="get_sys_url",
                                 db_type="redis",
                                 url=r['url'].rstrip("/"))
        data = {
            "msg": gettext("Modify the success"),
            "msg_type": "s",
            "http_status": 201
        }
    else:
        data = {
            "msg": gettext("No modification"),
            "msg_type": "w",
            "http_status": 400
        }
    return data
Example #32
0
def addNewItem(add_type, sid=None):

    if not add_type in dispatch:
        flash(gettext('Unknown type of content to add!'))
        return redirect(url_for('index'))
    if add_type == 'release' and sid == None:
        flash(
            gettext(
                'Adding a release must involve a series-id. How did you even do that?'
            ))
        return redirect(url_for('index'))

    form_class, callee, message = dispatch[add_type]
    have_auth = g.user.is_authenticated()

    if add_type == 'release':
        series = Series.query.filter(Series.id == sid).scalar()

        if not series:
            return render_template(
                'not-implemented-yet.html',
                message=
                "Trying to add a release for series sid: '%s' that doesn't exist? Wat? This shouldn't happen. Are you abusing something?"
                % sid)

        form = form_class(series_id=series.id, is_oel=series.tl_type)

        altn = AlternateTranslatorNames.query.all()
        altfmt = [(x.group, x.name) for x in altn if x.group]
        altfmt.sort(key=lambda x: x[1])
        form.group.choices = altfmt
    else:
        form = form_class()

    print("Trying to validate")
    # print(form.validate_on_submit())
    if form.validate_on_submit():
        print("Post request. Validating")
        if have_auth:
            print("Validation succeeded!")
            return callee(form)
        else:
            flash(gettext('You must be logged in to make changes!'))

    else:
        if not have_auth:
            flash(
                gettext(
                    'You do not appear to be logged in. Any changes you make will not be saved!'
                ))

    if add_type == 'release':

        altfmt = [(-1, "")] + altfmt
        form.group.choices = altfmt

        if 'Not a valid choice' in form.group.errors:
            form.group.errors.remove('Not a valid choice')

        return render_template('add-release.html',
                               form=form,
                               add_name=add_type,
                               message=message,
                               series=series)

    if add_type == 'post':
        return render_template(
            'add-post.html',
            form=form,
        )

    if add_type == 'series':
        return render_template('add-series.html',
                               form=form,
                               add_name=add_type,
                               message=message)

    else:
        return render_template('add.html',
                               form=form,
                               add_name=add_type,
                               message=message)
Example #33
0
def validate_product(product):
    if not product.get('name'):
        return jsonify({'name': gettext('Name not found')}), 400
Example #34
0
def logout():
    g.user.revoke_token()
    db.session.commit()
    logout_user()
    flash(gettext('You were logged out successfully.'), category='success')
    return redirect(url_for('flicket_bp.index'))
Example #35
0
 def get_template_configs(self):
     return [
         dict(type="settings",
              name=gettext("Printer Dialogs"),
              custom_bindings=False)
     ]
Example #36
0
        self._close_prompt()
        if "{choice}" in self._command:
            self._printer.commands([self._command.format(choice=choice)])
        else:
            self._printer.commands([
                "{command} S{choice}".format(command=self._command,
                                             choice=choice)
            ])


__plugin_name__ = "Action Command Prompt Support"
__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection"
__plugin_author__ = "Gina Häußge"
__plugin_disabling_discouraged__ = gettext(
    "Without this plugin your printer will no longer be able to trigger"
    " confirmation or selection prompts in OctoPrint")
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = ActionCommandPromptPlugin()
__plugin_hooks__ = {
    "octoprint.comm.protocol.action":
    __plugin_implementation__.action_command_handler,
    "octoprint.comm.protocol.gcode.queuing":
    __plugin_implementation__.gcode_queuing_handler,
    "octoprint.comm.protocol.firmware.capabilities":
    __plugin_implementation__.firmware_capability_handler,
    "octoprint.access.permissions":
    __plugin_implementation__.get_additional_permissions
}
    'thermal': cmocean.cm.thermal,
    'neo_sst': mcolors.ListedColormap(
        np.loadtxt(os.path.join(data_dir, 'neo_sst.txt'))),
    'BuYlRd': mcolors.ListedColormap(
        np.loadtxt(os.path.join(data_dir, 'BuYlRd.txt'))),
    'temperature': mcolors.ListedColormap(
        np.loadtxt(os.path.join(data_dir, 'temperature.txt'))),
}
colormaps['wind'] = colormaps['velocity']

# This is a little odd, but it has a purpose.
# These gettext calls don't really do anything, but it registers the keys with
# Babel so that they'll end up in the translation list.
# If the gettext calls were in the definition of colormap_names, they'd get
# executed before the user's locale is known and would always be in English.
gettext('Ammonium Concentration')
gettext('Anomaly')
gettext('Bathymetry')
gettext('Biogenic Silicon Concentration')
gettext('Chlorophyll')
gettext('Diatoms Concentration as Nitrogen')
gettext('Dissolved Organic Nitrogen Concentration')
gettext('Eastward Current')
gettext('Flagellates Concentration as Nitrogen')
gettext('Greyscale')
gettext('Ice')
gettext('Iron')
gettext('Mercator Ocean Current')
gettext('Mercator')
gettext('Mesodinium rubrum Concentration as Nitrogen')
gettext('Mesozooplankton Concentration as Nitrogen')
Example #38
0
def validate_method_data(form_data, this_method):
    if this_method.method_type == 'Date':
        if (not form_data.time_start.data or
                not form_data.time_end.data or
                form_data.setpoint_start.data == ''):
            flash(gettext("Required: Start date/time, end date/time, "
                          "start setpoint"), "error")
            return 1
        try:
            start_time = datetime.strptime(form_data.time_start.data,
                                           '%Y-%m-%d %H:%M:%S')
            end_time = datetime.strptime(form_data.time_end.data,
                                         '%Y-%m-%d %H:%M:%S')
        except ValueError:
            flash(gettext("Invalid Date/Time format. Correct format: "
                          "MM/DD/YYYY HH:MM:SS"), "error")
            return 1
        if end_time <= start_time:
            flash(gettext("The end time/date must be after the start "
                          "time/date."), "error")
            return 1

    elif this_method.method_type == 'Daily':
        if (not form_data.daily_time_start.data or
                not form_data.daily_time_end.data or
                form_data.setpoint_start.data == ''):
            flash(gettext("Required: Start time, end time, start "
                          "setpoint"), "error")
            return 1
        try:
            start_time = datetime.strptime(form_data.daily_time_start.data,
                                           '%H:%M:%S')
            end_time = datetime.strptime(form_data.daily_time_end.data,
                                         '%H:%M:%S')
        except ValueError:
            flash(gettext("Invalid Date/Time format. Correct format: "
                          "HH:MM:SS"), "error")
            return 1
        if end_time <= start_time:
            flash(gettext("The end time must be after the start time."),
                  "error")
            return 1

    elif this_method.method_type == 'Duration':
        try:
            if form_data.restart.data:
                return 0
        except Exception:
            pass
        try:
            if form_data.duration_end.data:
                return 0
        except Exception:
            pass
        if (not form_data.duration.data or
                not form_data.setpoint_start.data):
            flash(gettext("Required: Duration, start setpoint"),
                  "error")
            return 1
        if not is_positive_integer(form_data.duration.data):
            flash(gettext("Required: Duration must be positive"),
                  "error")
            return 1
Example #39
0
def method_add(form_add_method):
    """ Add line to method_data table """
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['method']['title'])
    error = []

    start_time = None
    end_time = None

    method = Method.query.filter(
        Method.unique_id == form_add_method.method_id.data).first()
    display_order = csv_to_list_of_str(method.method_order)

    try:
        if validate_method_data(form_add_method, method):
            return 1

        if method.method_type == 'DailySine':
            add_method_data = MethodData.query.filter(
                MethodData.method_id == form_add_method.method_id.data).first()
            add_method_data.amplitude = form_add_method.amplitude.data
            add_method_data.frequency = form_add_method.frequency.data
            add_method_data.shift_angle = form_add_method.shift_angle.data
            add_method_data.shift_y = form_add_method.shiftY.data
            db.session.commit()
            return 0

        elif method.method_type == 'DailyBezier':
            if not 0 <= form_add_method.shift_angle.data <= 360:
                flash(gettext("Error: Angle Shift is out of range. It must be "
                              "<= 0 and <= 360."), "error")
                return 1
            if form_add_method.x0.data <= form_add_method.x3.data:
                flash(gettext("Error: X0 must be greater than X3."), "error")
                return 1
            add_method_data = MethodData.query.filter(
                MethodData.method_id == form_add_method.method_id.data).first()
            add_method_data.shift_angle = form_add_method.shift_angle.data
            add_method_data.x0 = form_add_method.x0.data
            add_method_data.y0 = form_add_method.y0.data
            add_method_data.x1 = form_add_method.x1.data
            add_method_data.y1 = form_add_method.y1.data
            add_method_data.x2 = form_add_method.x2.data
            add_method_data.y2 = form_add_method.y2.data
            add_method_data.x3 = form_add_method.x3.data
            add_method_data.y3 = form_add_method.y3.data
            db.session.commit()
            return 0

        if method.method_type == 'Date':
            start_time = datetime.strptime(
                form_add_method.time_start.data,
                '%Y-%m-%d %H:%M:%S')
            end_time = datetime.strptime(
                form_add_method.time_end.data,
                '%Y-%m-%d %H:%M:%S')
        elif method.method_type == 'Daily':
            start_time = datetime.strptime(
                form_add_method.daily_time_start.data,
                '%H:%M:%S')
            end_time = datetime.strptime(
                form_add_method.daily_time_end.data,
                '%H:%M:%S')

        if method.method_type in ['Date', 'Daily']:
            # Check if the start time comes after the last entry's end time
            display_order = csv_to_list_of_str(method.method_order)
            if display_order:
                last_method = MethodData.query.filter(
                    MethodData.unique_id == display_order[-1]).first()
            else:
                last_method = None

            if last_method is not None:
                if method.method_type == 'Date':
                    last_method_end_time = datetime.strptime(
                        last_method.time_end,
                        '%Y-%m-%d %H:%M:%S')
                elif method.method_type == 'Daily':
                    last_method_end_time = datetime.strptime(
                        last_method.time_end,
                        '%H:%M:%S')
                else:
                    last_method_end_time = None

                if (start_time and last_method_end_time and
                        start_time < last_method_end_time):
                    flash(gettext("The new entry start time (%(st)s) "
                                  "cannot overlap the last entry's end "
                                  "time (%(et)s). Note: They may be the "
                                  "same time.",
                                  st=last_method_end_time,
                                  et=start_time),
                          "error")
                    return 1

        add_method_data = MethodData()
        add_method_data.method_id = form_add_method.method_id.data

        if method.method_type == 'Date':
            add_method_data.time_start = start_time.strftime(
                '%Y-%m-%d %H:%M:%S')
            add_method_data.time_end = end_time.strftime(
                '%Y-%m-%d %H:%M:%S')

        elif method.method_type == 'Daily':
            add_method_data.time_start = start_time.strftime('%H:%M:%S')
            add_method_data.time_end = end_time.strftime('%H:%M:%S')

        elif method.method_type == 'Duration':
            if form_add_method.restart.data:
                add_method_data.duration_sec = 0
                add_method_data.duration_end = form_add_method.duration_end.data
            else:
                add_method_data.duration_sec = form_add_method.duration.data

        add_method_data.setpoint_start = form_add_method.setpoint_start.data
        add_method_data.setpoint_end = form_add_method.setpoint_end.data


        db.session.add(add_method_data)
        db.session.commit()

        # Add line to method data list
        method.method_order = add_display_order(
            display_order, add_method_data.unique_id)
        db.session.commit()

        if method.method_type == 'Date':
            flash(gettext("Added duration to method from %(st)s to "
                          "%(end)s", st=start_time, end=end_time),
                  "success")
        elif method.method_type == 'Daily':
            flash(gettext("Added duration to method from %(st)s to "
                          "%(end)s",
                          st=start_time.strftime('%H:%M:%S'),
                          end=end_time.strftime('%H:%M:%S')),
                  "success")
        elif method.method_type == 'Duration':
            if form_add_method.restart.data:
                flash(gettext("Added method restart"), "success")
            else:
                flash(gettext("Added duration to method for %(sec)s seconds",
                              sec=form_add_method.duration.data), "success")

    except Exception as except_msg:
        logger.exception(1)
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_method.method_list'))
Example #40
0
 def get_friendly_name(self):
     return gettext("kerberos")
Example #41
0
    def getinfo(self, path=None, getsize=True, name=None, req=None):
        """
        Returns a JSON object containing information
        about the given file.
        """
        path = unquote(path)
        if hasattr(str, 'decode'):
            path = unquote(path).encode('utf-8').decode('utf-8')
        if self.dir is None:
            self.dir = ""
        orig_path = u"{0}{1}".format(self.dir, path)

        try:
            Filemanager.check_access_permission(self.dir, path)
        except Exception as e:
            thefile = {
                'Filename': split_path(path)[-1],
                'FileType': '',
                'Path': path,
                'Error': gettext(u"Error: {0}".format(e)),
                'Code': 0,
                'Info': '',
                'Properties': {
                    'Date Created': '',
                    'Date Modified': '',
                    'Width': '',
                    'Height': '',
                    'Size': ''
                }
            }
            return thefile

        user_dir = path
        thefile = {
            'Filename': split_path(orig_path)[-1],
            'FileType': '',
            'Path': user_dir,
            'Error': '',
            'Code': 1,
            'Info': '',
            'Properties': {
                'Date Created': '',
                'Date Modified': '',
                'Width': '',
                'Height': '',
                'Size': ''
            }
        }

        if not path_exists(orig_path):
            thefile['Error'] = gettext(u"'{0}' file does not exist.".format(
                path))
            thefile['Code'] = -1
            return thefile

        if split_path(user_dir)[-1] == '/'\
                or os.path.isfile(orig_path) is False:
            thefile['FileType'] = 'Directory'
        else:
            thefile['FileType'] = splitext(user_dir)

        created = time.ctime(os.path.getctime(orig_path))
        modified = time.ctime(os.path.getmtime(orig_path))

        thefile['Properties']['Date Created'] = created
        thefile['Properties']['Date Modified'] = modified
        thefile['Properties']['Size'] = sizeof_fmt(getSize(orig_path))

        return thefile
Example #42
0
def method_mod(form_mod_method):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['modify']['title'],
        controller=TRANSLATIONS['method']['title'])
    error = []

    method = Method.query.filter(
        Method.unique_id == form_mod_method.method_id.data).first()
    method_data = MethodData.query.filter(
        MethodData.unique_id == form_mod_method.method_data_id.data).first()
    display_order = csv_to_list_of_str(method.method_order)

    try:
        if form_mod_method.delete.data:
            delete_entry_with_id(
                MethodData, form_mod_method.method_data_id.data)
            method_order = Method.query.filter(
                Method.unique_id == method.unique_id).first()
            display_order = csv_to_list_of_str(method_order.method_order)
            display_order.remove(method_data.unique_id)
            method_order.method_order = list_to_csv(display_order)
            db.session.commit()
            return 0

        if form_mod_method.rename.data:
            method.name = form_mod_method.name.data
            db.session.commit()
            return 0

        # Ensure data is valid
        if validate_method_data(form_mod_method, method):
            return 1

        if method.method_type == 'Date':
            start_time = datetime.strptime(form_mod_method.time_start.data, '%Y-%m-%d %H:%M:%S')
            end_time = datetime.strptime(form_mod_method.time_end.data, '%Y-%m-%d %H:%M:%S')

            # Ensure the start time comes after the previous entry's end time
            # and the end time comes before the next entry's start time
            # method_id_set is the id given to all method entries, 'method_id', not 'id'
            previous_method = None
            next_method = None
            for index, each_order in enumerate(display_order):
                if each_order == method_data.unique_id:
                    if len(display_order) > 1 and index > 0:
                        previous_method = MethodData.query.filter(
                            MethodData.unique_id == display_order[index-1]).first()
                    if len(display_order) > index+1:
                        next_method = MethodData.query.filter(
                            MethodData.unique_id == display_order[index+1]).first()

            if previous_method is not None and previous_method.time_end is not None:
                previous_end_time = datetime.strptime(
                    previous_method.time_end, '%Y-%m-%d %H:%M:%S')
                if previous_end_time is not None and start_time < previous_end_time:
                    error.append(
                        gettext("The entry start time (%(st)s) cannot "
                                "overlap the previous entry's end time "
                                "(%(et)s)",
                                st=start_time, et=previous_end_time))

            if next_method is not None and next_method.time_start is not None:
                next_start_time = datetime.strptime(
                    next_method.time_start, '%Y-%m-%d %H:%M:%S')
                if next_start_time is not None and end_time > next_start_time:
                    error.append(
                        gettext("The entry end time (%(et)s) cannot "
                                "overlap the next entry's start time "
                                "(%(st)s)",
                                et=end_time, st=next_start_time))

            method_data.time_start = start_time.strftime('%Y-%m-%d %H:%M:%S')
            method_data.time_end = end_time.strftime('%Y-%m-%d %H:%M:%S')

        elif method.method_type == 'Duration':
            if method_data.duration_sec == 0:
                method_data.duration_end = form_mod_method.duration_end.data
            else:
                method_data.duration_sec = form_mod_method.duration.data

        elif method.method_type == 'Daily':
            method_data.time_start = form_mod_method.daily_time_start.data
            method_data.time_end = form_mod_method.daily_time_end.data

        method_data.setpoint_start = form_mod_method.setpoint_start.data
        method_data.setpoint_end = form_mod_method.setpoint_end.data

        if not error:
            db.session.commit()

    except Exception as except_msg:
        logger.exception(1)
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_method.method_list'))
Example #43
0
class FileManagerModule(PgAdminModule):
    """
    FileManager lists files and folders and does
    following operations:
    - File selection
    - Folder selection
    - Open file
    - Create File
    and also supports:
    - Rename file
    - Delete file
    - Upload file
    - Create folder
    """

    LABEL = gettext("Storage")

    def get_own_javascripts(self):
        return [
            {
                'name': 'pgadmin.file_manager',
                'path': url_for('file_manager.index') + 'file_manager',
                'when': None
            },
        ]

    def get_own_stylesheets(self):
        return [
            url_for('static', filename='vendor/jquery.dropzone/dropzone.css'),
            url_for('file_manager.static', filename='css/file_manager.css')
        ]

    def get_own_menuitems(self):
        return {
            'file_items': []
        }

    def get_exposed_url_endpoints(self):
        """
        Returns:
            list: a list of url endpoints exposed to the client.
        """
        return [
            'file_manager.filemanager',
            'file_manager.index',
            'file_manager.get_trans_id',
            'file_manager.delete_trans_id',
            'file_manager.save_last_dir',
            'file_manager.save_file_dialog_view',
            'file_manager.save_show_hidden_file_option'
        ]

    def get_file_size_preference(self):
        return self.file_upload_size

    def register_preferences(self):
        # Register 'file upload size' preference
        self.file_upload_size = self.preference.register(
            'options', 'file_upload_size',
            gettext("Maximum file upload size (MB)"), 'integer', 50,
            category_label=gettext('Options')
        )
        self.last_directory_visited = self.preference.register(
            'options', 'last_directory_visited',
            gettext("Last directory visited"), 'text', '/',
            category_label=gettext('Options')
        )
        self.file_dialog_view = self.preference.register(
            'options', 'file_dialog_view',
            gettext("File dialog view"), 'options', 'list',
            category_label=gettext('Options'),
            options=[{'label': gettext('List'), 'value': 'list'},
                     {'label': gettext('Grid'), 'value': 'grid'}]
        )
        self.show_hidden_files = self.preference.register(
            'options', 'show_hidden_files',
            gettext("Show hidden files and folders?"), 'boolean', False,
            category_label=gettext('Options')
        )
Example #44
0
    def rename(self, old=None, new=None, req=None):
        """
        Rename file or folder
        """
        if not self.validate_request('rename'):
            return {
                'Error': gettext('Not allowed'),
                'Code': 0
            }

        dir = self.dir if self.dir is not None else ''

        try:
            Filemanager.check_access_permission(dir, old)
            Filemanager.check_access_permission(dir, new)
        except Exception as e:
            res = {
                'Error': gettext(u"Error: {0}".format(e)),
                'Code': 0
            }
            return res

        # check if it's dir
        if old[-1] == '/':
            old = old[:-1]

        # extract filename
        oldname = split_path(old)[-1]
        if hasattr(str, 'decode'):
            old = old.encode('utf-8').decode('utf-8')
        path = old
        path = split_path(path)[0]  # extract path

        if not path[-1] == '/':
            path += u'/'

        newname = new
        if hasattr(str, 'decode'):
            newname = new.encode('utf-8').decode('utf-8')
        newpath = path + newname

        # make system old path
        oldpath_sys = u"{0}{1}".format(dir, old)
        newpath_sys = u"{0}{1}".format(dir, newpath)

        error_msg = gettext(u'Renamed successfully.')
        code = 1
        try:
            os.rename(oldpath_sys, newpath_sys)
        except Exception as e:
            code = 0
            error_msg = u"{0} {1}".format(
                gettext(u'There was an error renaming the file:'), e)

        result = {
            'Old Path': old,
            'Old Name': oldname,
            'New Path': newpath,
            'New Name': newname,
            'Error': error_msg,
            'Code': code
        }

        return result
Example #45
0
class LogoForm(FlaskForm):
    logo = FileField(validators=[
        FileRequired(message=gettext('File required.')),
        FileAllowed(['png'],
                    message=gettext("You can only upload PNG image files."))
    ])
Example #46
0
    def list_filesystem(dir, path, trans_data, file_type, show_hidden):
        """
        It lists all file and folders within the given
        directory.
        """
        Filemanager.suspend_windows_warning()
        is_show_hidden_files = show_hidden

        path = unquote(path)
        if hasattr(str, 'decode'):
            path = unquote(path).encode('utf-8').decode('utf-8')

        try:
            Filemanager.check_access_permission(dir, path)
        except Exception as e:
            Filemanager.resume_windows_warning()
            err_msg = u"Error: {0}".format(e)
            files = {
                'Code': 0,
                'Error': err_msg
            }
            return files

        files = {}
        if (_platform == "win32" and (path == '/' or path == '\\'))\
                and dir is None:
            drives = Filemanager._get_drives()
            for drive in drives:
                protected = 0
                path = file_name = u"{0}:".format(drive)
                try:
                    drive_size = getDriveSize(path)
                    drive_size_in_units = sizeof_fmt(drive_size)
                except:
                    drive_size = 0
                protected = 1 if drive_size == 0 else 0
                files[file_name] = {
                    "Filename": file_name,
                    "Path": path,
                    "file_type": 'drive',
                    "Protected": protected,
                    "Properties": {
                        "Date Created": "",
                        "Date Modified": "",
                        "Size": drive_size_in_units
                    }
                }
            Filemanager.resume_windows_warning()
            return files

        if dir is None:
            dir = ""
        orig_path = Filemanager.get_abs_path(dir, path)

        if not path_exists(orig_path):
            Filemanager.resume_windows_warning()
            return {
                'Code': 0,
                'Error': gettext(u"'{0}' file does not exist.".format(path))
            }

        user_dir = path
        folders_only = trans_data['folders_only'] if 'folders_only' in \
                                                     trans_data else ''
        files_only = trans_data['files_only'] if 'files_only' in \
                                                 trans_data else ''
        supported_types = trans_data['supported_types'] \
            if 'supported_types' in trans_data else []

        orig_path = unquote(orig_path)
        try:
            mylist = [x for x in sorted(os.listdir(orig_path))]
            for f in mylist:
                protected = 0
                system_path = os.path.join(os.path.join(orig_path, f))

                # continue if file/folder is hidden (based on user preference)
                if not is_show_hidden_files and \
                    (is_folder_hidden(system_path) or f.startswith('.')):
                    continue

                user_path = os.path.join(os.path.join(user_dir, f))
                created = time.ctime(os.path.getctime(system_path))
                modified = time.ctime(os.path.getmtime(system_path))
                file_extension = str(splitext(system_path))

                # set protected to 1 if no write or read permission
                if (not os.access(system_path, os.R_OK) or
                        not os.access(system_path, os.W_OK)):
                    protected = 1

                # list files only or folders only
                if os.path.isdir(system_path):
                    if files_only == 'true':
                        continue
                    file_extension = u"dir"
                    user_path = u"{0}/".format(user_path)
                else:
                    # filter files based on file_type
                    if file_type is not None and file_type != "*":
                        if folders_only or len(supported_types) > 0 and \
                                        file_extension not in supported_types or \
                                        file_type != file_extension:
                            continue

                # create a list of files and folders
                files[f] = {
                    "Filename": f,
                    "Path": user_path,
                    "file_type": file_extension,
                    "Protected": protected,
                    "Properties": {
                        "Date Created": created,
                        "Date Modified": modified,
                        "Size": sizeof_fmt(getSize(system_path))
                    }
                }
        except Exception as e:
            Filemanager.resume_windows_warning()
            if (hasattr(e, 'strerror') and
                    e.strerror == gettext('Permission denied')):
                err_msg = u"Error: {0}".format(e.strerror)
            else:
                err_msg = u"Error: {0}".format(e)
            files = {
                'Code': 0,
                'Error': err_msg
            }
        Filemanager.resume_windows_warning()
        return files
Example #47
0
def name_length_validation(form, field):
    if len(field.data) > Journalist.MAX_NAME_LEN:
        raise ValidationError(
            gettext('Cannot be longer than {max_chars} characters.'.format(
                max_chars=Journalist.MAX_NAME_LEN)))
Example #48
0
def get_engines_stats():
    # TODO refactor
    pageloads = []
    engine_times = []
    results = []
    scores = []
    errors = []
    scores_per_result = []

    max_pageload = max_engine_times = max_results = max_score = max_errors = max_score_per_result = 0  # noqa
    for engine in engines.values():
        if engine.stats['search_count'] == 0:
            continue
        results_num = \
            engine.stats['result_count'] / float(engine.stats['search_count'])

        if engine.stats['page_load_count'] != 0:
            load_times = engine.stats['page_load_time'] / float(
                engine.stats['page_load_count'])  # noqa
        else:
            load_times = 0

        if engine.stats['engine_time_count'] != 0:
            this_engine_time = engine.stats['engine_time'] / float(
                engine.stats['engine_time_count'])  # noqa
        else:
            this_engine_time = 0

        if results_num:
            score = engine.stats['score_count'] / float(
                engine.stats['search_count'])  # noqa
            score_per_result = score / results_num
        else:
            score = score_per_result = 0.0

        max_pageload = max(load_times, max_pageload)
        max_engine_times = max(this_engine_time, max_engine_times)
        max_results = max(results_num, max_results)
        max_score = max(score, max_score)
        max_score_per_result = max(score_per_result, max_score_per_result)
        max_errors = max(max_errors, engine.stats['errors'])

        pageloads.append({'avg': load_times, 'name': engine.name})
        engine_times.append({'avg': this_engine_time, 'name': engine.name})
        results.append({'avg': results_num, 'name': engine.name})
        scores.append({'avg': score, 'name': engine.name})
        errors.append({'avg': engine.stats['errors'], 'name': engine.name})
        scores_per_result.append({
            'avg': score_per_result,
            'name': engine.name
        })

    pageloads = to_percentage(pageloads, max_pageload)
    engine_times = to_percentage(engine_times, max_engine_times)
    results = to_percentage(results, max_results)
    scores = to_percentage(scores, max_score)
    scores_per_result = to_percentage(scores_per_result, max_score_per_result)
    erros = to_percentage(errors, max_errors)

    return [
        (gettext('Engine time (sec)'),
         sorted(engine_times, key=itemgetter('avg'))),
        (gettext('Page loads (sec)'), sorted(pageloads,
                                             key=itemgetter('avg'))),
        (gettext('Number of results'),
         sorted(results, key=itemgetter('avg'), reverse=True)),
        (gettext('Scores'), sorted(scores, key=itemgetter('avg'),
                                   reverse=True)),
        (gettext('Scores per result'),
         sorted(scores_per_result, key=itemgetter('avg'), reverse=True)),
        (gettext('Errors'), sorted(errors, key=itemgetter('avg'),
                                   reverse=True)),
    ]
Example #49
0
def preferences():
    """Render preferences page && save user preferences"""

    # save preferences
    if request.method == 'POST':
        resp = make_response(redirect(url_for('index', _external=True)))
        try:
            request.preferences.parse_form(request.form)
        except ValidationException:
            request.errors.append(gettext('Invalid settings, please edit your preferences'))
            return resp
        return request.preferences.save(resp)

    # render preferences
    image_proxy = request.preferences.get_value('image_proxy')
    disabled_engines = request.preferences.engines.get_disabled()
    allowed_plugins = request.preferences.plugins.get_enabled()

    # stats for preferences page
    stats = {}

    engines_by_category = {}
    for c in categories:
        engines_by_category[c] = []
        for e in categories[c]:
            if not request.preferences.validate_token(e):
                continue

            stats[e.name] = {'time': None,
                             'warn_timeout': False,
                             'warn_time': False}
            if e.timeout > settings['outgoing']['request_timeout']:
                stats[e.name]['warn_timeout'] = True
            stats[e.name]['supports_selected_language'] = _is_selected_language_supported(e, request.preferences)
            engines_by_category[c].append(e)

    # get first element [0], the engine time,
    # and then the second element [1] : the time (the first one is the label)
    for engine_stat in get_engines_stats(request.preferences)[0][1]:
        stats[engine_stat.get('name')]['time'] = round(engine_stat.get('avg'), 3)
        if engine_stat.get('avg') > settings['outgoing']['request_timeout']:
            stats[engine_stat.get('name')]['warn_time'] = True
    # end of stats

    locked_preferences = list()
    if 'preferences' in settings and 'lock' in settings['preferences']:
        locked_preferences = settings['preferences']['lock']

    return render('preferences.html',
                  selected_categories=get_selected_categories(request.preferences, request.form),
                  all_categories=_get_ordered_categories(),
                  locales=settings['locales'],
                  current_locale=request.preferences.get_value("locale"),
                  image_proxy=image_proxy,
                  engines_by_category=engines_by_category,
                  stats=stats,
                  answerers=[{'info': a.self_info(), 'keywords': a.keywords} for a in answerers],
                  disabled_engines=disabled_engines,
                  autocomplete_backends=autocomplete_backends,
                  shortcuts={y: x for x, y in engine_shortcuts.items()},
                  themes=themes,
                  plugins=plugins,
                  doi_resolvers=settings['doi_resolvers'],
                  current_doi_resolver=get_doi_resolver(request.args, request.preferences.get_value('doi_resolver')),
                  allowed_plugins=allowed_plugins,
                  theme=get_current_theme_name(),
                  preferences_url_params=request.preferences.get_as_url_params(),
                  base_url=get_base_url(),
                  locked_preferences=locked_preferences,
                  preferences=True)
Example #50
0
def check_invalid_usernames(form, field):
    if field.data in Journalist.INVALID_USERNAMES:
        raise ValidationError(
            gettext(
                "This username is invalid because it is reserved for internal use by the software."
            ))
Example #51
0
# see run() at the end of this file : searx_debug activates the reload feature.
werkzeug_reloader = flask_run_development or (searx_debug and __name__ == "__main__")

# initialize the engines except on the first run of the werkzeug server.
if not werkzeug_reloader\
   or (werkzeug_reloader and os.environ.get("WERKZEUG_RUN_MAIN") == "true"):
    search_initialize(enable_checker=True)

babel = Babel(app)

rtl_locales = ['ar', 'arc', 'bcc', 'bqi', 'ckb', 'dv', 'fa', 'fa_IR', 'glk', 'he',
               'ku', 'mzn', 'pnb', 'ps', 'sd', 'ug', 'ur', 'yi']
ui_locale_codes = [l.replace('_', '-') for l in settings['locales'].keys()]

# used when translating category names
_category_names = (gettext('files'),
                   gettext('general'),
                   gettext('music'),
                   gettext('social media'),
                   gettext('images'),
                   gettext('videos'),
                   gettext('it'),
                   gettext('news'),
                   gettext('map'),
                   gettext('onions'),
                   gettext('science'))

_flask_babel_get_translations = flask_babel.get_translations


# monkey patch for flask_babel.get_translations
Example #52
0
def minimum_length_validation(form, field):
    if len(field.data) < Journalist.MIN_USERNAME_LEN:
        raise ValidationError(
            gettext('Must be at least {min_chars} '
                    'characters long.'.format(
                        min_chars=Journalist.MIN_USERNAME_LEN)))
Example #53
0
def post_user():
    current_app.logger.info(
        f"/users (add_user) accessed by {g.request_user.email}")

    if not request.is_json:
        msg = flask_babel.gettext("Missing JSON in request")
        return jsonify({"message": msg}), 400

    email = request.json.get('email', None)
    username = request.json.get('username', None)
    role_id = request.json.get('role_id', None)
    name = request.json.get('name', None)
    location = request.json.get('location', None)

    if not email:
        msg = flask_babel.gettext("Missing email")
        return jsonify({"message": msg}), 400
    if models.User.query.filter_by(email=email).all():
        msg = flask_babel.gettext(
            "The email address you provided is already in use.")
        return jsonify({"message": msg}), 400
    if not username:
        msg = flask_babel.gettext("Missing username")
        return jsonify({"message": msg}), 400
    if models.User.query.filter_by(username=username).all():
        msg = flask_babel.gettext(
            "The username you provided is already in use.")
        return jsonify({"message": msg}), 400
    if not role_id:
        role = models.Role.query.filter_by(default=True).first()
    else:
        if not isinstance(role_id, int):
            msg = flask_babel.gettext("Role id should be a integer number.")
            return jsonify({"message": msg}), 400
        if role_id not in [r.id for r in models.Role.query.all()]:
            msg = flask_babel.gettext("%(role_id)s is an invalid role id.",
                                      role_id=role_id)
            return jsonify({"message": msg}), 400
        role = models.Role.query.get(role_id)
    password = models.User.generate_password()

    user_data = {
        'email': email,
        'username': username,
        'name': name,
        'role': role,
        'location': location,
        'password': password
    }

    metabase_user_id = metabase.insert_user(user_data)

    user = models.User(metabase_user_id=metabase_user_id, **user_data)

    db.session.add(user)
    db.session.commit()
    send_email(user.email,
               'Welcome to EPS',
               'auth/email/welcome',
               web_app_url=current_app.config['WEB_APP_URL'],
               user=user,
               password=password)

    return jsonify(user.__getstate__()), 200
Example #54
0
def search():
    """Search query in q and return results.

    Supported outputs: html, json, csv, rss.
    """

    # output_format
    output_format = request.form.get('format', 'html')
    if output_format not in ['html', 'csv', 'json', 'rss']:
        output_format = 'html'

    # check if there is query (not None and not an empty string)
    if not request.form.get('q'):
        if output_format == 'html':
            return render(
                'index.html',
                advanced_search=request.preferences.get_value('advanced_search'),
                selected_categories=get_selected_categories(request.preferences, request.form),
            )
        else:
            return index_error(output_format, 'No query'), 400

    # search
    search_query = None
    raw_text_query = None
    result_container = None
    try:
        search_query, raw_text_query, _, _ = get_search_query_from_webapp(request.preferences, request.form)
        # search = Search(search_query) #  without plugins
        search = SearchWithPlugins(search_query, request.user_plugins, request)

        result_container = search.search()

    except SearxParameterException as e:
        logger.exception('search error: SearxParameterException')
        return index_error(output_format, e.message), 400
    except Exception as e:
        logger.exception('search error')
        return index_error(output_format, gettext('search error')), 500

    # results
    results = result_container.get_ordered_results()
    number_of_results = result_container.results_number()
    if number_of_results < result_container.results_length():
        number_of_results = 0

    # checkin for a external bang
    if result_container.redirect_url:
        return redirect(result_container.redirect_url)

    # Server-Timing header
    request.timings = result_container.get_timings()

    # output
    for result in results:
        if output_format == 'html':
            if 'content' in result and result['content']:
                result['content'] = highlight_content(escape(result['content'][:1024]), search_query.query)
            if 'title' in result and result['title']:
                result['title'] = highlight_content(escape(result['title'] or ''), search_query.query)
        else:
            if result.get('content'):
                result['content'] = html_to_text(result['content']).strip()
            # removing html content and whitespace duplications
            result['title'] = ' '.join(html_to_text(result['title']).strip().split())

        if 'url' in result:
            result['pretty_url'] = prettify_url(result['url'])

        # TODO, check if timezone is calculated right
        if result.get('publishedDate'):  # do not try to get a date from an empty string or a None type
            try:  # test if publishedDate >= 1900 (datetime module bug)
                result['pubdate'] = result['publishedDate'].strftime('%Y-%m-%d %H:%M:%S%z')
            except ValueError:
                result['publishedDate'] = None
            else:
                if result['publishedDate'].replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
                    timedifference = datetime.now() - result['publishedDate'].replace(tzinfo=None)
                    minutes = int((timedifference.seconds / 60) % 60)
                    hours = int(timedifference.seconds / 60 / 60)
                    if hours == 0:
                        result['publishedDate'] = gettext('{minutes} minute(s) ago').format(minutes=minutes)
                    else:
                        result['publishedDate'] = gettext('{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes)  # noqa
                else:
                    result['publishedDate'] = format_date(result['publishedDate'])

    if output_format == 'json':
        return Response(json.dumps({'query': search_query.query,
                                    'number_of_results': number_of_results,
                                    'results': results,
                                    'answers': list(result_container.answers),
                                    'corrections': list(result_container.corrections),
                                    'infoboxes': result_container.infoboxes,
                                    'suggestions': list(result_container.suggestions),
                                    'unresponsive_engines': __get_translated_errors(result_container.unresponsive_engines)},  # noqa
                                   default=lambda item: list(item) if isinstance(item, set) else item),
                        mimetype='application/json')
    elif output_format == 'csv':
        csv = UnicodeWriter(StringIO())
        keys = ('title', 'url', 'content', 'host', 'engine', 'score', 'type')
        csv.writerow(keys)
        for row in results:
            row['host'] = row['parsed_url'].netloc
            row['type'] = 'result'
            csv.writerow([row.get(key, '') for key in keys])
        for a in result_container.answers:
            row = {'title': a, 'type': 'answer'}
            csv.writerow([row.get(key, '') for key in keys])
        for a in result_container.suggestions:
            row = {'title': a, 'type': 'suggestion'}
            csv.writerow([row.get(key, '') for key in keys])
        for a in result_container.corrections:
            row = {'title': a, 'type': 'correction'}
            csv.writerow([row.get(key, '') for key in keys])
        csv.stream.seek(0)
        response = Response(csv.stream.read(), mimetype='application/csv')
        cont_disp = 'attachment;Filename=searx_-_{0}.csv'.format(search_query.query)
        response.headers.add('Content-Disposition', cont_disp)
        return response

    elif output_format == 'rss':
        response_rss = render(
            'opensearch_response_rss.xml',
            results=results,
            answers=result_container.answers,
            corrections=result_container.corrections,
            suggestions=result_container.suggestions,
            q=request.form['q'],
            number_of_results=number_of_results,
            base_url=get_base_url(),
            override_theme='__common__',
        )
        return Response(response_rss, mimetype='text/xml')

    # HTML output format

    # suggestions: use RawTextQuery to get the suggestion URLs with the same bang
    suggestion_urls = list(map(lambda suggestion: {
                               'url': raw_text_query.changeQuery(suggestion).getFullQuery(),
                               'title': suggestion
                               },
                               result_container.suggestions))

    correction_urls = list(map(lambda correction: {
                               'url': raw_text_query.changeQuery(correction).getFullQuery(),
                               'title': correction
                               },
                               result_container.corrections))
    #
    return render(
        'results.html',
        results=results,
        q=request.form['q'],
        selected_categories=search_query.categories,
        pageno=search_query.pageno,
        time_range=search_query.time_range,
        number_of_results=format_decimal(number_of_results),
        suggestions=suggestion_urls,
        answers=result_container.answers,
        corrections=correction_urls,
        infoboxes=result_container.infoboxes,
        engine_data=result_container.engine_data,
        paging=result_container.paging,
        unresponsive_engines=__get_translated_errors(result_container.unresponsive_engines),
        current_language=match_language(search_query.lang,
                                        LANGUAGE_CODES,
                                        fallback=request.preferences.get_value("language")),
        base_url=get_base_url(),
        theme=get_current_theme_name(),
        favicons=global_favicons[themes.index(get_current_theme_name())],
        timeout_limit=request.form.get('timeout_limit', None)
    )
Example #55
0
 def wrapper(*args: Any, **kwargs: Any) -> Any:
     if logged_in() and g.user.is_admin:
         return func(*args, **kwargs)
     flash(gettext("Only admins can access this page."), "notification")
     return redirect(url_for('main.index'))
Example #56
0
def put_user(user_id):
    current_app.logger.info(
        f"/users/{user_id} PUT accessed by {g.request_user.email}")

    if not request.is_json:
        msg = flask_babel.gettext("Missing JSON in request")
        return jsonify({"message": msg}), 400

    return_user = models.User.query.get_or_404(user_id)

    put_is_active = request.json.get('is_active', return_user.is_active)

    if put_is_active is not None and (put_is_active != return_user.is_active):
        # trying to change is_active_flag
        if not g.request_user.can(models.Permission.DELETE_ACCOUNT):
            msg = flask_babel.gettext(
                "You do not have permission to change someone's active flag.")
            return jsonify({"message": msg}), 401

    # trying to disabled admin
    if return_user.is_admin() and put_is_active is False:
        msg = flask_babel.gettext("Admin users cannot be disabled.")
        return jsonify({"message": msg}), 400

    put_user_id = request.json.get('id', None)
    if not put_user_id:
        msg = flask_babel.gettext(
            "You must provide a user id in your put object.")
        return jsonify({"message": msg}), 400
    if put_user_id != return_user.id:
        msg = flask_babel.gettext(
            "The user id in the URL does not match the user id in your put object."
        )
        return jsonify({"message": msg}), 400

    requested_email = request.json.get('email', return_user.email)
    if not requested_email:
        msg = flask_babel.gettext(
            "User's email addresses cannot be null or empty.")
        return jsonify({"message": msg}), 400
    if len(
            models.User.query.filter(models.User.email == requested_email,
                                     models.User.id != put_user_id).all()):
        msg = flask_babel.gettext(
            "The email address you provided is already in use.")
        return jsonify({"message": msg}), 400

    requested_username = request.json.get('username', return_user.username)
    if not requested_username:
        msg = flask_babel.gettext("Usernames cannot be null or empty.")
        return jsonify({"message": msg}), 400
    if len(
            models.User.query.filter(
                models.User.username == requested_username,
                models.User.id != put_user_id).all()):
        msg = flask_babel.gettext(
            "The username you provided is already in use.")
        return jsonify({"message": msg}), 400

    if 'role_id' in request.json:
        requested_role_id = request.json.get('role_id')

        if requested_role_id not in [r.id for r in models.Role.query.all()]:
            msg = flask_babel.gettext(
                "The provided role id is not a valid role id.")
            return jsonify({"message": msg}), 400

        new_role = models.Role.query.get(requested_role_id)
        # if the user's current role has ASSIGNABLE_TO_CASE and the new role does not
        # then unassign all their cases and notify admins
        if return_user.can(models.Permission.ASSIGNABLE_TO_CASE
                           ) and not new_role.has_permission(
                               models.Permission.ASSIGNABLE_TO_CASE):
            cases_updated = []
            for case in models.Case.query.filter_by(
                    assigned_to_id=return_user.id).all():
                case.assigned_to_id = None
                case.assigned_at = datetime.utcnow()
                cases_updated.append(case)
            if len(cases_updated) > 0:
                notification_service.notify_user_role_changed_not_assignable(
                    return_user, cases_updated)
Example #57
0
class TableModule(SchemaChildModule):
    """
     class TableModule(SchemaChildModule)

        A module class for Table node derived from SchemaChildModule.

    Methods:
    -------
    * __init__(*args, **kwargs)
      - Method is used to initialize the Table and it's base module.

    * get_nodes(gid, sid, did, scid, tid)
      - Method is used to generate the browser collection node.

    * node_inode()
      - Method is overridden from its base class to make the node as leaf node.

    * script_load()
      - Load the module script for schema, when any of the server node is
        initialized.
    """
    NODE_TYPE = 'table'
    COLLECTION_LABEL = gettext("Tables")

    def __init__(self, *args, **kwargs):
        """
        Method is used to initialize the TableModule and it's base module.

        Args:
            *args:
            **kwargs:
        """
        super(TableModule, self).__init__(*args, **kwargs)
        self.max_ver = None
        self.min_ver = None

    def get_nodes(self, gid, sid, did, scid):
        """
        Generate the collection node
        """
        yield self.generate_browser_collection_node(scid)

    @property
    def script_load(self):
        """
        Load the module script for database, when any of the database node is
        initialized.
        """
        return database.DatabaseModule.NODE_TYPE

    def get_own_javascripts(self):
        scripts = SchemaChildModule.get_own_javascripts(self)

        scripts.append({
            'name': 'pgadmin.browser.table.partition.utils',
            'path':
            url_for('browser.index') + 'table/static/js/partition.utils',
            'when': 'database',
            'is_template': False
        })

        return scripts
Example #58
0
            cases_updated = []
            for case in models.Case.query.filter_by(
                    assigned_to_id=return_user.id).all():
                case.assigned_to_id = None
                case.assigned_at = datetime.utcnow()
                cases_updated.append(case)
            if len(cases_updated) > 0:
                notification_service.notify_user_role_changed_not_assignable(
                    return_user, cases_updated)

    else:
        requested_role_id = return_user.role_id

    color = request.json.get('color', return_user.color)
    if color not in models.User.supported_user_colors:
        msg = flask_babel.gettext("You provided an unsupported color")
        return jsonify({'message': msg}), 400

    updates = {
        'email': requested_email,
        'username': requested_username,
    }
    metabase.update_user(return_user.metabase_user_id, updates)

    is_active = request.json.get('is_active', return_user.is_active)

    if return_user.is_active and is_active is False:
        metabase.deactivate_user(return_user.metabase_user_id)
    elif return_user.is_active is False and is_active:
        metabase.reactivate_user(return_user.metabase_user_id)
Example #59
0
def page_camera():
    """
    Page to start/stop video stream or time-lapse, or capture a still image.
    Displays most recent still image and time-lapse image.
    """
    if not flaskutils.user_has_permission('view_camera'):
        return redirect(url_for('general_routes.home'))

    form_camera = flaskforms.Camera()
    camera = Camera.query.all()

    # Check if a video stream is active
    for each_camera in camera:
        if each_camera.stream_started and not CameraStream().is_running():
            each_camera.stream_started = False
            db.session.commit()

    if request.method == 'POST':
        if not flaskutils.user_has_permission('edit_settings'):
            return redirect(url_for('page_routes.page_camera'))

        control = DaemonControl()
        mod_camera = Camera.query.filter(
            Camera.id == form_camera.camera_id.data).first()
        if form_camera.capture_still.data:
            if mod_camera.stream_started:
                flash(
                    gettext(
                        u"Cannot capture still image if stream is active."))
                return redirect('/camera')
            if CameraStream().is_running():
                CameraStream().terminate_controller()  # Stop camera stream
                time.sleep(2)
            camera_record('photo', mod_camera)
        elif form_camera.start_timelapse.data:
            if mod_camera.stream_started:
                flash(gettext(u"Cannot start time-lapse if stream is active."))
                return redirect('/camera')
            now = time.time()
            mod_camera.timelapse_started = True
            mod_camera.timelapse_start_time = now
            mod_camera.timelapse_end_time = now + float(
                form_camera.timelapse_runtime_sec.data)
            mod_camera.timelapse_interval = form_camera.timelapse_interval.data
            mod_camera.timelapse_next_capture = now
            mod_camera.timelapse_capture_number = 0
            db.session.commit()
            control.refresh_daemon_camera_settings()
        elif form_camera.pause_timelapse.data:
            mod_camera.timelapse_paused = True
            db.session.commit()
            control.refresh_daemon_camera_settings()
        elif form_camera.resume_timelapse.data:
            mod_camera.timelapse_paused = False
            db.session.commit()
            control.refresh_daemon_camera_settings()
        elif form_camera.stop_timelapse.data:
            mod_camera.timelapse_started = False
            mod_camera.timelapse_start_time = None
            mod_camera.timelapse_end_time = None
            mod_camera.timelapse_interval = None
            mod_camera.timelapse_next_capture = None
            mod_camera.timelapse_capture_number = None
            db.session.commit()
            control.refresh_daemon_camera_settings()
        elif form_camera.start_stream.data:
            if mod_camera.timelapse_started:
                flash(gettext(u"Cannot start stream if time-lapse is active."))
                return redirect('/camera')
            elif CameraStream().is_running():
                flash(
                    gettext(
                        u"Cannot start stream. The stream is already running.")
                )
                return redirect('/camera')
            elif (not (mod_camera.camera_type == 'Raspberry Pi'
                       and mod_camera.library == 'picamera')):
                flash(
                    gettext(u"Streaming is only supported with the Raspberry"
                            u" Pi camera using the picamera library."))
                return redirect('/camera')
            elif Camera.query.filter_by(stream_started=True).count():
                flash(
                    gettext(u"Cannot start stream if another stream is "
                            u"already in progress."))
                return redirect('/camera')
            else:
                mod_camera.stream_started = True
                db.session.commit()
        elif form_camera.stop_stream.data:
            if CameraStream().is_running():
                CameraStream().terminate_controller()
            mod_camera.stream_started = False
            db.session.commit()
        return redirect('/camera')

    # Get the full path and timestamps of latest still and time-lapse images
    latest_img_still_ts = {}
    latest_img_still = {}
    latest_img_tl_ts = {}
    latest_img_tl = {}
    for each_camera in camera:
        camera_path = os.path.join(
            PATH_CAMERAS, '{id}-{uid}'.format(id=each_camera.id,
                                              uid=each_camera.unique_id))
        try:
            latest_still_img_full_path = max(glob.iglob(
                '{path}/still/Still-{cam_id}-*.jpg'.format(
                    path=camera_path, cam_id=each_camera.id)),
                                             key=os.path.getmtime)
        except ValueError:
            latest_still_img_full_path = None
        if latest_still_img_full_path:
            ts = os.path.getmtime(latest_still_img_full_path)
            latest_img_still_ts[
                each_camera.id] = datetime.datetime.fromtimestamp(ts).strftime(
                    "%Y-%m-%d %H:%M:%S")
            latest_img_still[each_camera.id] = os.path.basename(
                latest_still_img_full_path)
        else:
            latest_img_still[each_camera.id] = None

        try:
            latest_time_lapse_img_full_path = max(glob.iglob(
                '{path}/timelapse/Timelapse-{cam_id}-*.jpg'.format(
                    path=camera_path, cam_id=each_camera.id)),
                                                  key=os.path.getmtime)
        except ValueError:
            latest_time_lapse_img_full_path = None
        if latest_time_lapse_img_full_path:
            ts = os.path.getmtime(latest_time_lapse_img_full_path)
            latest_img_tl_ts[each_camera.id] = datetime.datetime.fromtimestamp(
                ts).strftime("%Y-%m-%d %H:%M:%S")
            latest_img_tl[each_camera.id] = os.path.basename(
                latest_time_lapse_img_full_path)
        else:
            latest_img_tl[each_camera.id] = None

    time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    return render_template('pages/camera.html',
                           camera=camera,
                           form_camera=form_camera,
                           latest_img_still=latest_img_still,
                           latest_img_still_ts=latest_img_still_ts,
                           latest_img_tl=latest_img_tl,
                           latest_img_tl_ts=latest_img_tl_ts,
                           time_now=time_now)
Example #60
0
    def create(self, gid, sid, did, scid):
        """
        This function will creates new the table object

         Args:
           gid: Server Group ID
           sid: Server ID
           did: Database ID
           scid: Schema ID
        """
        data = request.form if request.form else json.loads(request.data,
                                                            encoding='utf-8')

        for k, v in data.items():
            try:
                data[k] = json.loads(v, encoding='utf-8')
            except (ValueError, TypeError, KeyError):
                data[k] = v

        required_args = ['name']

        for arg in required_args:
            if arg not in data:
                return make_json_response(
                    status=410,
                    success=0,
                    errormsg=gettext(
                        "Could not find the required parameter (%s)." % arg))

        # Parse privilege data coming from client according to database format
        if 'relacl' in data:
            data['relacl'] = parse_priv_to_db(data['relacl'], self.acl)

        # Parse & format columns
        data = self._parse_format_columns(data)
        data = TableView.check_and_convert_name_to_string(data)

        # 'coll_inherits' is Array but it comes as string from browser
        # We will convert it again to list
        if 'coll_inherits' in data and \
                isinstance(data['coll_inherits'], str):
            data['coll_inherits'] = json.loads(data['coll_inherits'],
                                               encoding='utf-8')

        if 'foreign_key' in data:
            for c in data['foreign_key']:
                SQL = render_template("/".join(
                    [self.foreign_key_template_path, 'get_parent.sql']),
                                      tid=c['columns'][0]['references'])
                status, rset = self.conn.execute_2darray(SQL)
                if not status:
                    return internal_server_error(errormsg=rset)

                c['remote_schema'] = rset['rows'][0]['schema']
                c['remote_table'] = rset['rows'][0]['table']

        try:
            partitions_sql = ''
            partitioned = False
            if 'is_partitioned' in data and data['is_partitioned']:
                data['relkind'] = 'p'
                # create partition scheme
                data['partition_scheme'] = self.get_partition_scheme(data)
                partitions_sql = self.get_partitions_sql(data)
                partitioned = True

            SQL = render_template("/".join(
                [self.table_template_path, 'create.sql']),
                                  data=data,
                                  conn=self.conn)

            # Append SQL for partitions
            SQL += '\n' + partitions_sql

            status, res = self.conn.execute_scalar(SQL)
            if not status:
                return internal_server_error(errormsg=res)

            # PostgreSQL truncates the table name to 63 characters.
            # Have to truncate the name like PostgreSQL to get the
            # proper OID
            CONST_MAX_CHAR_COUNT = 63

            if len(data['name']) > CONST_MAX_CHAR_COUNT:
                data['name'] = data['name'][0:CONST_MAX_CHAR_COUNT]

            # Get updated schema oid
            SQL = render_template("/".join(
                [self.table_template_path, 'get_schema_oid.sql']),
                                  tname=data['name'])

            status, scid = self.conn.execute_scalar(SQL)
            if not status:
                return internal_server_error(errormsg=scid)

            # we need oid to to add object in tree at browser
            SQL = render_template("/".join(
                [self.table_template_path, 'get_oid.sql']),
                                  scid=scid,
                                  data=data)

            status, tid = self.conn.execute_scalar(SQL)
            if not status:
                return internal_server_error(errormsg=tid)

            return jsonify(node=self.blueprint.generate_browser_node(
                tid,
                scid,
                data['name'],
                icon="icon-partition" if partitioned else "icon-table",
                is_partitioned=partitioned))
        except Exception as e:
            return internal_server_error(errormsg=str(e))