Пример #1
0
    def create_structure(self):
        """Создаем структуру"""
        make_folder(self.themeforest)
        self.template_path = '%s/%s' % (self.themeforest, self.template)
        self.css_path = os.path.join(self.template_path, 'css')
        self.js_path = os.path.join(self.template_path, 'js')
        self.img_path = os.path.join(self.template_path, 'img')
        self.misc_path = os.path.join(self.template_path, 'misc')

        drop_folder(self.css_path)
        drop_folder(self.js_path)
        drop_folder(self.img_path)
        drop_folder(self.misc_path)

        make_folder(self.css_path)
        make_folder(self.js_path)
        make_folder(self.img_path)
        make_folder(self.misc_path)

        # ------------------------------------------
        # Записать ссылку на источник, откуда тыбзим
        # ------------------------------------------
        reference = '%s/%s' % (self.template_path, 'reference.txt')
        with open_file(reference, 'w+') as f:
            f.write(self.url_template)
Пример #2
0
    def handle(self, *args, **options):
        """Загрузка email ов для формирования xlsx
           для загрузки в спам лист для рассылки"""
        fname = 'clients_emails'
        link = 'https://223-223.ru/media/%s.json' % fname
        r = requests.get(link)
        rows = json.loads(r.text)
        folder = 'spamcha'
        make_folder(folder)

        xls_file = '%s.xlsx' % fname
        dest = full_path(os.path.join(folder, xls_file))
        book = xlsxwriter.Workbook(dest)
        sheet = book.add_worksheet('Лист 1')
        row_number = 0

        titles = (
            'client_id',
            'client_name',
            'dest',
            'name',
        )
        for i, title in enumerate(titles):
            sheet.write(row_number, i, title)

        for row in rows:
            row_number += 1
            for i, field in enumerate(row):
                sheet.write(row_number, i, field)
        book.close()
Пример #3
0
def spam_tables_images(request, *args, **kwargs):
    """Работа с изображениями через redactor"""
    result = {}
    folder = 'sp-images'  # Чтобы не фигурировало spam
    make_folder(folder)
    mh_vars = spam_tables_vars.copy()
    # Список изображений:
    #[{ "thumb": "/img/1m.jpg", "image": "/img/1.jpg", "title": "Image 1", "folder": "Folder 1" }, ... ]
    # Ответ по загрузке:
    # { "filelink": "/images/img.jpg" }
    perms = get_user_permissions(request.user, mh_vars['model'])
    if request.FILES and perms['edit']:
        result['filelink'] = '/static/img/ups.png'
        f = request.FILES.get('file')
        if f:
            dest = os.path.join(folder, f.name)
            if catch_file(f, dest):
                result['filelink'] = '/media/%s' % dest
    elif request.method == 'GET':
        result = []
        items = ListDir(folder)
        for item in items:
            path = os.path.join(folder, item)
            img = '/media/%s' % path
            if isForD(path) == 'file' and extension(item):
                result.append({
                    'thumb': img,
                    'image': img,
                    'title': '',
                    'folder': folder,
                })
    return JsonResponse(result, safe=False)
Пример #4
0
    def upload_img(self, img):
        """Загрузка изображения"""
        new_img = None
        if self.img:
            self.drop_img()
        # ---------------------------------------------------
        # django.core.files.uploadedfile.InMemoryUploadedFile
        # ---------------------------------------------------
        if type(img) == InMemoryUploadedFile:
            ext = extension(img.name)
            if ext:
                media_folder = self.get_folder()
                if check_path(media_folder):
                    make_folder(media_folder)
                new_img = "%s%s" % (self.id, ext)
                path = os.path.join(media_folder, new_img)
                if catch_file(img, path):
                    imageThumb(path, 1920, 1280)
        # ------------------------------
        # Загрузка изображения по ссылке
        # ------------------------------
        elif type(img) == str:
            new_img = grab_image_by_url(img, self.get_folder(), str(self.id))
            if new_img:
                path = os.path.join(self.get_folder(), new_img)
                img = imageThumb(path, 1920, 1280)
                if not img:
                    self.drop_img()
                    return None
            else:
                new_img = None
        # ----------------------------------------------------
        # django.core.files.uploadedfile.TemporaryUploadedFile
        # ----------------------------------------------------
        elif type(img) == TemporaryUploadedFile:
            path = img.temporary_file_path()
            tmp_file = open(path, 'rb')
            img_content = tmp_file.read()
            tmp_file.close()
            ext = extension(img.name)
            new_img = '{}{}'.format(str(self.id), ext)
            media_folder = self.get_folder()
            if check_path(media_folder):
                make_folder(media_folder)
            dest = os.path.join(media_folder, new_img)
            img_file = open_file(dest, 'wb+')
            img_file.write(img_content)
            img_file.close()
            img = imageThumb(dest, 1920, 1280)
            if not img:
                self.drop_img()
                return None
        else:
            logger.error('Unknown img type %s' % (type(img), ))
            assert False

        self.__class__.objects.filter(pk=self.id).update(img=new_img)
        self.img = new_img
        return new_img
Пример #5
0
def create_daemon(daemon_name,
                  exec_script,
                  port,
                  pyenv: str = None,
                  api_url: str = None):
    """Создаем демона
       :param daemon_name: название демона, например daemon_1.service
       :param exec_script: исполняемый файл, например,
           /home/jocker/sites/astwobytes/apps/ws_a223/wss_server.py
       :param port: параметр для передачи в испольняемый файл, например
           порт на котором должен запускаться демон
           скрипт должен принимать этот параметр,
           демон к этому не имеет отношения, просто передает
       :param pyenv: питонячий путь для запуска через python, например,
           /home/jocker/sites/astwobytes/env/bin/python
       :param api_url: endpoint, чтобы обращаться за настройками,
           отправлять обновления
       :return:
       --------
       В демоне не нужно активировать виртуальное окружение,
       можно просто запускать исполняемый файл вирт. окружения,
       там уже содержатся все нужные пути -
       Проверить это можно через
       # python -m site
       сравниваем с
       # /home/jocker/sites/astwobytes/env/bin/python -m site
       - покажет базу и пути
       """
    if check_path(DAEMON_FOLDER):
        make_folder(DAEMON_FOLDER)

    if not pyenv:
        pyenv = '%s/env/bin/python' % (settings.BASE_DIR.rstrip('/'), )

    #daemon_path = '%s/%s.service' % (SYSTEM_FOLDER, daemon_name)
    #if os.path.exists(daemon_path):
    #    logger.info('daemon already exists')
    #    os.unlink(daemon_path)

    daemon_script = """[Unit]
Description=%s
After=multi-user.target
ConditionPathExists=%s

[Service]
ExecStart=%s %s %s %s
Restart=always
Type=idle

[Install]
WantedBy=multi-user.target
#Alias=%s # Алиас не должен быть таким же как имя сервсиа
""" % (daemon_name, exec_script, pyenv, exec_script, port, api_url,
       daemon_name)

    daemon = '%s/%s' % (DAEMON_FOLDER, daemon_name)
    with open_file(daemon, 'w+') as f:
        f.write(daemon_script)
Пример #6
0
def script_titul(request, *args, **kwargs):
    """Анализ архива с титулом (список узлов в титуле)"""
    result = {}
    context = scripts_vars.copy()

    context['material_choices'] = MATERIALS
    context['welding_types'] = WELDING_TYPES
    context['join_types'] = JOIN_TYPES
    context['conn_view_choices'] = Joint.welding_conn_view_choices

    folder = 'scripts'
    if request.method == 'GET':
        make_folder(folder)
        # тут лежат архивы
        # нас интересуют только zip
        dirs = ListDir(folder)

    if request.is_ajax():
        return JsonResponse(result, safe=False)
    if request.FILES.get('path'):
        docx_files = None
        fname = request.FILES['path']
        if not fname.name.endswith('.zip') and not fname.name.endswith('.docx'):
            result['error'] = 'Поддерживается только zip-архив или docx'
        else:
            path = os.path.join(folder, fname.name)
            if catch_file(fname, path):
                result['success'] = 'Файл загружен'
                now = '%s' % time.time()
                now = now.replace('.', '-')
                dest_folder = os.path.join(folder, now)
                if fname.name.endswith('.zip'):
                    unzip(path, dest_folder)
                else:
                    make_folder(dest_folder)
                    copy_file(path, dest_folder)
                docx2html(dest_folder)

                preview = titul_docx2excel(dest_folder)
                result.update(preview)
                drop_file(path)

        return JsonResponse(result, safe=False)
    template = '%stitul.html' % (context['template_prefix'], )
    return render(request, template, context)
Пример #7
0
    def handle(self, *args, **options):
        """Создаем uwsgi файл, который нужно будет разместить в
           /etc/uwsgi/apps-available/, например,
           /etc/uwsgi/apps-available/astwobytes.ini"""

        logger.info("""please, do following:
---------------------------------
--- INSTALL uwsgi for python3 ---
---------------------------------
# apt-get install uwsgi-plugin-python3
# apt install uwsgi-plugin-python
look at /usr/lib/uwsgi/plugins, check python3_plugin.so python_plugin.so
if it does not exists
if we have python LOWER 3.6, let is build
-------------------------------
--- BUILD uwsgi for python3 ---
-------------------------------
# sudo apt install python3.6 python3.6-dev uwsgi uwsgi-src uuid-dev libcap-dev libpcre3-dev libssl-dev
$ cd ~
$ export PYTHON=python3.6
$ uwsgi --build-plugin "/usr/src/uwsgi/plugins/python python36"
$ sudo mv python36_plugin.so /usr/lib/uwsgi/plugins/python36_plugin.so
$ sudo chmod 644 /usr/lib/uwsgi/plugins/python36_plugin.so
$ uwsgi --plugin python36 -s :0
""")

        folder = 'demonize'
        if check_path(folder):
            make_folder(folder)
        uwsgi_path = '%s/astwobytes.ini' % (folder, )
        with open_file(uwsgi_path, 'w+') as f:
            f.write("""[uwsgi]
  processes = 1
  master = true
  plugins = python36
  chdir = /home/jocker/sites/astwobytes
  harakiri = 40
  wsgi-file = /home/jocker/sites/astwobytes/conf/wsgi.py
  pythonpath = /home/jocker/sites/astwobytes/env/lib/python3.6/site-packages
  buffer-size = 8192
""")
        logger.info('created %s' % (uwsgi_path, ))
Пример #8
0
    def save(self, *args, **kwargs):
        cid = kill_quotes(self.cid, 'int')
        if cid.startswith('7'):
            cid = '8%s' % (cid[1:], )
        self.cid = cid
        super(FSUser, self).save(*args, **kwargs)
        if not self.is_active or not self.user or not self.passwd or not self.context or not self.cid:
            self.drop_extension()
            return
        extension = """
<include>
  <user id="{}">
    <params>
      <param name="password" value="{}"/>
    </params>
    <variables>
      <variable name="toll_allow" value="domestic,international,local"/>
      <variable name="accountcode" value="{}"/>
      <variable name="user_context" value="{}"/>
      <variable name="effective_caller_id_name" value="{}"/>
      <variable name="effective_caller_id_number" value="{}"/>
      <variable name="outbound_caller_id_name" value="{}"/>
      <variable name="outbound_caller_id_number" value="{}"/>
      <variable name="callgroup" value="{}"/>
    </variables>
  </user>
</include>""".format(self.user.username,
                     self.passwd,
                     self.user.username,
                     self.context,
                     self.user.username,
                     self.user.username,
                     self.cid,
                     self.cid,
                     self.callgroup)
        fname = full_path('%s/fs_user_%s.xml' % (self.FOLDER, self.id))
        if check_path(fname):
            make_folder(self.FOLDER)
        with open(fname, 'w+') as f:
            f.write(extension)
        FreeswitchBackend(settings.FREESWITCH_URI).reloadxml()
Пример #9
0
 def create_robots_txt(domain: dict = None):
     """Вспомогательная функция для создания robotx.txt файла
        :param domain: словарь с параметрами домена
     """
     if not domain:
         domain = {}
     robots_txt = Files.objects.create(
         link=robots_txt_link,
         name='robots.txt',
         desc='Файл для запретов индексации поисковым системам',
         domain=domain.get('pk'))
     folder = robots_txt.get_folder()
     make_folder(folder)
     dest = '%s%s' % (folder.rstrip('/'), robots_txt_link)
     with open_file(dest, mode='w+', encoding='utf-8') as f:
         domain_site = domain.get('domain')
         if not domain_site:
             domain_site = settings.MAIN_DOMAIN or 'masterme.ru'
         f.write(robots_txt_content.format(domain_site))
     robots_txt.path = robots_txt_link.lstrip('/')
     robots_txt.save()
Пример #10
0
    def save(self, *args, **kwargs):
        super(Redirects, self).save(*args, **kwargs)
        if not self.is_active:
            self.drop_extension()
            return
        extension = """
<extension name="redirect_{}">
  <condition field="destination_number" expression="^([78]{})$">
    <action application="set" data="effective_caller_id_number={}"/>
    <action application="set" data="effective_caller_id_name={}"/>
    <action application="set" data="ringback={}"/>
    <action application="export" data="hold_music={}"/>
    <action application="set" data="ignore_early_media=true" />
    <action application="set" data="record_file_name={}"/>
    <action application="set" data="media_bug_answer_req=true"/>
    <action application="export" data="execute_on_answer=record_session {}"/>
    <action application="set" data="sip_h_Diversion=&quot;{}&quot; <sip: {}@{}>;reason=unconditional;"/>
    <action application="bridge" data="sofia/gateway/{}/{}"/>
  </condition>
</extension>""".format(self.phone,
                       kill_quotes(self.phone[1:], 'int'),
                       '${caller_id_number}',
                       '${caller_id_number}',
                       '${us-ring}',
                       '$${hold_music}',
                       '$${base_dir}/${context}/${strftime(%Y-%m-%d)}/${destination_number}_${uuid}.wav',
                       '${record_file_name}',
                       '${diversion_phone}',
                       '${diversion_phone}',
                       '${diversion_domain}',
                       self.gw,
                       kill_quotes(self.dest, 'int'))
        fname = full_path('%s/redirect_%s.xml' % (self.FOLDER, self.id))
        if check_path(fname):
            make_folder(self.FOLDER)
        with open(fname, 'w+') as f:
            f.write(extension)
        FreeswitchBackend(settings.FREESWITCH_URI).reloadxml()
Пример #11
0
 def upload_file(self, fname, field: str, additional_update: dict = None):
     """Загрузка файла в нужное поле
        :param fname: файл
        :param field: поле в которое загружаем файл
        :param additional_update: доп. поля, которые хотим
                                  обновить у модели,
                                  например, {'name': '123.txt'}
     """
     new_fname = None
     if not hasattr(self, field):
         return None
     if not additional_update:
         additional_update = {}
     self.drop_file(field)
     media_folder = self.get_folder()
     if check_path(media_folder):
         make_folder(media_folder)
     ext = fname.name.split(".")[-1]
     if len(ext) > 5:
         return None
     # ---------------------------------------------
     # field подставляем, чтобы не заменило картинку
     # или чтобы не совпало с другими ибучими полями
     # ---------------------------------------------
     new_fname = "%s_%s.%s" % (field, self.id, ext)
     path = os.path.join(media_folder, new_fname)
     params = {
         field: new_fname,
     }
     params.update(additional_update)
     if catch_file(fname, path):
         self.__class__.objects.filter(pk=self.id).update(**params)
         setattr(self, field, new_fname)
     else:
         self.__class__.objects.filter(pk=self.id).update(**{field: None})
         setattr(self, field, None)
     return new_fname
Пример #12
0
def export_templates():
    """Экспорт шаблонов"""
    templates = Containers.objects.filter(state__in=(99, 100),
                                          tag__isnull=False)
    for template in templates:
        make_folder('export')
        path = os.path.join('export', template.tag)
        make_folder(path)
        if template.img:
            copy_file(os.path.join(template.get_folder(), template.img),
                      os.path.join(path, template.img))
        obj = object_fields(template)
        obj['blocks'] = []
        blocks = template.blocks_set.all()
        blocks_path = os.path.join(path, 'blocks')
        make_folder(blocks_path)
        for block in blocks:
            if block.img:
                copy_file(os.path.join(block.get_folder(), block.img),
                          os.path.join(blocks_path, block.img))
            obj['blocks'].append(
                object_fields(block, pass_fields=('container', )))

        json_path = os.path.join(path, 'template.json')
        with open_file(json_path, 'w+', encoding='utf-8') as f:
            f.write(json.dumps(obj))

        template_fname = '%s.html' % template.tag
        template_src = os.path.join(settings.BASE_DIR,
                                    'apps/site/templates/web/containers/',
                                    template_fname)
        template_dest = os.path.join(settings.MEDIA_ROOT, path, template_fname)
        if os.path.exists(template_src):
            shutil.copy2(template_src, template_dest)
        else:
            logger.info('template not found %s' % template_src)