Exemplo n.º 1
0
 def set_start_and_stop(self, global_layout):
     grid = QVBoxLayout()
     row_1 = QHBoxLayout()
     row_2 = QHBoxLayout()
     self.start_button = QPushButton('Start', self)
     self.start_button.clicked.connect(self.start_server)
     self.start_button.setFont(self.fonts)
     self.start_button.setIcon(
         QIcon(absolute_path(solve_path('static/images/play.png'))))
     self.stop_button = QPushButton('Stop', self)
     self.stop_button.clicked.connect(self.stop_server)
     self.stop_button.setIcon(
         QIcon(absolute_path(solve_path('static/images/pause.png'))))
     self.reset_button = QPushButton(
         self.get_translation('Reset admin password'))
     self.reset_button.clicked.connect(self.reset_admin_pass)
     self.start_button.setToolTip(self.get_translation('Start the server'))
     self.stop_button.setToolTip(self.get_translation('Stop the server'))
     self.stop_button.setEnabled(False)
     self.stop_button.setFont(self.fonts)
     row_1.addWidget(self.start_button)
     row_1.addWidget(self.stop_button)
     row_2.addWidget(self.reset_button)
     grid.addLayout(row_1)
     grid.addLayout(row_2)
     global_layout.addLayout(grid)
Exemplo n.º 2
0
Arquivo: main.py Projeto: KsAmJ/FQM
def create_app(config={}):
    ''' Create the flask app and setup extensions and blueprints.

    Returns
    -------
        app: Flask app
            app with settings and blueprints loadeds.
    '''
    app = Flask(__name__,
                static_folder=absolute_path('static'),
                template_folder=absolute_path('templates'))
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{absolute_path(DATABASE_FILE)}?check_same_thread=False'
    app.config['DB_NAME'] = DATABASE_FILE
    # Autoreload if templates change
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    # flask_upload settings
    # app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024 # Remove Upload limit. FIX ISSUE
    app.config['UPLOADED_FILES_DEST'] = absolute_path('static/multimedia')
    app.config['UPLOADED_FILES_ALLOW'] = reduce(lambda sum, group: sum + group,
                                                SUPPORTED_MEDIA_FILES)
    app.config['SECRET_KEY'] = os.urandom(24)
    app.config.update(config)

    # Initiating extensions before registering blueprints
    Moment(app)
    QRcode(app)
    configure_uploads(app, files)
    login_manager.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db=db)
    datepicker(
        app, local=['static/css/jquery-ui.min.css', 'static/jquery-ui.min.js'])
    colorpicker(app,
                local=['static/css/spectrum.css', 'static/spectrum.min.js'])
    fontpicker(app,
               local=[
                   'static/jquery-ui.min.js', 'static/css/jquery-ui.min.css',
                   'static/webfont.min.js', 'static/webfont.select.min.js',
                   'static/css/webfont.select.css'
               ])
    minify(app,
           js=True,
           cssless=True,
           caching_limit=3,
           fail_safe=True,
           bypass=['.min.*'])
    gTTs.init_app(app)
    gtranslator.init_app(app)

    # Register blueprints
    app.register_blueprint(administrate)
    app.register_blueprint(core)
    app.register_blueprint(cust_app)
    app.register_blueprint(manage_app)
    app.jinja_env.add_extension('jinja2.ext.loopcontrols')

    return app
Exemplo n.º 3
0
 def set_start_and_stop(self, global_layout):
     horizontal_layout = QHBoxLayout()
     self.start_button = QPushButton('Start', self)
     self.start_button.clicked.connect(self.start_server)
     self.start_button.setFont(self.fonts)
     self.start_button.setIcon(QIcon(absolute_path(solve_path('static/images/play.png'))))
     self.stop_button = QPushButton('Stop', self)
     self.stop_button.clicked.connect(self.stop_server)
     self.stop_button.setIcon(QIcon(absolute_path(solve_path('static/images/pause.png'))))
     self.start_button.setToolTip(self.get_translation('Start the server'))
     self.stop_button.setToolTip(self.get_translation('Stop the server'))
     self.stop_button.setEnabled(False)
     self.stop_button.setFont(self.fonts)
     horizontal_layout.addWidget(self.start_button)
     horizontal_layout.addWidget(self.stop_button)
     global_layout.addLayout(horizontal_layout)
Exemplo n.º 4
0
 def start_server(self):
     current = self.select_ips_ports_change()
     self.Process = RunnerThread(current[1].split(',')[1], current[0], self.app)
     self.Process.setTerminationEnabled(True)
     if not self.Process.isRunning():
         try:
             self.Processport = current[0]
             self.start_button.setEnabled(False)
             self.stop_button.setEnabled(True)
             self.select_ip.setEnabled(False)
             self.select_port.setEnabled(False)
             self.status_icon = QIcon(absolute_path(solve_path('static/images/play.png')))
             self.status_icon = self.status_icon.pixmap(70, 70, QIcon.Active, QIcon.On)
             self.status_icon_container.setPixmap(self.status_icon)
             current = self.select_ips_ports_change()
             address = self.get_translation('Server is <u>Running</u> <br> On : ')
             address += "<a href='http://"
             address += current[1].split(',')[1] + ":" + current[0]
             address += "'> http://" + current[1].split(',')[1] + ":" + current[0]
             address += "</a>"
             self.status_label.setText(address)
             self.status_label.setFont(self.font)
             self.Process.start()
             self.currently_running = True
         except Exception:
             self.before_exit()
     else:
         self.before_exit()
Exemplo n.º 5
0
def multi_del(f_id):
    ''' to delete multimedia file '''
    media_path = absolute_path('static/multimedia/')
    medias = data.Media.query.filter_by(used=False)
    media = medias.filter_by(id=f_id).first()

    if not medias.count():
        flash('Error: there is no unused multimedia file to be removed !',
              'danger')
        return redirect(url_for('cust_app.multimedia', aa=1))

    def delete_media(m):
        file_path = os.path.join(media_path, m.name)

        if os.path.isfile(file_path):
            os.remove(file_path)

        db.session.delete(m)

    if media:
        delete_media(media)
    elif not f_id:
        for media in medias:
            delete_media(media)
    else:
        flash('Error: there is no unused multimedia file to be removed !',
              'danger')
        return redirect(url_for('cust_app.multimedia', aa=1))

    db.session.commit()
    flash('Notice: multimedia file been removed.', 'info')
    return redirect(url_for('cust_app.multimedia', aa=1))
Exemplo n.º 6
0
def multi_del(f_id):
    """ to delete multimedia file """
    dire = absolute_path('static/multimedia/')
    if data.Media.query.filter_by(used=False).count() <= 0:
        flash("Error: there is no unused multimedia file to be removed !",
              'danger')
        return redirect(url_for('cust_app.multimedia', aa=1))
    if f_id == 00:
        for a in data.Media.query:
            if not a.used:
                if os.path.exists(dire + a.name):
                    os.remove(dire + a.name)
                db.session.delete(a)
        db.session.commit()
        flash("Notice: multimedia file been removed.", 'info')
        return redirect(url_for('cust_app.multimedia', aa=1))
    mf = data.Media.query.filter_by(id=f_id).first()
    if mf is not None:
        if mf.used:
            flash("Error: there is no unused multimedia file to be removed !",
                  'danger')
            return redirect(url_for('cust_app.multimedia', aa=1))
        if os.path.exists(dire + mf.name):
            os.remove(dire + mf.name)
        db.session.delete(mf)
        db.session.commit()
        flash("Notice: multimedia file been removed.", 'info')
        return redirect(url_for('cust_app.multimedia', aa=1))
    else:
        flash("Error: there is no unused multimedia file to be removed !",
              'danger')
        return redirect(url_for('core.root'))
Exemplo n.º 7
0
def get_tts_safely():
    ''' Helper to read gTTS data from `static/tts.json` file safely.

    Parameters
    ----------
        failsafe: boolean
            to silence any encountered errors.

    Returns
    -------
        Dict of gTTS content. Example::
        {"en-us": {"langauge": "English", "message": "new ticket!"}, ...}
    '''
    tts_path = os.path.join(absolute_path('static'), 'tts.json')
    tts_content = {}

    try:
        with open(tts_path, encoding='utf-8') as tts_file:
            tts_content.update(json.load(tts_file))
    except Exception as e:
        log_error(e)
        tts_content.update({
            'en-us': {
                'language': 'English',
                'message': ' , please proceed to the {} number : '
            }
        })

    return tts_content
Exemplo n.º 8
0
 def set_status(self, global_layout):
     font = self.font
     self.status_icon = QIcon(
         absolute_path(solve_path('static/images/pause.png')))
     self.status_icon_container = QLabel('Icond', self)
     self.status_icon = self.status_icon.pixmap(70, 70, QIcon.Active,
                                                QIcon.On)
     self.status_icon_container.setPixmap(self.status_icon)
     self.status_icon_container.setAlignment(QtCore.Qt.AlignCenter
                                             | QtCore.Qt.AlignHCenter)
     self.status_icon_container.setFont(font)
     self.status_label = QLabel('Texted', self)
     self.status_label.setText(
         self.get_translation('Server is <u> Not running </u> <br>'))
     self.status_label.setOpenExternalLinks(True)
     self.status_label.setAlignment(QtCore.Qt.AlignCenter
                                    | QtCore.Qt.AlignHCenter)
     self.status_label.setFont(font)
     self.status_label.setToolTip(
         self.get_translation('Status of the server'))
     self.status_icon_container.setToolTip(
         self.get_translation('Status of the server'))
     global_layout.addStretch()
     global_layout.addWidget(self.status_icon_container)
     global_layout.addWidget(self.status_label)
     global_layout.addStretch()
Exemplo n.º 9
0
 def __init__(self, app=None):
     super(MainWindow, self).__init__()
     self.app = app
     global_layout = QVBoxLayout(self)
     icon_path = absolute_path(solve_path('static/images/favicon.png'))
     # NOTE: need to use objective message boxes instead of functions to set font
     self.font = QFont("static/gfonts/Amiri-Regular.ttf", 12, QFont.Bold)
     self.fonts = QFont("static/gfonts/Amiri-Regular.ttf", 10, QFont.Bold)
     # Language support variable
     self.current_language = 'en'
     self.currently_running = False
     icon = QIcon(icon_path)
     self.initiate(icon)
     self.set_center()
     self.set_languages_list(global_layout)
     self.set_about(icon_path, global_layout)
     self.set_ips_and_ports(global_layout)
     self.set_status(global_layout)
     self.set_start_and_stop(global_layout)
     self.setLayout(global_layout)
     selected_ip_and_port = self.select_ips_ports_change()
     self.Process = RunnerThread(selected_ip_and_port[1].split(',')[1],
                                 selected_ip_and_port[0], self.app)
     self.activateWindow()
     self.show()
Exemplo n.º 10
0
def csv():
    ''' to export tables to `.csv` file '''
    form = CSVForm()

    if form.validate_on_submit():
        tabels = [t[0] for t in EXPORT_TABLES]

        if form.table.data not in tabels:
            flash('Error: wrong entry, something went wrong', 'danger')
            return redirect(url_for('core.root'))

        module = getattr(data, form.table.data, None)
        csv_path = absolute_path(f'csv_{form.table.data}.csv')
        delimiter = EXPORT_DELIMETERS[form.delimiter.data]

        with open(csv_path, 'w+') as csv_file:
            fields = get_module_columns(module)
            csv_buffer = DictWriter(csv_file,
                                    delimiter=delimiter,
                                    fieldnames=fields)
            rows = [{fields[i]: value
                     for i, value in enumerate(values)}
                    for values in get_module_values(module)]

            form.headers.data and csv_buffer.writeheader()
            csv_buffer.writerows(rows)

        return send_file(csv_path, mimetype='csv', as_attachment=True)

    return render_template('csvs.html',
                           navbar='#snb3',
                           page_title='Export CSV',
                           form=form)
Exemplo n.º 11
0
def create_db(app, testing=False):
    ''' Creating all non-existing tables and load initial data.

    Parameters
    ----------
        app: Flask app
            app to use its context to create tables and load initial data.
        testing: bool
            flag to disable migrations, mainly used during integration testing.
    '''
    with app.app_context():
        if not os.path.isfile(absolute_path(app.config.get('DB_NAME'))):
            db.create_all()
        else:
            try:
                database_upgrade(directory=absolute_path(MIGRATION_FOLDER))
            except Exception as exception:
                if not isinstance(exception, OperationalError):
                    log_error(exception, quiet=os.name == 'nt')
        create_default_records()
Exemplo n.º 12
0
def test_new_printed_ticket_fail(c):
    touch_screen_settings = Touch_store.query.first()
    touch_screen_settings.n = False
    db.session.commit()
    task = choice(Task.query.all())
    last_ticket = Serial.query.filter_by(task_id=task.id)\
                              .order_by(Serial.number.desc()).first()

    response = c.post(f'/serial/{task.id}', follow_redirects=True)
    new_ticket = Serial.query.filter_by(task_id=task.id)\
                             .order_by(Serial.number.desc()).first()

    with open(absolute_path('errors.log'), 'r') as errors_log:
        errors_log_content = errors_log.read()

    assert response.status == '200 OK'
    assert new_ticket.id == last_ticket.id
    assert 'escpos.exceptions.USBNotFoundError: USB device not found' in errors_log_content
Exemplo n.º 13
0
Arquivo: core.py Projeto: picsldev/FQM
def test_new_printed_ticket_fail(c):
    with c.application.app_context():
        # NOTE: set ticket setting to printed
        touch_screen_settings = Touch_store.query.first()
        touch_screen_settings.n = False
        db.session.commit()

        task = choice(Task.query.all())
        last_ticket = Serial.query.filter_by(task_id=task.id)\
                                  .order_by(Serial.number.desc()).first()

    response = c.post(f'/serial/{task.id}', follow_redirects=True)
    new_ticket = Serial.query.filter_by(task_id=task.id)\
                             .order_by(Serial.number.desc()).first()

    with open(absolute_path('errors.log'), 'r') as errors_log:
        errors_log_content = errors_log.read()

    assert response.status == '200 OK'
    assert new_ticket.id == last_ticket.id
    assert "ValueError: invalid literal for int() with base 10: ' '" in errors_log_content
Exemplo n.º 14
0
def test_upgrading_database(c):
    with c.application.app_context():
        assert database_upgrade(
            directory=absolute_path(MIGRATION_FOLDER)) is None
Exemplo n.º 15
0
def test_execute():
    path = absolute_path('static')

    assert sorted(execute(f'ls {path}',
                          parser='\n')) == sorted(os.listdir(path))
Exemplo n.º 16
0
def multimedia(aa):
    """ uploading multimedia files """
    # Number of files limit
    nofl = 300
    # size folder limit in MB
    sfl = 2000  # Fix limited upload folder size
    dire = absolute_path('static/multimedia/')
    pf = data.Media.query.order_by(data.Media.id.desc()).first()
    if pf is not None:
        pf = pf.name
    if aa == 0:
        if data.Media.query.count() >= nofl:
            flash(
                "Error: you have reached the amount limit of multimedia files "
                + str(nofl), 'danger')
            return redirect(url_for('cust_app.multimedia', aa=1))
        else:
            flash(
                "Notice: if you followed the rules, it should be uploaded ..",
                "success")
    elif aa != 1:
        flash('Error: wrong entry, something went wrong', 'danger')
        return redirect(url_for("core.root"))
    mmm = data.Media.query
    page = request.args.get('page', 1, type=int)
    pagination = data.Media.query.paginate(page, per_page=10, error_out=False)
    form = forms.Multimedia(session.get('lang'))
    if mmm.count() >= 1:
        from sqlalchemy.sql import or_
        for me in mmm:
            if os.path.isfile(dire + me.name):
                dl = [
                    data.Display_store.query.filter(
                        or_(data.Display_store.ikey == me.id,
                            data.Display_store.akey == me.id)).first(),
                    data.Touch_store.query.filter(
                        or_(data.Touch_store.ikey == me.id,
                            data.Touch_store.akey == me.id)).first(),
                    data.Slides.query.filter_by(ikey=me.id).first(),
                    data.Vid.query.filter_by(vkey=me.id).first()
                ]
                me.used = False
                for d in dl:
                    if d is not None:
                        me.used = True
                        break
                db.session.add(me)
                db.session.commit()
            else:
                if me.img or me.audio or me.vid:
                    for t in [
                            data.Touch_store, data.Display_store, data.Slides
                    ]:
                        t = t.query.filter_by(
                            or_(data.Display_store.ikey == me.id,
                                data.Display_store.vkey == me.id)).first()
                        if me.img or me.vid and t is not None:
                            if me.img:
                                t.ikey = None
                            if me.vid:
                                t.vid = None
                            if t != data.Slides:
                                t.bgcolor = "bg-danger"
                            else:
                                t.bgname = "bg-danger"
                            db.session.add(t)
                        ttt = t.query.filter_by(akey=me.id).first()
                        if me.audio and ttt is not None:
                            if t != data.Slides:
                                t.akey = None
                                t.audio = "false"
                                db.session.add(t)
                db.session.delete(me)
        db.session.commit()
    if form.validate_on_submit():
        ff = form.mf.data
        ffn = secure_filename(ff.filename)
        # dc = data.Media.query.count()
        # FIX ISSUE Remove folder size limitation
        # if int(utils.getFolderSize(dire)) >= sfl or dc >= nofl:
        #     return redirect(url_for('cust_app.multimedia', aa=1))
        e = ffn[-3:]
        if e in SUPPORTED_MEDIA_FILES[0]:
            files.save(request.files['mf'], name=ffn)
            if imghdr.what(dire + ffn) is None:
                os.remove(dire + ffn)
                return redirect(url_for("cust_app.multimedia", aa=1))
            db.session.add(data.Media(False, False, True, False, ffn))
            db.session.commit()
            return redirect(url_for("cust_app.multimedia", aa=1))
        elif e in SUPPORTED_MEDIA_FILES[1]:
            files.save(request.files['mf'], name=ffn)
            # FIXME: Find an alternative to sndhdr for audio file detection
            # if sndhdr.what(dire + ffn) is None:
            #     os.remove(dire + ffn)
            #     return redirect(url_for("cust_app.multimedia", aa=1))
            db.session.add(data.Media(False, True, False, False, ffn))
            db.session.commit()
            return redirect(url_for("cust_app.multimedia", aa=1))
        elif e in SUPPORTED_MEDIA_FILES[2] or ffn[
                -4:] in SUPPORTED_MEDIA_FILES[2]:
            files.save(request.files['mf'], name=ffn)
            db.session.add(data.Media(True, False, False, False, ffn))
            db.session.commit()
            return redirect(url_for("cust_app.multimedia", aa=1))
        else:
            flash('Error: wrong entry, something went wrong', 'danger')
            return redirect(url_for("cust_app.multimedia", aa=1))
    return render_template("multimedia.html",
                           page_title="Multimedia",
                           navbar="#snb2",
                           form=form,
                           hash="#da1",
                           mmm=mmm,
                           len=len,
                           ml=SUPPORTED_MEDIA_FILES,
                           mmmp=pagination.items,
                           pagination=pagination,
                           tc=data.Touch_store.query,
                           sl=data.Slides.query,
                           dc=data.Display_store.query,
                           fs=int(getFolderSize(dire, True)),
                           nofl=nofl,
                           sfl=sfl,
                           vtrue=data.Vid.query.first().enable,
                           strue=data.Slides_c.query.first().status)
Exemplo n.º 17
0
         'Alvin Friend', 'Ambrose Immortal', 'Amery Industrious',
         'Amos A Burden', 'Andrew Valiant', 'Angus Unique', 'Ansel Nobel',
         'Anthony Priceless', 'Archer Bowman', 'Archibald Prince',
         'Arlen Pledge', 'Arnold Eagle', 'Arvel Wept', 'Atwater Waterside',
         'Atwood Forest', 'Aubrey Ruler', 'Austin Helpful', 'Axel Peace',
         'Baird Bard', 'Baldwin Friend', 'Barnaby Prophet', 'Baron Nobleman',
         'Barrett Bear-Like', 'Barry Marksman', 'Bartholomew Warlike',
         'Basil King-like')
TEST_PREFIX = 'Z'
PREFIXES = [
    p for p in list(map(lambda i: chr(i).upper(), range(97, 123)))
    if p != TEST_PREFIX
]

MODULES = [Serial, User, Operators, Task, Office]
DB_PATH = absolute_path('testing.sqlite')
TEST_REPEATS = 3


@pytest.fixture
def c():
    app_config = {
        'LOGIN_DISABLED': True,
        'WTF_CSRF_ENABLED': False,
        'TESTING': True,
        'SQLALCHEMY_DATABASE_URI': f'sqlite:///{DB_PATH}'
    }
    db_fd, app_config['DATABASE'] = tempfile.mkstemp()
    app = bundle_app(app_config)

    # FIXME: Tasks are not integration tested yet.
Exemplo n.º 18
0
def print_ticket_windows_ar(pname, ti, ofc, tnu, tas, cticket, ip, l=None):
    def fsizeit(text, t, f):
        return f.getsize(t)

    def center(text, t, f):
        fs1, fs2 = fsizeit(text, t, f)
        return ((text.size[0] - fs1) / 2, (text.size[1] - fs2) / 2)

    if name == 'nt':
        fpath = absolute_path('static\\gfonts\\arial.ttf')
    else:
        fpath = absolute_path('static/gfonts/arial.ttf')
    fonts = [
        ImageFont.truetype(fpath, 50),
        ImageFont.truetype(fpath, 30),
        ImageFont.truetype(fpath, 25)
    ]

    logo = 'FQM ' + VERSION[:4]
    title = u'نظام إدارة الحشود الحر'
    title = arabic_reshaper.reshape(title)
    title = get_display(title)
    link = 'http://fqms.github.io'
    border = "#" * 20
    ticket = str(ti)
    officet = u'المكتب : ' + ofc
    office = arabic_reshaper.reshape(officet)
    office = get_display(office)
    try:
        taskt = u'المهمة : ' + tas
    except Exception:
        taskt = tas
    task = arabic_reshaper.reshape(taskt)
    task = get_display(task)
    datet = u'الوقت : '
    datet += str(datetime.now())[:-7]
    date = arabic_reshaper.reshape(datet)
    date = get_display(date)
    aheadt = u'تذاكر قبلك : '
    aheadt += str(tnu)
    ahead = arabic_reshaper.reshape(aheadt)
    ahead = get_display(ahead)
    cutit = u'التذكرة الحالية : '
    cutit += str(cticket)
    cuti = arabic_reshaper.reshape(cutit)
    cuti = get_display(cuti)

    w = 400
    bt_1 = Image.new('RGB', (w, 60), "white")
    bt_2 = Image.new('RGB', (w, 60), "white")
    bt_3 = Image.new('RGB', (w, 60), "white")
    st_1 = Image.new('RGB', (w, 50), "white")
    st_2 = Image.new('RGB', (w, 50), "white")
    st_3 = Image.new('RGB', (w, 50), "white")
    st_4 = Image.new('RGB', (w, 50), "white")
    st_5 = Image.new('RGB', (w, 50), "white")
    st_6 = Image.new('RGB', (w, 50), "white")
    st_7 = Image.new('RGB', (w, 50), "white")
    st_8 = Image.new('RGB', (w, 50), "white")
    tt = 50 * 8
    tt += 60 * 3
    mt = Image.new('RGB', (w, tt), "white")

    bd_1 = ImageDraw.Draw(bt_1)
    bd_2 = ImageDraw.Draw(bt_2)
    bd_3 = ImageDraw.Draw(bt_3)
    sd_1 = ImageDraw.Draw(st_1)
    sd_2 = ImageDraw.Draw(st_2)
    sd_3 = ImageDraw.Draw(st_3)
    sd_4 = ImageDraw.Draw(st_4)
    sd_5 = ImageDraw.Draw(st_5)
    sd_6 = ImageDraw.Draw(st_6)
    sd_7 = ImageDraw.Draw(st_7)
    sd_8 = ImageDraw.Draw(st_8)
    md = ImageDraw.Draw(mt)

    b = "black"
    bd_1.text(center(bt_1, logo, fonts[0]), logo, font=fonts[0], fill=b)
    bd_2.text(center(bt_2, title, fonts[1]), title, font=fonts[1], fill=b)
    bd_3.text(center(bt_3, ticket, fonts[0]), ticket, font=fonts[0], fill=b)
    sd_1.text(center(st_1, link, fonts[2]), link, font=fonts[2], fill=b)
    sd_2.text(center(st_2, border, fonts[2]), border, font=fonts[2], fill=b)
    sd_3.text(center(st_3, border, fonts[2]), border, font=fonts[2], fill=b)
    sd_4.text(center(st_4, office, fonts[2]), office, font=fonts[2], fill=b)
    sd_5.text(center(st_5, task, fonts[2]), task, font=fonts[2], fill=b)
    sd_6.text(center(st_6, date, fonts[2]), date, font=fonts[2], fill=b)
    sd_7.text(center(st_7, ahead, fonts[2]), ahead, font=fonts[2], fill=b)
    sd_8.text(center(st_8, cuti, fonts[2]), cuti, font=fonts[2], fill=b)

    tts = 0
    mt.paste(bt_1, (0, 0))
    tts += bt_1.size[1]
    mt.paste(bt_2, (0, tts))
    tts += bt_2.size[1]
    mt.paste(st_1, (0, tts))
    tts += st_1.size[1]
    mt.paste(st_2, (0, tts))
    tts += st_2.size[1]
    mt.paste(bt_3, (0, tts))
    tts += bt_3.size[1]
    mt.paste(st_3, (0, tts))
    tts += st_3.size[1]
    mt.paste(st_4, (0, tts))
    tts += st_4.size[1]
    mt.paste(st_8, (0, tts))
    tts += st_8.size[1]
    mt.paste(st_7, (0, tts))
    tts += st_7.size[1]
    mt.paste(st_5, (0, tts))
    tts += st_5.size[1]
    mt.paste(st_6, (0, tts))

    sffs = []
    sfs = [
        f'{uuid.uuid4()}'.replace('-', '') + '.jpg',
        f'{uuid.uuid4()}'.replace('-', '') + '.txt'
    ]

    for f in sfs:
        sffs.append(path.join(getcwd(), f))
    mt.save(sfs[0], format="JPEG")
    p = Dummy()
    p.image(sfs[0], fragment_height=tt, high_density_vertical=True)
    p.cut()
    f = open(sfs[1], 'wb+')
    f.write(p.output)
    p.close()
    f.close()

    text = f'print /D:\\\localhost\\"{pname}" "{sfs[1]}"'
    system(text)
    for f in sffs:
        if path.isfile(f):
            remove(f)
Exemplo n.º 19
0
def test_upgrading_database(c):
    assert database_upgrade(directory=absolute_path(MIGRATION_FOLDER)) is None
Exemplo n.º 20
0
def multimedia(aa):
    ''' uploading multimedia files '''
    if aa == 0:
        flash('Notice: if you followed the rules, it should be uploaded ..',
              'success')

    files_limit_indicator = 300
    folder_size_limit_indicator = 2000
    media_path = absolute_path('static/multimedia')
    form = MultimediaForm()
    medias = data.Media.query
    page = request.args.get('page', 1, type=int)
    pagination = data.Media.query.paginate(page, per_page=10, error_out=False)
    supported_images = SUPPORTED_MEDIA_FILES[0]
    supported_audios = SUPPORTED_MEDIA_FILES[1]
    supported_videos = SUPPORTED_MEDIA_FILES[2]
    supported_all = supported_images + supported_audios + supported_videos

    if medias.count():  # cleanup unused media files
        for media in medias:
            if os.path.isfile(os.path.join(media_path, media.name)):
                media.used = media.is_used()
            else:
                db.session.delete(media)

        db.session.commit()

    if form.validate_on_submit():
        name = secure_filename(form.mf.data.filename)
        extension = name[-3:]

        if extension in supported_all:
            files.save(request.files['mf'], name=name)
            db.session.add(
                data.Media(
                    extension in supported_videos
                    or name[-4:] in supported_videos, extension
                    in supported_audios, extension in supported_images, False,
                    name))
        else:
            flash('Error: wrong entry, something went wrong', 'danger')
            return redirect(url_for('cust_app.multimedia', aa=1))

        db.session.commit()
        return redirect(url_for('cust_app.multimedia', aa=0))

    return render_template('multimedia.html',
                           page_title='Multimedia',
                           navbar='#snb2',
                           form=form,
                           hash='#da1',
                           mmm=medias,
                           len=len,
                           ml=SUPPORTED_MEDIA_FILES,
                           mmmp=pagination.items,
                           pagination=pagination,
                           tc=data.Touch_store.query,
                           sl=data.Slides.query,
                           dc=data.Display_store.query,
                           fs=int(getFolderSize(media_path, True)),
                           nofl=files_limit_indicator,
                           sfl=folder_size_limit_indicator,
                           vtrue=data.Vid.get().enable,
                           strue=data.Slides_c.get().status)
Exemplo n.º 21
0
         'Alexander Protector', 'Alfred Wise', 'Avery Elfin Ruler',
         'Alvin Friend', 'Ambrose Immortal', 'Amery Industrious',
         'Amos A Burden', 'Andrew Valiant', 'Angus Unique', 'Ansel Nobel',
         'Anthony Priceless', 'Archer Bowman', 'Archibald Prince',
         'Arlen Pledge', 'Arnold Eagle', 'Arvel Wept', 'Atwater Waterside',
         'Atwood Forest', 'Aubrey Ruler', 'Austin Helpful',
         'Axel Peace', 'Baird Bard', 'Baldwin Friend', 'Barnaby Prophet',
         'Baron Nobleman', 'Barrett Bear-Like', 'Barry Marksman',
         'Bartholomew Warlike', 'Basil King-like')
TEST_PREFIX = 'Z'
PREFIXES = [p for p in list(map(lambda i: chr(i).upper(), range(97, 123))) if p != TEST_PREFIX]

MODULES = [Serial, User, Operators, Task, Office, Media, Slides, AuthTokens]
DEFAULT_MODULES = [Touch_store, Display_store, Vid, Slides_c, Aliases, Printer, Settings]
DB_NAME = 'testing.sqlite'
DB_PATH = absolute_path(DB_NAME)
TEST_REPEATS = 3
ENTRY_NUMBER = 4


@atexit.register
def before_exit():
    os.path.isfile(DB_PATH) and os.remove(DB_PATH)
    os.path.isfile(absolute_path('errors.log')) and os.remove(absolute_path('errors.log'))


@pytest.fixture
def c():
    app_config = {'LOGIN_DISABLED': True,
                  'WTF_CSRF_ENABLED': False,
                  'TESTING': True,
Exemplo n.º 22
0
def before_exit():
    os.path.isfile(DB_PATH) and os.remove(DB_PATH)
    os.path.isfile(absolute_path('errors.log')) and os.remove(absolute_path('errors.log'))