Microimpuls Smarty - документация по платформе Middleware для управления интерактивным IPTV/OTT

Contents:

1. The description of IPTV/OTT Middleware Smarty

Актуальное описание системы в новой базе знаний по продукту на сайте: https://microimpuls.com/docs/smarty/about

1.1. The system architecture

Актуальное описание архитектуры системы в новой базе знаний по продукту на сайте: https://microimpuls.com/docs/smarty/about

1.2. System requirements

Актуальные системные требования в новой базе знаний по продукту на сайте: https://microimpuls.com/docs/smarty/about/system-requirements

2. Installation and configuration of the Smarty server

2.1. Where to download the installation packages

Installation packages are distributed via FTP, access to which is granted for the duration of the contract.

2.2. Installation on Linux Debian

All the Smarty modules are shipped as an installable deb packages, and are installable with dpkg utility. smarty-base is an integral module.

Needed packages are nginx web server, uwsgi, python 2.7, and several others.

2.2.1. Installing dependencies

Installing via apt-get:

sudo apt-get install nginx git python-dev python2.7 libmysqlclient-dev libtiff5-dev libjpeg62-turbo-dev zlib1g-dev
libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk uwsgi uwsgi-plugin-python redis-server

Installation of the pip utility:

wget https://bootstrap.pypa.io/get-pip.py && python get-pip.py && rm get-pip.py

2.2.2. Installing Smarty and modules

Installing via dpkg:

dpkg -i smarty*.deb
dpkg -i python2.7-jsonrpctcp*.deb

After installing Smarty pakages, you need to install the python libraries via pip:

sudo pip install -r /usr/share/nginx/html/microimpuls/smarty/requirements.txt

After installation of the smarty-base package it is being created a configuration file for nginx in /etc/nginx/sites-available/smarty. Defaults to the domain smarty.example.com and listening to port 80 and 8180. Change this domain to yours.

Smarty files are located in /usr/share/nginx/html/microimpuls/smarty.

2.2.3. Installing the database schema

Initial installation of the database schema is performed with the command:

smarty_manage migrate --settings=settings.<settings filename>

2.2.4. Creating user administrator

Create user with service admin rights with the command:

smarty_manage createsuperuser --settings=settings.<settings filename>

2.2.5. Creating system objects in the database and examples of operator settings

To create system objects Smarty in the database, as well as example settings, run the command:

smarty_manage setup_initial_data --settings=settings.<settings filename>

Note

You can skip creating the sample operator settings, adding the flag --no-sample-data

2.2.6. Клонирование Client со всеми настройками оператора

В случае необходимости создания нового объекта Client и копирования всех данных можно использовать команду клонирования:

smarty_manage clone_client --src_client_id=<source client id> --settings=settings.<settings filename>
  • <source client id> - ID объекта Client, который нужно склонировать в новый Client.
  • <settings filename> - the file name of the Smarty settings, in which must be set the connection settings to the database (see Description of the main parameters of).

Note

Можно перенести также все телеканалы, фильмы, радиостанции, камеры и сервисы, используя соответствующие опции --clone-channels --clone-video --clone-radio --clone-cameras --clone-apps

2.2.7. Создание пользователя или восстановление пароля

В Smarty возможно создание или восстановление пользователя через команду create_user:

smarty_manage create_user --settings=settings.<settings filename> --username=new_user --password=new_password --is_admin=True --client_id=1 --is_superuser=True

Параметры:

  • –username - имя пользователя, обязательный.
  • –password - пароль, обязательный.
  • –is_admin - True или False, если True, то создаваемому пользователю будет доступна служебная часть сайта, по умолчанию False.
  • –client_id - ID клиента, к которому будет привязан создаваемы пользователь.
  • –is_superuser - True или False, если True, то будет создаен суперпользователь, по умолчанию False.
  • –monitoring_user - True или False, если True, то пользователь будет являться оператором мониторинга устройств, по умолчанию False.
  • –reset_password - если True, то в случае, если указанный username уже используется, то вместо создания нового будет изменён пароль у старого пользователя; по умолчанию False.

2.2.8. Создание Client

В Smarty возможно создание оператора (Client) через команду create_client:

smarty_manage create_client --settings=settings.<settings filename> --name=Client_name --api_key=api_key --domain_prefix=domain_prefix --email=email@example.com

Параметры:

  • –name - название оператора, обязательный.
  • –api_key - TVMW API Key, обязательный.
  • –domain_prefix - префикс домена оператора, обязательный.
  • –email - email оператора, обязательный.

2.3. Installation on Linux CentOS

Support for CentOS is experimental - correct operation of all functions of Smarty is not guaranteed. The setup script for fabric and the configuration examples for CentOS can be found here: https://github.com/microimpuls/smarty-centos

2.4. Smarty Configuration

2.4.1. The configuration file Smarty

After the initial installation of the base configuration file Smarty is located at the address /etc/microimpuls/smarty/base.py (link to /usr/share/nginx/html/microimpuls/smarty/settings/base.py).

The main configuration file used for production-mode - /etc/microimpuls/smarty/prod.py. This file (or other configuration used) must specify the symlink in /usr/share/nginx/html/microimpuls/smarty/settings/<setings name>.py. It should be set Smarty, because a basic configuration file can be overwritten after updates.

Configuration is made by assigning values to variables in Python.

2.4.1.1. Maintaining multiple Smarty instances on a single server

For convenience, the configuration and placement on a single server, multiple instances of Smarty instead of using the settings file prod.py create your own file with a short symbolic name that matches the service name, for example myiptv.py.

This name is then also recommended to use as a prefix or suffix in the names of configuration files nginx, uwsgi, the names of the folders for logs, pid files, etc.

2.4.2. Description of the configuration parameters to Smarty

Актуальная документация: https://microimpuls.com/docs/smarty/configuring-and-management/smarty-config https://microimpuls.com/docs/smarty/configuring-and-management/logging

2.4.3. Adding a license key server, Smarty

Each instance of Smarty is tied to the hardware and software configuration server license key, which can be limited by time steps and the maximum number of configured Client ID (see Multiprovider).

The license key is configured in the configuration file in the following variables:

SMARTY_KEY = 'XXXXXXX-XXXXXXX-XXXXXXX-XXXXXXX'
SMARTY_MAX_CLIENTS = 2
SMARTY_AVAILABLE_UNTIL = 'dd.mm.yyyy'

To obtain the key you must contact your Manager on the contract.

2.4.4. Setting up caching

For caching server is used Redis - is a required component of the system. It requires Redis >= 2.6.

The default configuration assumes a local installation of Redis server on the same server with Smarty, but if necessary, they can be divided. To change connection settings for Redis configuration is required Smarty to register an array CACHES as follows:

CACHES = {
    "default": {
        "BACKEND": "core.cache.backends.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
        }
    }
}

In the configuration file Redis /etc/redis/redis.conf I need to write:

stop-writes-on-bgsave-error no

Для оптимизации дисковых операций и увеличения общей производительности на сервере Redis рекомендуем также указать опцию, запрещающую сохранение на диск текущих данных сервера:

save ""

При ее указании все данные во время работы Redis будут храниться ТОЛЬКО в RAM сервера. В случае перезапуска сервера Redis рекомендуем запустить менеджмент команду flushall для заполнения Redis данными, используемыми Smarty.

Для вступления изменений конфигурации в силу требуется перезагрузить Redis и uwsgi.

Operation is also supported in cluster mode with a group of Redis servers configuration example:

CACHES = {
    "default": {
        "BACKEND": "core.cache.backends.RedisCache",
        "LOCATION": "redis://192.168.33.11:7000/0", # не используется, но необходимо
        "OPTIONS": {
            "REDIS_CLIENT_CLASS": "rediscluster.client.StrictRedisCluster",
            "CONNECTION_POOL_CLASS": "core.cache.cluster_connection.ClusterConnectionPool",
            "CONNECTION_POOL_KWARGS": {
                "startup_nodes": [
                    # masters
                    {"host": "192.168.33.11", "port": "7000"},
                    {"host": "192.168.33.12", "port": "7000"},
                    {"host": "192.168.33.13", "port": "7000"},
                ]
            }
        }
    }
}

2.4.5. Configuration of the module geolocation

Supports multiple locators based on IP addresses of the subscriber, working with different sources of geo-data. In service-admin for custom Client ID, you must install the locator used, the most suitable for the operator and its region of service provision.

If you have to change the locator database of countries and cities have already been filled, it is recommended to clean it.

All locators require the creation/updating its database. The database can be in the form of SQL tables, or binary data (or both).

2.4.5.1. Locator django-geoip (ipgeobase)

Is a wrapper around the https://django-geoip.readthedocs.org/en/latest/

The command to update the database:

$ smarty_manage geoip_update --settings=settings.<settings name>

The creation of countries and cities based on the data of django-geoip (only works if there is no country and city):

$ smarty_manage sync_geo_geoip --settings=settings.<settings name>
2.4.5.2. Locator ip2location

Database update:

$ smarty_manage update_ip2location --settings=settings.<settings name>

This command downloads a binary database to determine the location and CSV database to create a directory of cities and countries.

The creation of countries and cities based on data from ip2location (only works if there is no country and city):

$ smarty_manage sync_geo_ip2location --settings=settings.<settings name>

After you select the locator and synchronization mechanism geolocation is ready to use. The availability of various Middleware services (TV, movies, streaming services, options, etc.) is determined by the tariff packages (see the possibility of billing), in the settings where you can specify the country and city in which they operate.

2.4.6. Setting of the monitoring module of the video streams

Актуальная документация: https://microimpuls.com/docs/smarty/configuring-and-management/monitoring-and-alarming

2.4.7. Configuration of the module statistics and reports

См. https://micro.im/docs/smarty/configuring-and-management/viewstats

2.4.8. Настройка модуля сбора статистики по абонентам

См. https://micro.im/docs/smarty/configuring-and-management/viewstats

2.4.9. Настройка модуля мониторинга устройств

Актуальная документация: https://microimpuls.com/docs/smarty/configuring-and-management/monitoring-and-alarming

2.4.10. Настройка модуля отправки SMS

Актуальная документация: https://micro.im/docs/smarty/extra-services-integration/интеграция-с-sms-шлюзами

2.4.11. Подключение системы мониторинга ошибок Sentry

To connect Sentry need in the configuration file to add Smarty in INSTALLED_APPS module raven.contrib.django.raven_compat and set the connection parameters:

RAVEN_CONFIG = {
    'dsn': 'http://<LOGIN>:<PASS>@<SENTRY HOST>/<PROJECT>',
}

The connection string can be obtained from the project settings in Sentry.

2.4.12. Настройка nginx и uwsgi

A sample configuration file for the nginx is in the file /etc/nginx/sites-available/smarty.

Configuration for uwsgi is in the file /etc/uwsgi/apps-available/smarty and /etc/microimpuls/smarty/uwsgi/smarty.uwsgi on it (or another used the config) must specify the symlink in /usr/share/nginx/html/microimpuls/smarty/<uwsgi settings name>.uwsgi.

2.4.13. Настройка мультиязычности контента в Smarty

Smarty allows you to save database content of names of localizable fields in different languages - for example, the names of channels, movies, categories, genres, EPG etc. to activate this mechanism, you must add a configuration file option SMARTY_ADDITIONAL_LANGUAGES list of required languages (not more than 5 additional to the main languages), and specify the primary language. The language names must match the locale name in the user application, the default is to use the two-letter names.

SMARTY_DEFAULT_LANGUAGE str
The name of the main language. Default EN.
SMARTY_ADDITIONAL_LANGUAGES list
A list of additional languages, specified in square brackets with indication of values separated by commas, for example: [ 'en', 'fr', 'de', 'es', 'pt' ] default empty.

After setting up of multilingual settings and reboot uwsgi in the admin panel Smarty in the form of localizable fields will have the opportunity to indicate the name in additional languages.

For the server to Smarty in response to the request the API returned the value in the desired language, you must additionally pass a parameter lang. Read more in the documentation TVMiddleware API.

2.5. System team Smarty and configure crontab

Note

Attention! Some commands of the scheduler are required for the operation of the service.

2.5.2. Импорт EpgChannel

Team:

smarty_manage epg_channel_import --settings=settings.<settings name>

Данная команда поможет загрузить все каналы или обновить иконки из определенного источника. Для запуска обязательно необходимо указать epg_source_id или --epg_source_name.

Если команда вызывается для загрузки иконок или загрузки всех каналов из EpgChannelSource, то к загруженным иконкам по возможности будут созданы более маленькие копии следующих размеров: 500x500, 120x91 и 40x40.

Для источника обязательно должен существовать EpgChannelSource с указанием маски URL источника каналов. Для источников, у которых нет общего списка необходимо указывать epg_channel_id или channel_id.

Аргументы для запуска:

--epg_source_id
 Идентификатор EpgSource, для которого необходимо произвести импортирование каналов.
--epg_source_name
 Имя EpgSource, для которого необходимо произвести импортирование каналов.
--epg_channel_id
 Идентификатор EpgChannel, для которого необходимо произвести импортирование.
--channel_id Идентификатор Channel, для которого необходимо произвести импортирование.
--reimport_icons
 Если указан этот аргумент, то для всех импортированных каналов будет произведено обновление иконок.
--force_import Загрузка всех каналов из источника. Если указан данный аргумент то все аргументы кроме epg_source_id и epg_source_name будут проигнорированы.
--force_parser_handling
 Принудительно разрешает использовать передачу управления парсеру (равносильно TVMW_EPG_IMPORT_ALLOW_PARSER_HANDLING=True)
--force_disable_parser_handling
 Принудительно запрещает использовать передачу управления парсеру (равносильно TVMW_EPG_IMPORT_ALLOW_PARSER_HANDLING=False)
--fix_duplicates
 Удаляет дубликаты телеканалов с одним и тем же внешним идентификатором в рамках одного источника EPG.
--verbose Включает подробный вывод информации о загружаемых из источника иконках.

Использование опций –force_parser_handling и –force_disable_parser_handling приоритетнее параметра TVMW_EPG_IMPORT_ALLOW_PARSER_HANDLING.

Пример команды для повторного импортирования иконок для одного канала:

smarty_manage epg_channel_import –epg_source_id=1 –epg_channel_id=100 –reimport_icons –settings=settings.<settings name>

2.5.14. Команда кэширования существующих иконок

Team:

smarty_manage recache_icons --settings=settings.<settings name>

Вызывается в случае отсутствия информации о существующих иконках.

Команда проверяет и сохраняет в кэше существование иконок для всех EpgChannel по размерам, указанным в SMARTY_DEFAULT_ICON_SIZE и SMARTY_DEFAULT_ICON_SIZES.

2.5.19. Пример настройки crontab

For example:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
*/1 * * * *         python /usr/share/nginx/html/microimpuls/smarty/manage.py cache_channel_list --settings=settings.prod
0 5,9,13 * * *      python /usr/share/nginx/html/microimpuls/smarty/manage.py epg_import --settings=settings.prod
0 3 * * *           python /usr/share/nginx/html/microimpuls/smarty/manage.py clean_old_messages --days_count 3 --settings=settings.prod

2.5.20. Команда генерации видео для архивных записей

Team:

smarty_manage make_vodpvr --client_id=<client_id> --settings=settings.<settings name>

Выполняет создание видео для каждой программы, если для нее существует канал ведущий архивную запись. Отличается от контента

2.6. Start, restart and stop Smarty

For the process control application server uses uwsgi init script /etc/init.d/uwsgi:

$ /etc/init.d/uwsgi
Usage: /etc/init.d/uwsgi {start|stop|status|restart|reload|force-reload}

All commands operate on all running uwsgi instances.

The logs are stored by default in /var/log/uwsgi/, /var/log/nginx/ and /var/log/microimpuls/.

2.7. Install updates Smarty

Note

Before installing the service packs, please make a backup of the configuration files, Smarty, and database dump.

Updates are installed by a team dpkg:

dpkg -i smarty*.deb

After you install the update you need to install the new required python libraries using pip:

sudo pip install -r /usr/share/nginx/html/microimpuls/smarty/requirements.txt --ignore-installed

Migration of the database schema with the command:

python /usr/share/nginx/html/microimpuls/smarty/manage.py migrate --settings=settings.<settings filename>

Если в процессе установки пакета будет предложено заменить файл base.py - необходимо ответить Y (заменить файл).

After installing all the upgrade and migration of database schemas, you must restart the application server, uwsgi, complete all commands epg_import and cache_channel_list (via a call to kill), and then run a command to update the cache:

python /usr/share/nginx/html/microimpuls/smarty/manage.py flushall --settings=settings.<settings filename>

Note

If you do not run the command to update the cache flushall, then the cache may be the data from the old structure, which can lead to unpredictable errors in the applications.

2.7.1. Troubleshoot conflict migrations

During the migration of the database schema error may occur conflict migration: To fix them run 'python manage.py makemigrations --merge'. No need to make a team makemigrations. Error may occur in case of violation of correct procedure when installing or updating a system. To resolve this error, you must perform the following steps:

  • To remove the contents of the folder /tvmiddleware/migrations

  • To reinstall service pack smarty, which was installed at the time when the error occurred. Temporarily remove from the folder /tvmiddleware/migrations all available new migrations (creation date, which is newer than the date of the last successful update smarty).

  • Clear table django_migrations database in smarty.

  • Run the command:

    $ python manage.py migrate --fake --settings=settings.<settings filename>
    
  • Copy back the migration, is temporarily removed in step 2. Re-run the migration command:

    $ python manage.py migrate --settings=settings.<settings filename>
    

2.8. Scalability and fault tolerance

2.8.1. Available scaling and fault tolerance

Подробная информация о кластерных конфигурациях Smarty в новой базе знаний по продукту на сайте https://microimpuls.com/docs/smarty/scaling-and-redundancy.

2.8.2. Configure a connection to a DBMS using replication

Актуальная документация по настройке подключения к SQL-кластеру: https://microimpuls.com/docs/smarty/scaling-and-redundancy/smarty-sql-cluster-connection

2.8.3. Configure the logging of query statistics to statsd

statsd - server aggregate statistics: https://github.com/etsy/statsd.

Smarty allows you to upload a statsd statistics API requests (number of requests, response time, number of executed SQL queries, the response time of the DBMS). To do this, you must add the configuration file Smarty the parameters listed below:

MIDDLEWARE_CLASSES += (
    'core.middleware.StatsMiddleware',
)

STATSD_HOST = 'X.X.X.X'
STATSD_PORT = '8125'

Where:

STATSD_HOST str
The IP address of the statsd server to upload data for statistics and monitoring of servers with Smarty.
STATSD_PORT int
The port of the statsd server to upload data for statistics and monitoring of servers with Smarty.
STATSD_PREFIX str
The prefix that will be added (if used) to the key parameters that are passed to statsd.

Note

Внимание! Необходимо обеспечить доступность сервера statsd и правильность настроек подключения, в противном случае подключенная `core.middleware.StatsMiddleware` и отсутствие соединения со statsd может приводить к чрезмерному потреблению оперативной памяти.

3. Configure a service IPTV/OTT in Smarty

To configure the service available for two admin panel and the main service. The tool required to configure the General and basic entities, as well as edit any objects.

In the main pane configures the service IPTV/OTT operator-specific (Client ID).

Service http://smarty.example.com/admin
The main http://smarty.example.com

The service dashboard is available only for super admin (system administrator).

Note

Domain example.com sample only use your domain that is configured in the configuration file for nginx.

3.1. Initial configuration

3.1.1. Adding the Client ID and the ability to work in a “Multiprovider”

Note

You can skip this step if the command was executed setup_initial_data

The multiprovider is the ability to connect multiple projects or operators within the same system installation. For each project you will be using an independent set of settings, subscriber base, device settings, services, etc.

For operation of the system, you need to have created at least one Client ID. Under Client ID refers to the service provider or the project operator.

To create a Client ID is required in the service dashboard the link: http://smarty.example.com/admin/clients/client/

The fields are:

Name
The name of the operator or project.
E-Mail
E-mail to send system messages.
Subdomain
A subdomain name for customizing portals, for example provider.example.com.
Website address
The website address of the service.
API key
The API key for connecting subscriber devices.
Billing API key
The key API for script integration with external billing.
The default currency
The currency that will be selected when the payment for the services by the subscriber.
Payment method by default
The payment method will be chosen when paying for the services by the subscriber.
Maximum days trial safe
The limit for API requests to create accounts.
Number mask of the contract
Mask the formation of the contract number (see Documents).
The Mechanism For GeoIP
The mechanism used for geolocation (see configuring geo-location).
3.1.1.1. The binding of the subscriber device to the Client ID

For an application to bind the subscriber to a specific Client ID, use the API key (api_key) and client_id. These parameters must be set in the settings file client.js when configuring the portal, and when building native clients on the devices.

An API key is recommended to generate using pwgen utility key -s length less than 64 characters, e.g.:

pwgen -s 64

3.1.2. Adding templates portals

Note

You can skip this step if the command was executed setup_initial_data

In the service administration panel to add installed templates portals: http://smarty.example.com/admin/tvmiddleware/playdevicetemplate/

The name (path) of the standard templates: classic impuls iridium focus futuristic

3.1.3. Adding supported devices

Note

You can skip this step if the command was executed setup_initial_data

In the service administration panel, you add the supported device types: http://smarty.example.com/admin/tvmiddleware/playdevice/

The fields are:

Name
The name of the device type.
System name
System name device type, possible values see below.

Поддерживаемые типы устройств (системные названия):

android - под данным типом устройства распознается мобильный клиент под Android.

android_stb - Smart TV или STB под OS Android.

dune - STB Dune HD, начиная с модели Dune HD TV-101 и новее (модели PRO 4K, NEO 4K PLUS, NEO 4K T2 PLUS, SKY 4K PLUS работают под OS Android и относятся к типу устройства android_stb).

eltex - STB Eltex под OS Linux (NV-102).

tvip - STB Tvip.

lg_netcast - LG Smart TV под OS Netcast.

lg_webos - LG Smart TV под OS WebosTV.

mag - STB MAG.

pc - под данным типом устройства распознается ПК-клиент (не поддерживается на текущий момент).

sagemcom - STB Sagemcom.

samsung_smart_tv - Samsung Smart TV под Orsay (серии E, F, H).

tizen_tv - Samsung Smart TV под Tizen (серии J, K, M, Q, N, R).

ios - под данным типом устройства распознается мобильный клиент под iOS.

wrt- STB WRTech.

amino - STB Amino.

imaqliq - STB Imaqliq под OS Linux (G-box, Q-box). Модели под OS Android (Q-box Ultra) относятся к типу устройства android_stb

kodi - медиаплеер Kodi.

vewd - Smart TV, запускающие видео через HTML5-плеер (бывш. OperaTV). К таким телевизорам могут относиться устройства на платформах: Zeasn (Philips Smart TV), AmazonFireOS, Vewd и другие.

tbrowser - телевизоры TCL и те, которые используют внутренний движок tbrowser (Panasonic FSR400).

3.1.4. Connect allowed device types for Client ID

Note

You can skip this step if the command was executed setup_initial_data

In the service administration panel to add the permitted device types for each Client ID: http://smarty.example.com/admin/tvmiddleware/clientplaydevice/

3.1.5. Configure EPG and icons of TV channels

In the system there is a basic concept of the EPG Channel is a channel with attached icons and program guide. When you create the channel grid operator each channel corresponds to one of the basic channels. Thus, for channels operator fixed icon and TV guide (EPG).

The television program can be obtained from different sources, which are configured in the service dashboard: http://smarty.example.com/admin/tvmiddleware/epgsource/

The fields are:

The name of the source
The name to display.
The name of the parser module
The name must match the name of the class file parser in the folder /tvmiddleware/epg_parsers/.
Mask URL
By the provider EPG.

Existing parsers:

The name of the module Provider EPG
dummy_source Специальный источник EPG, который генерирует 60-минутные отбивки. Может использоваться, например, для каналов без EPG или для видеокамер с PVR. Маска URL: оставить пустым
yandex

http://tv.yandex.ru free access (the parser).

Mask URL: leave blank

epgservice

http://epgservice.ru, paid access, the XMLTV format.

Mask URL:

http://xmldata.epgservice.ru:8181/EPGService/hs/xmldata/<id>/file/%s

the <id> is the identifier of a service provided epgservice

xmltv_common

A universal parser for XMLTV.

URL mask: specify the source XMLTV

xmltv_from_file

The XMLTV parser-based file xmltv_common.

Mask URL: enter the path to the file on the server, Smarty

walla

http://walla.co.il free access (the parser).

Mask URL: leave blank

ucom

https://www.ucom.am/en/personal/home-services/u-tv/epg (parser)

Mask URL: leave blank

Configure EPG-channels is done in the service administration panel: http://smarty.example.com/admin/tvmiddleware/epgchannel/

The fields are:

Name
The name of the channel.
URL icons
Path to the icon, relative or absolute, starting with /tvmiddleware/media/.
The EPG source
The name of the source.
The channel ID in the EPG source
ID of the channel in the source.
Room for sorting
Position in the list is used for automatic sorting operator.
The shift in hours
The program shift in hours relative to UTC+0.

Icons default channel is located at the address /tvmiddleware/media/img/logo/default/.

The use of icons in several sizes

If the application requires icons of a certain size, then the server will issue the icons with the address <file name><width>_<height>.<extension>. For example, if the standard icon size is located at the address /tvmiddleware/media/img/logo/default/somelogo.png, icon size 400x400px - /tvmiddleware/media/img/logo/default/somelogo400_400.png.

The required icon sizes are passed by the application as arguments icon_width, icon_height in queries API TVMiddleware.

Note

The server does not check existence of icon file, incorrect size will lead to a results URL to a non-existent icon.

3.1.5.1. To add a new parser

To add your own EPG parser, you must create a module in Python in the folder /tvmiddleware/epg_parsers/ which should contain a class EpgParser inherited from EpgParserBase and implements all its methods and then create a record in the EPG Source.

3.1.5.2. Edit the EPG in manual mode

Edit the EPG is available in the service administration panel at: http://smarty.example.com/admin/tvmiddleware/epg/

3.1.5.3. Adding EPG-EPG categories and genres

Note

You can skip this step if the command was executed setup_initial_data

For detailed and easy content filtering and introduced the notion of EPG-EPG categories and genres - the data metrics are supplied by the provider EPG part of the description of each specific program. Thus, in addition to the category, the channel is also available to users category, and genre of any transfer of individually, which may not coincide with the theme of the channel.

Note

It is through the EPG categories and EPG-genres filtering works in the “screen TB of interests”.

Adding EPG-EPG categories-genres is done similarly, so below is presented the description of this process for categories.

1. В первую очередь создаются категории, которые в дальнейшем будут отображаться для абонентов в приложении: http://smarty.example.com/admin/tvmiddleware/epgcategory/

The fields are:

Category name
The name of the category.

2. Далее создается “карта отображения” созданных категорий, на те, что предоставляет источник EPG (список данных категорий запрашивается у поставщика EPG): http://smarty.example.com/admin/tvmiddleware/epgsourcecategorymap/

The fields are:

The EPG source
The name of the source.
The name of the category at the source
The name of the category in the form in which it gives the EPG source.
Category EPG
The name of one of the objects epgcategory that you have already created in admin panel in step 1 or created in the process.

Step 2 must be done for all the category names given by the source.

3.1.5.4. Добавление EPG-премьер

Помимо программы передач можно получить также программу премьер для указанного источника EPG. Программа премьер может быть получена из разных источников, которые настраиваются в служебной панели администрирования: http://smarty.example.com/admin/tvmiddleware/epgpremieresource/

The fields are:

Epg source
Источник, для каналов которого будут загружаться премьеры.
Адрес URL источника
Предоставляется поставщиком премьер.

3.2. Guide to working in the admin panel

3.2.1. General information about the administrative interface

Conventionally, the interface can be divided into two areas: a control panel and a data area.

The control panel has the following elements:

  • Links to sections in the settings — provides easy navigation through the interface.
  • Select the current operator in the framework of the function Multiprovider.
  • The choice of language button to switch language of interface (Russian and English).
  • User name — shows the name of the current user and allows you to exit the administrative interface, if you click on the user name in the list to select “Exit”.

The data area can look different depending on the current section.

3.2.2. A description of the interface

All settings of the administrative interface are thematically grouped in the menu on the control panel. Selecting any item displays a list of custom entities. If no item, then instead of a list I get a message saying that they are not found.

For lists you can sort, but only one column. It is available to sort columns have a lower point underlining their names.

_images/admin-guide-sort-columns.png

To sort the list simply click the column name. The first click sorts the list in ascending, the second descending, further clicks will alternate between these two ways of sorting. The ascending sort order is indicated by the up arrow next to the name column, and sort descending — down arrow.

_images/admin-guide-sort-asc.png

For some data uses a specific column sort Order. It sorts the elements not only in the administrative interface, but also defines the order of items in the interface on the device subscribers. In this column, each element of the list corresponds to the arrow icon. Depending on up or down directional arrow, clicking on it, the item will go up or down in the list respectively.

_images/admin-guide-sort-field.png

If the items list is large, it is split into pages. On one page is usually placed 25 records, but you can choose another value with 10, 50, 100, or 250, for this feature drop-down list at the bottom of the page.

_images/admin-guide-number-of-rows.png

When you select a new value the current page is updated, and depending on the number of pages displayed is either the same on the account page where you were required to change values, or the first nearest to her. Navigating between pages is done using the navigation bar with page numbers. Panel is 10 buttons with page numbers, the other buttons allow you to navigate between pages. So button < and > lead to the previous and next page, respectively. And buttons << and >> load the first and last pages, respectively.

_images/admin-guide-pagination.png

In almost all the sections available to search or filter data.

_images/admin-guide-search.png

To return from search results to the full list press Reset.

For almost all settings available to add/remove items. This feature provides the buttons Add, Change and Delete selected the above list.

_images/admin-guide-manage-buttons.png

When this button Change and Delete selected become active only after you select at least one item of the list.

To delete an entity, click Delete selected. After clicking Edit opens the edit page where you can change the values of the parameters.

_images/admin-guide-edit-form.png

Button Save changes saves the edits. Button back to the list without having saved any changes, just moves the user to the list of custom entities.

In some parts of the available summary statistics activity, for example in the accounts of the subscribers.

_images/admin-guide-active-status.png

Blue in these tables indicated the total number of records. Green indicates the number of records that have the selected: Active or ** or their status is Online, respectively, red color — the number of records that have not included the values of the Active or **. Gray — the number of records with a status of Offline.

3.2.3. An overview of the main sections

Панель администратора позволяет управлять настройками таких компонентов как:

  • The subscriber base
  • Packages and range of services
  • TV channels
  • TV guide (EPG)
  • Radio
  • Catalogue of the library
  • The application catalog
  • Streaming services (Live, VOD, PVR, etc.)
  • The device

For convenience settings are grouped in the menu on the main panel and is divided into categories:

  • General settings
  • Video servers
  • Monitoring
  • Settings streaming
  • Billing
  • Content settings
  • Subscribers
  • Reports

To start working with the settings you should select in the drop-down list of categories. Each setting is a list whose elements you can add/delete and change the values of their parameters, which allows you to configure the various components.

3.2.4. Section: General settings

3.2.4.1. STB settings and applications

This section contains a list of devices to view the IPTV service (STB Set-Top Box, Smart TV, mobile device, computer, etc.) supported by the operator (see allowed to Connect the operator device types).

Here you specify the basic settings for communication with the service.

To edit the device settings, you can click Settings, either click on the name of the device.

3.2.4.1.1 Рекомендации по заполнению блока “Логотип оператора”

Логотип для главного меню - используется во всех шаблонах, кроме infinitly и мобильного приложения, рекомендуемые размеры:

  • futuristic (STB&TV) - 178x48 пикселей
  • impuls (STB&TV) - 311х123 пикселя
  • classic (STB&TV) - 206x74 пикселя

Логотип для страницы авторизации - используется только в шаблоне classic, рекомендуемый размер: 140х174 пикселя

Логотип для стартовой страницы - используется только в шаблоне classic, рекомендуемый размер: 178х140 пикселей

3.2.4.2 Локализация уведомлений

Данный раздел позволяет локализовать имена транзакций, уведомления биллинга, отображаемые для абонента, а также имена ценовых категорий для контента.

Локализация уведомлений доступна для всех настроенных языков Smarty.

3.2.4.3 Правовые документы

Данный раздел позволяет создавать/настраивать/удалять правовые документы для абонентов, такие как: оферта, политика конфиденциальности, правила пользования сервисом и другие.

Отображение и акцепт правовых документов доступен не во всех шаблонах клиентских приложений.

3.2.4.4. Настройка прав пользователей

In this section, administrators can edit permissions of other administrators or moderators of the service to limit their access to certain sections or functionality.

Adding new users is done in the service administration panel to: http://smarty.example.com/admin/users/user/.

Access rights are divided into groups according to topic categories, in the admin panel. Detailed rights to perform certain actions with the data consist of:

  • Can view … - has access to view information
  • Can create … - has access to create items
  • Can edit … - has access to edit
  • *Can delete … * has access to delete
3.2.4.5 Провайдеры HbbTV

Раздел позволяет настраивать интеграцию с HBB TV провайдерами. На текущий момент интегрированы 2 провайдера: Teletarget и GetShopTV. Для получения ключей и URL-адресов необходимо обращаться к самим провайдерам напрямую.

После настройки провайдеров в данном разделе появится возможность задать показ интерактивов от конкретного провайдера для конкретных каналов. HbbTV ID совпадает с UID клиента на странице “Общие настройки Client”.

Отображение HbbTV-интерактивов доступно не на всех устройствах и не во всех шаблонах клиентских приложений.

3.2.4.6. Виджеты для интеграции с сайтом

In this section, you configure widgets to integrate your website with the IPTV service. Read more about the mechanism installation of modules in the.

The following types of widgets:

  • Channel list - a list of TV channels grouped by tariff packages and search capability.
  • Registration sign - up page by e-mail and SMS.
  • Account page - a personal account of subscriber, which is used to connect/disconnect packages, payment, profile editing etc.
  • EPG program the program on all connected channels.

3.2.5. Section: Setup streaming

3.2.5.1. Data centers

Under the data center means a physical or host server group, or virtual group streaming services. Used for service aggregation and routing on the basis of preferred geographic or any other relationship accounts for different services.

3.2.5.2. Streaming services

Streaming services are the servers, broadcasting, and video processing. The range of settings varies depending on the type of the selected streaming services, however, the parameters in blocks Basic settings are common to all.

3.2.5.2.1. Dynamic and static routing

If for TV, film or other content unit is set to an active streaming services and not asked a direct URI of the stream, we will use dynamic routing. At the time of treatment set-top box to the corresponding content is searched from one of connected streaming services based on content type, tariff packages, as well as accessibility and loading service. Then, based on the settings of a streaming service, forming a content URL, the mask or after the calculating of the script.

When static routing content URL is generated when forming the playlist. This type of routing can be used for streams without authorization, the Multicast streams for IPTV or external Unicast streams partners.

3.2.5.2.2. Dynamic routing is specified by the script

The script allows you to create custom routing logic. The language used is Python. The result of the script must be defined variable uri containing the URL of the video stream.

Example script:

def get_random_proxy(datacenter):
    if datacenter == 4:
        proxies = [
            {
                'ip': '1.1.1.1', 'port': 8181,
                'key': 'DrRSwkrMudmsYb0K'
            },
            {
                'ip': '2.2.2.2', 'port': 8181,
                'key': 'DrRSwkrMudmsYb0K'
            },
            {
                'ip': '3.3.3.3', 'port': 8181,
                'key': 'DrRSwkrMudmsYb0K'
            }
        ]
    else:
        return 0
    return random.choice(proxies)

uri = 'http://1.2.3.4:8080/%s/?s=DeZcC2A0OkjLwlBb' % prefix

proxy = get_random_proxy(adid)
if proxy:
    uri = 'http://%s:%d/%s/%s' % (proxy['ip'], proxy['port'], proxy['key'], uri.replace('http://', ''))

Above is an example of the script in which the URL of the video stream sets the first mask, and then, if the account is set to a specific data center (id = 4 in the example), then it randomly selects one of the proxy servers, then the URL is replaced with the proxy.

3.2.5.3. Technical work

The technical work used to partially restrict access to the service when necessary. For example, in a given time period, while under maintenance or accident, subscribers may be prevented from viewing recorded programs.

3.2.6. Section: Billing

3.2.6.1. Packages

Section allows you to manage the list of tariff packages and their settings. Cm. the possibility of billing.

3.2.6.3. Financial transactions

Section contains information about the movement of funds on accounts of the subscribers.

Data can be added manually or automatically in case of use billing (see Scenarios of interaction with a billing system). If you use an external billing system, to retrieve a list of transactions in this section, you must synchronize using API Billing.

Search here is a filter as one parameter, and multiple at once:

_images/admin-guide-transactions-filter.png

Also available report export transactions to a CSV file:

_images/admin-guide-transactions-export.png

3.2.7. Section: content Settings

3.2.7.1. Categories: TV

Use this section to add categories TV channels. Each channel must belong to the given category. In the customer application, depending on the template, but as a rule, there is the ability to display TV channels in a certain category to facilitate the search for the desired content.

3.2.7.2. Channels

This is one of the main sections to configure a service IPTV/OTT. Here is the configuration list of the channels that broadcasts the operator and configuration of their broadcast and display.

In addition to manually setting the channel order by using the fields sort Order the list of channels can be automatically set sorting to be used on the user device, using the methods from list Auto-sort, which is located above the rest of the control buttons:

Automatically
Sorting is carried out by button number of channels that are specified in the Room for sorting when configuring the EPG-channels, see configure EPG. When using Microimpuls Middleware as a platform from company “Microimpulse” within the service “Virtual operator” this method sorts the channels according to the signed license agreements between OOO “Microimpulse” and copyright holders and the law.
ID
When you add a channel in the list is assigned the ID, the sorting is done according to this parameter.
The title
Sorting is done by name of the channel.
Custom sorting
If you apply one of the previous sorting, selecting this item will return to the original manual sorting operator.
3.2.7.3. TV program

Section allows you to view the EPG for all channels, as well as to clear and force to primordiality EPG for individual channels.

Channel selection is done in the left menu. To clean the TV program, click Clear EPG, import - Forced to import EPG.

Note

Automatic import is configured through the scheduler, see the customize run commands in crontab.

Advanced editing EPG service available in the admin panel, see Edit EPG in manual mode.

3.2.7.4. Genres and categories of VOD

In this section you can add/delete and edit genres for movies provided on the service Video-On-Demand.

The genres displayed in the user interface on a client device, selecting a menu item corresponding to this service. As well to determine the order in which genres are displayed on the subscriber’s device used a column sort Order.

3.2.7.5. Movies

In this section you manage the catalog of movies and video files.

In the list of movies is the button Assets, when clicked, will open a section for editing assets (files) related to this video. One video can have multiple assets, select the specific asset available for playback to the caller when you view the movie details on your device.

Please note that in order to return to the original list of assets video library, click back to list, which is located above the list.

3.2.7.6. Radio

In this section you can edit the list of radio stations.

3.2.7.7. Commercials

Use this section to add commercials, which can then be formed in Ad units (see below).

Note

Support for this functionality is not available in all devices and it is dependent on the subscription application.

3.2.7.8. Ad units

In this section, you will add ad units, consisting of a sequence of rollers.

3.2.7.9. The application directory

In this section you can manage the directory of the external applications available to the subscriber device to the portal, in addition to the basic IPTV service. An external application can be, for example, Youtube player, online chat, weather forecast or traffic, games and other services. The application is a Web-page using Javascript.

Типы приложений:

  • Web-приложение во внешнем окне - любой URL, открывающийся в браузере устройства. Особенность данного вида приложения заключается в том, что не на всех устройствах после его открытия можно вернуться обратно в родительское приложение.

  • Web-приложение во внутреннем окне - данный тип приложения используется для собственных виджетов оператора, написанных специально для абонентского портала Justify. Для разработки такого приложения можно воспользоваться документацией: http://mi-justify-dev-docs.readthedocs.io/

  • Ссылка на раздел видеотеки - при создании данного типа виджета в приложении появится ещё одна ссылка на открытие видеотеки (в главном меню или в списке сервисов, в зависимости от настройки виджета).

  • Воспроизведение потока по ссылке - воспроизведение любого потока по ссылке, указанной в поле “URL / Название / ID приложения”.

  • Виджет - в приложение будет добавлен внутренний виджет, разработанный специально для шаблона. Виджеты для шаблона futuristic:

    • Прогноз погоды
      • Системное название: WeatherWidget
      • url: /templates/futuristic/default/apps/weather-widget/weather.widget.js
      • Атрибуты:
        • city__NUM__name: название города
        • city__NUM__id: идентификатор города в источнике, заданном в конфиге Smarty
        • city__NUM__ext_id: внешний идентификатор города (из источника погоды)
        • auto_detect_current_city: флаг, при передаче которого город по-умолчанию для виджета будет определяться по геолокации, принимает значения 0 или 1
        • show_current_city_name: флаг, при передаче которого в виджете будет отображено название текущего выбранного города
    • Курс валют
      • Системное название: ExchangeWidget
      • url: /templates/futuristic/default/apps/exchange-widget/exchange.widget.js
    • Телеканал
      • Системное название: TVChannelWidget
      • url: /templates/futuristic/default/apps/tvchannel-widget/tvchannel.widget.js
      • Атрибуты:
        • number: номер канала по порядку в Smarty
    • Баннер
      • Системное название: PromoImageWidget
      • url: /templates/futuristic/default/apps/promo-image-widget/promo.image.widget.js
      • Атрибуты:
        • image_url: адрес превью-картинки баннера
        • big_image_url: адрес полноэкранной картинки баннера
        • refresh_interval: интервал для обновления картинки с сервера (в секундах)
    • Новости
      • Системное название: NewsWidget
      • url: /templates/futuristic/default/apps/news-widget/news.widget.js
      • Атрибуты:
        • rss_url: адрес RSS-ленты
    • Баннер-ссылка
      • Системное название: LinkImageWidget
      • url: /templates/futuristic/default/apps/link-image-widget/link.image.widget.js
      • Атрибуты:
        • image_url: адрес превью-картинки баннера
        • link_url: адрес ссылки, открывающийся при запуске виджета
    • Поиск
      • Системное название: SearchWidget
      • url: /templates/futuristic/default/apps/search-widget/search.widget.js
    • Промо фильма
      • Системное название: PromoVodWidget
      • url: /templates/futuristic/default/apps/promo-vod-widget/promo.vod.widget.js
      • Атрибуты:
        • items__NUM__id: идентификатор фильма/подписки в Smarty
        • items__NUM__content_type: тип контента, значения: 0 - фильм, 1 - подписка
        • items__NUM__content_name: название контента
        • items__NUM__trailer_url: url потока трейлера фильма, который запустится при нажатии на виджет
        • items__NUM__preview_url: url превью-картинки
    • Промо канала
      • Системное название: PromoStreamWidget
      • url: /templates/futuristic/default/apps/promo-stream-widget/promo.stream.widget.js
      • Атрибуты:
        • items__NUM__trailer_url: url потока трейлера канала, который запустится при нажатии на виджет
        • items__NUM__preview_url: url превью-картинки
    • ТВ Премьеры
      • Системное название: PremieresWidget
      • url: /templates/futuristic/default/apps/premieres-widget/premieres.widget.js

Виджеты для шаблона impuls:

  • Тест скорости (корректная работа гарантирована на tvip, redbox, tizen_tv, прочие устройства в работе)
    • Системное название: SpeedTestWidget
    • url: /templates/impuls/default/apps/speedtest-widget/speedtest.widget.js
    • Атрибуты:
      • speedtest_server_url: url сервера, до которого измеряется скорость (на сервере должны находиться дополнительные файлы для корректной работы виджета, выдаются по запросу)
  • Экран настроек Android - виджет, который при запуске открывает системные настройки Android

  • Меню приложений Android - виджет, который при запуске открывает системное меню приложений Android

  • Запуск приложения Android по AppId - виджет, открывающий заданное системное или установленное приложение Android. Для данного виджета в поле “URL / Название / ID приложения” задается системное имя приложения, которое можно узнать несколькими способами:

    • на некоторых версиях Android его можно узнать, открыв: Настройки -> Приложения -> Интересующее приложение
    • если приложение было скачано из Google Play, идентификатор можно посмотреть в строке браузера:
    _images/service-configuration-android-app-id.png
    • если оба способа выше не подходят/не помогли, то можно установить специальное приложение Package Name Viewer, благодаря которому появится возможность просмотреть идентификатор всех установленных приложений.
  • Ссылка на раздел ТВ - при создании данного типа виджета в приложении появится ещё одна ссылка на открытие меню ТВ (в главном меню или в списке сервисов, в зависимости от настройки виджета).

  • Запуск системного приложения по ID - аналог виджета “Запуск приложения Android по AppId”, но предназначенный для других устройств с возможностью запуска внешних приложений. На данный момент такая возможность доступна на приставках Tvip (идентификаторы приложений можно посмотреть в официальной документации Tvip https://wiki.tvip.ru/stb/system_uri ), телевизорах Samsung Smart TV 2015-2019 годов выпуска и приставках Imaqliq (идентификаторы youtube и youtube_kids).

3.2.8. Section: Subscribers

3.2.8.1. Subscribers

The section is the institution of the subscribers. In the list of subscribers there are three special columns: Accounts, Payments, and Messages - they contain references to the relevant associated with the subscriber sections.

When you click on the name of the subscriber opens the customer page and edit its settings.

3.2.8.2. Accounts

This section is the establishment of the subscribers ‘ accounts. When you click on the account number open a card account, where you can also edit its parameters.

3.2.8.3. The device

This section displays the list of registered devices of subscribers. Information about the devices added to the system automatically on first connection of the subscriber, but also allowed manual addition of devices.

3.2.8.4. Сообщения и команды

In this section you can create a newsletter on subscriber devices. These messages can be added either manually from the dashboard interface and added automatically by the system, for example when you receive a payment from your personal account, or connecting/disconnecting the tariff package, or when approaching the end date of the subscription.

Note

In most subscriber applications Microimpuls incoming messages are implemented as pop-UPS.

Warning

Mobile and native applications may not support HTML formatting.

3.2.8.4.1. Bulk mail

Tool Mass mailing allows you to create messaging groups, which can be chosen according to several criteria:

  • The last activity accounts - allows you to select subscribers who used the service in a given period.
  • Packages - allows you to select packages, in this case, the sample will get subscribers, which is connected to the selected tariff packages.

When you use mass mailing in the subject and message text can contain variables that are automatically replaced by their value at the time of message creation: $firstname - the name of the person $lastname - the name of the subscriber.

3.2.8.5. Действия абонентов

В этой вкладке у администратора Smarty есть возможность проследить действия абонентов, такие как: изменение пароля, обновление данных профиля, подключение/отключение тарифов и так далее. Помимо действий также указывается их источник - виджет для интеграции с сайтом или приложение (TVMW API).

Для того, чтобы данный раздел стал доступен, необходимо включить опцию TVMIDDLEWARE_CUSTOMER_LOG_ENABLED.

3.2.8.6. Дилеры

Dealers are the partners who can provide services and interact with subscribers on behalf of the operator. In this section you enter information about the dealers, a set of fields and the structure of the section is similar to the page Subscribers.

Separately to cost to pay attention to the field username and Password - these data are needed to create an account, dealer in admin panel Smarty. This account has limited privileges and does not have access to some features, but allows you to create users and accounts, thus connecting them to the service.

Created the subscriber accounts are automatically linked to dealer.

3.2.9. Раздел: Мониторинг

Актуальная документация: https://microimpuls.com/docs/smarty/admin-guide/monitoring

3.3. General features of the services and accounts in Smarty

Актуальная информация об особенностях работы встроенного биллинга в Smarty в базе знаний продукта на сайте https://microimpuls.com/docs/smarty/external-billing-integration/about-internal-billing

4. Logging Smarty

4.1. Logs Smarty

Entries in the logs are as follows:

%(timestamp)% %(log level)% %(module)%:%(code line number)% %(function)%[%(pid)%.%(thread id)%] %(message text)%

The message (message text) consists of the name of events and additional context.

An example entry in the log:

Fri Mar 24 10:22:35+0300 2017 DEBUG api:621 get[83630.Thread-3] SOME_EVENT 'ip'='127.0.0.1' args=['foo', 'bar']

In this example:

Fri
day of the week
Mar
a month
24
date
10:22:35
local time in timezone specified in settings.py in the constant TIME_ZONE
+0300
the offset relative to UTC
2017
year
DEBUG
the level of logging
api:621
the file name and line number
get[83630.Thread-3]
the name of the function, the pid and the name of the thread
SOME_EVENT
event name
ip and args
additional context

The level of logging westvlaamse in the project settings(smarty/settings/settings_<local>.py). For example, to set the INFO level to log api requests, you must add the following code:

LOGGING['handlers']['smarty_api_requests_handler']['level'] = "INFO"

Events depending on type are grouped in different files. By default, logs are stored at the address /var/log/microimpuls/smarty/.

4.1.1. smarty_main - main log

Types of events:

URLS_INITIALIZED

Smarty configuration initialized. Occurs during the application start, additional context:

  • available_apps - available modules
Events that are unprocessed other loggers

Occurs during the error, you need to contact the developer to solve.

Additional context: local variables of the function in which the error occurred.

4.1.2. smarty_accounts - log subscribers

Types of events:

LOGIN_SUCCESS

A successful authorization, the context:

  • login_type - type login (multilogin, basic device, additional equipment)
  • login_method - the method login (and password pass only pass only the UID of the device)
  • params - the query parameters
LOGIN_ERROR

Authorization error, context:

  • reason - the cause of the error:
    • account_does_not_exist account there is no subscription or password is invalid or device_uid
    • account_is_not_active account is not active
    • client_does_not_exist - invalid api_key or client_id
    • basic_device_sessions_limit - exceeded session limit on the base unit
    • account_deivce_invalid - such a basic device already exists
    • external_api_error - request error to the external system (e.g. external billing)
    • unknown_error - unknown error (accompanied by stacktrace’ohms)
  • params - the query parameters
ACCOUNT_DEVICE_ERROR

Error when creating a device account context:

  • account - account
  • device - device
  • device_uid - the UID of the device
  • client - operator
ACCOUNT_ACTIVATED

Account has been activated, the context:

  • activation_result - the answer returned by the external system
  • params - the query parameters
ACCOUNT_CREATED

Create account context:

  • account_id - the account ID
ACCOUNT_CHANGED

Change the account context:

  • account_id - the account ID
  • changed fields
ACCOUNT_TARIFFS_ASSIGNED

Adding tariffs account context:

  • account_id - the account ID
  • tariffs_ids - the list of IDs of the connected tariffs
ACCOUNT_TARIFFS_REMOVED

The removal of tariffs to the account context:

  • account_id - the account ID
  • tariffs_ids - the list of IDs of deleted rates
CUSTOMER_CREATED

Create subscriber context:

  • customer_id caller ID
CUSTOMER_CHANGED

The change of the subscriber context:

  • customer_id caller ID
  • changed fields
CUSTOMER_TARIFFS_ASSIGNED

Adding tariffs to the subscriber, the context:

  • customer_id caller ID
  • tariffs_ids - the list of IDs of the connected tariffs
CUSTOMER_TARIFFS_REMOVED

The removal of tariffs subscriber context:

  • customer_id caller ID
  • tariffs_ids - the list of IDs of deleted rates
ACCOUNT_DEVICE_REMOVED

Delete the device account context:

  • account_id - the account ID
  • device_uid - the device ID

4.1.3. smarty_billing_out requests to external systems

INIT_ERROR

Error initializing API handler, context:

  • kwargs - the arguments passed in the handler class
  • api_client_class - the class name of the handler API
  • stacktrace
CUSTOMER_BALANCE_REQUEST_ERROR

Error balance inquiry, context:

  • api_client_class - the class name of the handler API
  • params - the query parameters
  • stacktrace
CUSTOMER_BALANCE_REQUEST_SUCCESS

A successful balance inquiry, context:

  • api_client_class - the class name of the handler API
  • params - the query parameters
  • result - the result of the query
CUSTOMER_PAYMENT_LIST_REQUEST_ERROR

Error when requesting list of transactions that context:

  • api_client_class - the class name of the handler API
  • params - the query parameters
  • stacktrace
CUSTOMER_PAYMENT_LIST_REQUEST_SUCCESS

A successful list request transaction context:

  • api_client_class - the class name of the handler API
  • params - the query parameters
  • result - the query result
VIDEO_ACTIONS_LIST_REQUEST_ERROR

Error query options with the video context:

  • api_client_class - the class name of the handler API
  • params - the query parameters
  • stacktrace
VIDEO_ACTIONS_LIST_REQUEST_SUCCESS

A successful query options with the video context:

  • api_client_class - the class name of the handler API
  • params - the query parameters
  • result - the query result
VIDEO_ACTION_REQUEST_ERROR

Error when trying to perform an action with the video context:

  • api_client_class - the class name of the handler API
  • params - the query parameters
  • stacktrace
VIDEO_ACTION_REQUEST_SUCCESS

Successful action with the video context:

  • api_client_class - the class name of the handler API
  • params - the query parameters
  • result - the query result

4.1.4. smarty_billing_in incoming requests to the Billing API

BILLING_REQUEST_ERROR

Error when querying the Billing API context:

  • url - URL method, which made the request
  • the ip - the IP address from which the request proizvodite
  • args - arguments of the request
  • error_message - error message
  • ``”error” `` - error code
BILLING_REQUEST_SUCCESS

A successful request to the billing system, the context:

  • url - URL method, which made the request
  • the ip - the IP address from which the request proizvodite
  • args - arguments of the request

4.1.5. smarty_cache events related to caching

OBJECT_CACHED

Cached object, context:

  • object - cached object
  • timeout - the time after which the object will be removed from the cache
  • key key object in the cache
  • deps - objects, changing of which the cached object should be invalizilor
OBJECT_INVALIDATED

Invalizilor object, context:

  • object - the object that was removed from the cache
  • deps_key - the key of the object, where the keys of related objects, which must also be Invalidovna

4.1.6. smarty_messaging - log sent messages for accounts

MESSAGE_CREATED

Created message context:

  • account - the account to which the message was sent
  • subject - the subject of the message
  • text - the message text
MESSAGE_SEND

The message was sent, the context:

  • account - the account to which the message was sent
  • subject - the subject of the message
  • text - the message text
  • uuid - the message ID
MESSAGE_DELETED

Message deleted, additional context:

  • account - the account to which the message was sent
  • subject - the subject of the message
  • text - the message text
  • uuid - the message ID

4.1.7. smarty_management - log periodic commands

MANAGEMENT_COMMAND_SUCCESS

Successful execution of the command, additional context:

  • command - the team name
  • execution_time - run time
MANAGEMENT_COMMAND_ERROR

Error executing the command for more context:

  • command - the team name
  • stacktrace

4.1.8. smarty_epg - log import EPG

EPG_CHANNEL_IMPORTED

Programs for channel imported successfully, more context:

  • epg_channel - channel
  • source - the EPG source
  • programs_imported - the number of imported programmes
EPG_CHANNEL_IMPORT_ERROR

Error when importing programs, additional context:

  • epg_channel - channel
  • source - the EPG source
  • stacktrace
EPG_IMPORT_FINISHED

Import programs are completed, additional context:

  • channels_processed - the number of processed channels
  • programms_imported - the number of imported programmes
EPG_REMOVED

In the course of parsing have been removed the old entry for more context:

  • epg_channel - channel
  • source - the epg source
  • removed_objects - deleted objects
EPG_TIME_OVERLAP

The end time of the previous program start time of the current, more context:

  • epg_channel - channel
  • source - the epg source
  • program_name - the name of the program
  • previous_program_name - the name of the previous program
  • program_time_begin - the start time of the current program
  • previous_time_end - the end time of the previous program
EPG_TIME_HOLE

The end time of the previous program start time less the current, more context:

  • epg_channel - channel
  • source - the epg source
  • program_name - the name of the program
  • previous_program_name - the name of the previous program
  • program_time_begin - the start time of the current program
  • previous_time_end - the end time of the previous program
EPG_NAME_DOUBLE

The name of the current program coincides with the previous one, the additional context:

  • epg_channel - channel
  • source - the epg source
  • program_name - the name of the program

4.1.9. smarty_content_requests - requests for links to/addresses of the stream using TVMW API

CONTENT_REQUEST_FAIL

Has encountered an unhandled error in the request process, you must contact the developer.

Additional context:

  • url - URL method, which made the request
  • params - the query parameters
  • stacktrace
CONTENT_REQUEST_ERROR

Processed error in the request process, additional context:

  • url - URL method, which made the request
  • params - the query parameters

Possible causes:

  • invalid request parameters
  • legacy authorization key
  • request to ustravel data (for example, trying to play too old transfer from archive)
CONTENT_REQUEST_SUCCESS

A successful query, link the received additional context:

  • url - URL method, which made the request
  • params - the query parameters
  • additional information, including the address of the thread (depending on method)
CLIENT_CHANNELS_NOT_FOUND

Not found in the cache channels for a given Client ID may have been reset cache or an error occurred executing the command cache_channel_list, additional context:

  • client - Client ID

4.1.10. smarty_portal - log events portal

PORTAL_EVENT

The event in the portal additional context:

  • event_description - the event description
  • the ip - the IP address of the device of the subscriber
  • device_uid - the device ID
  • screen_name - title screen
  • user_agent - User-Agent device

4.1.11. smarty_stream_services - log-streaming-services

STREAM_SERVICE_CHECKING_ERROR

Error checking of availability of the streaming service, for more context:

  • stream_service - streaming service
  • was_available_before - indicates whether a streaming service available earlier
  • check_ping_success - was a successful test of ping (optional)
  • check_tcp_success- whether successful verification attempt to open socket (optional)
  • check_http_success - whether successful verification attempt to access the URL (optional)
  • check_is_alive_success - whether successful test is_alive (optional)
  • stacktrace
STREAM_SERVICE_CHECKING_SUCCESS

Successful checking of availability of the streaming service, for more context:

  • stream_service - streaming service
  • was_available_before - indicates whether a streaming service available earlier
  • check_ping_success - the ping test was successful (optional)
  • check_tcp_success- check the attempt to open the socket was successful (optional)
  • check_http_success - check by trying to open a URL was successful (optional)
  • check_is_alive_success - check is_alive was successful (optional)

4.1.12. smarty_admin - log admin panel Smarty

ADMIN_REQUEST

Query the administration interface, additional context:

  • user - the user who typed the query
  • the ip - the IP of the consumers
  • path - the request path
  • user_agent - User-Agent browser

4.1.13. smarty_videoservices - log of requests to video

VIDEOSERVICES_REQUEST

The user’s query in Smarty to run the command:

  • the ip - the IP of the consumers
  • user_agent - User-Agent browser
  • user - the user who typed the query
  • path - the request path
VIDEOSERVICES_API_REQUEST

The Smarty request to the video service:

  • the host - the type and address of video service
  • args - arguments of the request
  • command - the called method
  • message - the server’s response (only if error)

4.1.14. smarty_payment - лог оплаты

NOTIFY_ERROR

Ошибка обработки сообщения нотификации, дополнительный контекст:

  • client - ID клиента в платёжном шлюзе.
  • transaction - ID транзакции.
  • payment_source - название платёжного шлюза.
  • params - параметры запроса.
  • error - описание ошибки.

Возможные причины ошибки:

  • Неверная настройка платёжного шлюза.
  • Передача неверных параметров платёжному шлюзу.
  • Платёж не прошёл.
NOTIFY_SUCCESS

Успешная нотификация, дополнительный контекст:

  • client - ID клиента в платёжном шлюзе.
  • transaction - ID транзакции.
  • payment_source - название платёжного шлюза.
  • params - параметры запроса.
PAYTURE_REQUEST

Запрос к платёжному шлюзу Payture:

  • url - URL API Payture, на который выполняется запрос.
  • args - аргументы запроса.
  • response - ответ от API в виде XML.

5. Smarty integration with external systems and services

5.1. API для разработчиков

Актуальная документация по API-методам в базе знаний продукта на сайте: https://microimpuls.com/docs/smarty/extra/api

5.1.1. Примеры кода

Note

See also other additional tools:

5.2. Интеграция с биллинговой системой

Актуальная документация о возможностях интеграции с внешним биллингом оператора в базе знаний продукта на сайте https://microimpuls.com/docs/smarty/external-billing-integration

5.3. Embedding modules in the website

Актуальная документация по интеграции виджетов на сайт: https://microimpuls.com/docs/smarty/extra-services-integration/site-widgets

5.4. Integration with popular video-servers

5.4.1. Integration with Astra

To integrate the authentication mechanism of video streams (streaming) with Astra is a mechanism for generating one-time tokens for the links to the stream on the server side Smarty. Astra at the time of parsing HTTP Request from the subscriber device selects a token and checks it on the server, the Smarty validity.

Для генерации токена необходимо в маске URL стриминг-сервиса в Smarty добавить переменную $token в маску URL, например:

http://streamer.example.com:8080/mychannel/?token=$token

5.4.2. Интеграция с Flussonic

Для интеграции механизма авторизации видеопотоков (стриминг-сервисов) с Flussonic используется механизм генерации одноразовых токенов для ссылок на поток на стороне сервера Smarty. Flussonic в момент разбора HTTP Request от абонентского устройства выделяет токен и проверяет его на сервере Smarty на валидность.

Для генерации токена необходимо в маске URL стриминг-сервиса в Smarty добавить переменную $token в маску URL, например:

http://streamer.example.com:8080/mychannel/?token=$token

На стороне Flussonic необходимо настроить авторизационный бекенд, указав адрес API-метода StreamServiceTokenCheck на стороне Smarty:

auth_backend main {
    backend https://smarty.example.com/tvmiddleware/api/streamservice/token/check/;
}

и в свойствах канала прописать параметр auth:

stream example {
    url hls://example.com/channel/index.m3u8;
    title "Channel Name";
    auth auth://main;
}
5.4.2.1. Настройка маски URL для архивных записей

Для корректной работы функционала постановки Live-трансляций на паузу и перемотки назад из Live необходимо использовать следующий шаблон URL:

http://<host>/$cid/video-$flpbt-$flpdur.m3u8?token=$token

5.5. Integration with online cinemas

5.5.1. Integration with MEGOGO

Smarty contains a module for integration with online cinema MEGOGO <http://megogo.net>`_, which includes the following functionality:

  • Sync movies MEGOGO with built-in video library Smarty (title, description, genre, cover, etc.)
  • The subscription model (SVOD)
  • The model of purchasing individual movies and series (TVOD)
  • All the standard functions built-in video library Smarty (search, filtering, sorting, grouping by genre, etc.)
  • Transparent integration in standard applications Microimpuls on different devices - a single interface for viewing live TV and VOD and other services familiar to the subscriber
5.5.1.1. Configuration of the module megogo

To connect integration MEGOGO need to do the following steps:

  • Connect module megogo Smarty configuration in the section of INSTALLED_APPS, restart Smarty and migrate data.
  • Create a hidden tariff package that will be used for the access of subscribers to the catalog and purchase TVOD or SVOD subscription. This subscription package will automatically be enabled for all imported films in order to be visible in the directory.
  • To create a tariff package that will be used for subscription movies. When buying SVOD-subscription this package will connect to the subscriber in Smarty, and if you disable the package will be unsubscribing from the SVOD package.
  • In the admin panel under “General settings” -> “API Integration with external systems” to create a new external system:
    • specify the name (for example, MEGOGO)
    • choose from the drop down list class API megogo_api_client
    • choose the tariff package that you created in the second step. Subscribers who have connected to this tariff package will see the videos and be able to buy them (on a subscription or transactional, depending on the settings of the film in MEGOGO)
  • To specify additional attributes of the external system:
    • mobile_private_key - the private key for mobile devices (available MEGOGO)
    • mobile_public_key - the public key for mobile devices (available MEGOGO)
    • smart_tv_private_key - the private key for Smart TV (available MEGOGO)
    • smart_tv_public_key - the public key for Smart TV (available MEGOGO)
    • stb_private_key - the private key for STB (available MEGOGO)
    • stb_public_key - the public key for STB (available MEGOGO)
    • partner_id - the partner ID (provided MEGOGO)
    • salt - the key used to generate authorization request to billing (available MEGOGO)
    • svod_service_id - the identifiers of the SVOD service, which is used for processing of the service user (provided MEGOGO)
    • available_tvod_collection_id - the ID of the collection to get available TVOD-objects (available MEGOGO)
    • tariff_id - the identifier of the tariff package that you created in step 3 which will be connected to the subscriber when activating the subscription. The connectivity of this package means you subscribe to a corresponding package of SVOD in MEGOGO. If you disable this package, the subscriber/account is in Smarty, the method will be called automatically unsubscribe from SVOD in MEGOGO.
    • additional_tariffs_ids - IDs mixed tariff packages (unifying channels and subscription MEGOGO), separated by commas. When you connect one of these rates will be added to the subscription MEGOGO as well as for tariff_id. If you disable all of these packages will be unsubscribing from MEGOGO as well as for tariff_id.
    • ignore_customer_balance_check - при значении 1 при покупке контента не будет проверяться баланс абонента. Необходимо при интеграции покупок с внешней биллинговой системой оператора.
    • typhoid_comment_category_id - идентификатор жанра-категории, присваиваемый фильму, если он является фильмом с тифлокомментариями. Если данный атрибут указан и фильм имеет тифлокомментарии, то другие категории для него указаны не будут.
    • sign_language_category_id - идентификатор жанра-категории, присваиваемый фильму, если он является фильмом с сурдопереводом. Если данный атрибут указан и фильм имеет сурдоперевод, то другие категории для него указаны не будут.

After completing all the steps required to synchronize mirrored via miracast ™ with the help of management team:

python manage.py megogo_sync_content --settings=settings.<settings filename>

Первая синхронизация может занять около получаса в связи со скачиванием обложек, последующие синхронизации проходят быстрее. Для регулярной синхронизации фильмов необходимо добавить вызов команды в crontab. Помимо синхронизации фильмов эта команда также создает подборки контента из базы MEGOGO для импортированных фильмов.

Для команды megogo_sync_content можно указать флаг --load_actor_info для загрузки данных об актёрах со стороны сервиса MEGOGO, однако это потребует больше времени для синхронизации.

After the first synchronization will be created go to the movies MEGOGO. Then you can follow final steps:

During a subsequent synchronization of the films will be binding genres.

Note

For buying movies available in TVOD, each key must be connected to the service side MEGOGO.

5.5.2. Интеграция с tvzavr (deprecated)

Note

Кинотеатр tvzavr более недоступен в рамках Smarty по причине его официального закрытия.

Smarty contains a module for integration with online cinema tvzavr <http://tvzavr.ru>`_, which includes the following functionality:

  • Sync movies and TV series tvzavr.ru with built-in video library Smarty (title, description, genre, cover, etc.)
  • The subscription model (SVOD)
  • All the standard functions built-in video library Smarty (search, filtering, sorting, grouping by genre, etc.)
  • Transparent integration in standard applications Microimpuls on different devices - a single interface for viewing live TV and VOD and other services familiar to the subscriber
5.5.2.1. Configuration of the module tvzavr

To connect integration tvzavr need to do the following steps:

  • Connect module tvzavr Smarty configuration in the section of INSTALLED_APPS, restart Smarty and migrate data.
  • Create a hidden tariff package that will be used for the access of subscribers to the SVOD catalogue. This subscription package will automatically be enabled for all imported films in order to be visible in the directory.
  • To create a tariff package that will be used for subscription movies. When buying SVOD-subscription this package will connect to the subscriber in Smarty, and if you disable the package will be unsubscribing from the SVOD package.
  • In the admin panel under “General settings” -> “API Integration with external systems” to create a new external system:
    • specify the name (for example, tvzavr)
    • choose from the drop down list class API tvzavr_api_client
    • choose the tariff package that you created in the second step. Subscribers who have connected to this tariff package will see the videos and be able to purchase them.
  • To specify additional attributes of the external system:
    • tvzavr_tariff_id - the value of this parameter gives tvzavr
    • plf - the value of this parameter gives tvzavr
    • secret - the value of this parameter gives tvzavr
    • subscription_tariff_id - the identifier of the tariff package that you created in step 3 which will be connected to the subscriber when activating the subscription. The connectivity of this package means you subscribe to a corresponding package of SVOD in tvzavr. If you disable this package, the subscriber/account is in Smarty, the method will be called automatically unsubscribe from SVOD in tvzavr.

After completing all the steps required to synchronize mirrored via miracast ™ with the help of management team:

python manage.py tvzavr_sync_content --settings=settings.<settings filename>

The first synchronization can take up to an hour in connection with the download of the skins, subsequent syncs are faster. For regular sync of movies, you must add the command to crontab.

After the first synchronization will be created go to the movies tvzavr. Then you can follow final steps:

During a subsequent synchronization of the films will be binding genres.

Note

For to order the subscription was renewed on the server side, tvzavr, you must also schedule a select team check_accounts.

5.5.3. Интеграция со Start

Актуальная документация: https://micro.im/docs/smarty/external-vod-integration/start

5.5.3. Интеграция со PREMIER

Актуальная документация: https://micro.im/docs/smarty/external-vod-integration/premier

5.6. Integration with CAS CMS

Smarty supports integration with certain systems CAS model unified management system subscriptions with portal applications and customers for set-top boxes and other devices support operation with any CAS that are supported by a specific device.

5.6.1. Integration with Irdeto

Integration settings are specified in the configuration file Smarty:

IRDETO_NATIONALITY str
Default value: ‘ENG’
IRDETO_REGION_TAG str
Default value: ‘MO’
IRDETO_HOST str
Server address Irdeto with the SOAP API, by default ‘http://127.0.0.1:80

5.7 Интеграция с платежными системами

Актуальная документация: https://microimpuls.com/docs/smarty/payments-integration

5.7.1. Интеграция с Payture

Актуальная документация: https://microimpuls.com/docs/smarty/payments-integration/payture

5.8. Дополнительные инструменты

The script is smarty data migration between databases on client_id
https://github.com/microimpuls/admin-tools/tree/master/smarty_migrate_tool
The migration script with the OFT Middleware Middleware Microimpuls
https://github.com/microimpuls/admin-tools/tree/master/oft_db_migrate_tool
The migration script accounts and MAC addresses with Billing in the Hydra Middleware Microimpuls
https://github.com/microimpuls/admin-tools/tree/master/hydra_migrate
Script to bulk create accounts through the Billing API
https://github.com/microimpuls/admin-tools/tree/master/mass_customer_creator

Note

Other useful scripts and utilities, see Microimpuls repository on Github: https://github.com/microimpuls/admin-tools

6. Install and configure portal for STB and Smart TV

The portal is a set of Javascript (JS/HTML/CSS) in different stylistic and functional options (templates), which is a shell (interface) for a user. The portal is loaded to built-in device (set-top box or Smart TV) browser.

6.1. Installing portal

Since the portal is a static file that does not require the application server support any scripting, hosting any web server. Also, if necessary, the portal can be hosted on a CDN service, or embedded in the firmware of the device.

With Smarty the portal server communicates over HTTP API, through the implementation of XMLHttpRequest requests.

For hosting the portal, use the web server nginx.

The portal settings are specified in the file client.js hosted in the root directory. For ease of deployment and administration client.js is usually that on the specific provider config, located in the /etc/microimpuls/portal/.

Note

Because of the restriction policy implementation crossdomain requests on some devices it is recommended to query to Smarty to use the same domain that hosts the portal. In the standard nginx configuration for the portal that comes with the installation package of the portal, provides special location /api performing a redirect to Smarty.

6.2. Configuration options client.js

In the config client.js are defined as key parameters (for example, the information to connect to Smarty) and specific for each application (template).

Required parameters

Актуальная документация по обязательным параметрам: https://microimpuls.com/docs/smarty/portal-and-apps-settings/portal-settings

Additional options

Актуальная документация по дополнительным параметрам: https://microimpuls.com/docs/smarty/portal-and-apps-settings/portal-settings

Specific template parameters

Актуальная документация по дополнительным параметрам шаблона impuls: https://microimpuls.com/docs/smarty/portal-and-apps-settings/impuls-settings

Актуальная документация по дополнительным параметрам шаблона focus: https://microimpuls.com/docs/smarty/portal-and-apps-settings/focus-settings

Актуальная документация по дополнительным параметрам шаблона futuristic: https://microimpuls.com/docs/smarty/portal-and-apps-settings/futuristic-settings

Актуальная документация по дополнительным параметрам шаблона infinitly: https://microimpuls.com/docs/smarty/portal-and-apps-settings/infinitly-settings

6.3. The event mechanism

Events allow you to add or override some functionality of the portal at different points in its life cycle. Event handlers are defined in the config client.js that allows you to save custom settings and functions even if you upgrade the portal to new version.

Available events:

  • OnDataRequestError - error running query to Smarty as argument - error code
  • OnAppInitBegin - start application initialization
  • OnAppInitEnd - completion of application initialization
  • OnDeviceInitBegin - start initialization of the device driver
  • OnDeviceInitEnd - completion of initialization of the device driver
  • OnDeviceKeyEvent event keypress of the remote, as the argument is the keycode
  • OnAccountLoginSuccessful successful authorization of the account

Life cycle: OnAppInitBegin > OnDeviceInitBegin > OnDeviceInitEnd > OnAppInitEnd.

Example of creating event handlers is shown below.

Note

Attention! The use of this mechanism requires programming skills in Javascript, knowledge of architecture and API portal and API devices.

6.4. Example configuration

The example below is for template impuls and in addition to the default behavior adds an additional item in the settings menu of the subscriber - “standby Mode” that enables or disables the event handling connect/disconnect HDMI cable on MAG, and also checks the firmware version and runs the update if necessary when starting the application, and adds some other functions.

var CLIENT_SETTINGS = {
    'client_id': 1,
    'api_key': '***',
    'api_url': '/api',
    'template_name': 'impuls',
    'template_size': {
        'impuls': {
            'default': [1280, 720]
        },
        'classic': {
            'default': [1280, 720],
            '720x576': [720, 576]
        },
    },
    'available_templates': ['futuristic'],
    'template_styles': {
        'futuristic': ['futuristic', 'futuristic_x']
    },
    'settings_filename': 'example.dat',
    'site_url': 'www.example.com',
    'signup_auto_activation_period': 0,
    'show_welcome_message': false,1
    'registration_available': false,
    'settings_menu_custom_items': [
        'handle-hdmi-events'
    ],
    'auth_mode': 'device_uid',
    'default_timezone': 12,
    'default_buffersize': 3,
};

OnAppInitBegin = function()
{
    // Автоматическое выключение плеера ночью в 01:30 по локальному времени
    setInterval(function(){
        var date = new Date();
        if (date.getHours() == 1 && date.getMinutes() == 30) {
            App.player.stop();
            App.display.showScreen('tvchannels');
        }
    }, 35000);

    // Обновление прошивки для определенных старых версий
    try {
        var fver = parseInt(gSTB.RDir('ImageVersion'));
        var desc = gSTB.GetDeviceImageDesc();
        if (desc == 'default-214') {
            stbUpdate.startAutoUpdate("http://update.example.com/imageupdate", true);
        }
    } catch (e) {}
};

OnAppInitEnd = function()
{
    // Подключение custom css верстки
    var el = document.createElement('link');
    el.rel = 'stylesheet';
    el.type = 'text/css';
    el.href = '/custom/css/custom.css';
    document.getElementsByTagName('body')[0].appendChild(el);

    // Подключение режима overscan для шаблона impuls
    Helper.addBodyClass('overscan');

    // Переопределение кнопки EPG на красную кнопку
    App.playerScreen.key_epg = App.playerScreen.key_red;
    App.tvChannelsScreen.key_epg = App.tvChannelsScreen.key_red;

    // Переопределение обработчика кнопки Power
    App.display.setGlobalKeyCodeHandler('power', function(){
        App.player.stop();
        App.display.showScreen('mainmenu');
    }, App.playerScreen);
};

OnDeviceInitBegin = function()
{
    // Добавление меню настройки режима ожидания
    var handleHdmiEventsMenu = new BaseMenu({
        menuTag: 'ul',
        itemIdPrefix: 'settings-handle-hdmi-events-value',
        useItemIdWithoutIndex: true,
        itemTag: 'span',
        displayItemsNumber: 1,
        sourceItemsNumber: 2,
        useFastRefresh: false,
        getItemNameFunc: function(sourceItemIndex, displayItemIndex) {
            var names = [
                'Отключен',
                'Включен'
            ];
            return names[sourceItemIndex];
        }
    });
    App.settings.setCustomSetting('handle-hdmi-events', 1);
    App.lang.set('ru', 'label-settings-handle-hdmi-events', 'Режим ожидания');
    App.settingsScreen.addCustomSettingsMenu('handle-hdmi-events', handleHdmiEventsMenu);
};

OnDeviceInitEnd = function()
{
    // Установка произвольной прозрачности интерфейса
    App.device.setWindowTransparencyLevel(230);

    // Установка режима 16:9 по умолчанию
    App.device.setAspectRatioMode('16:9');

    // Обработка событий HDMI для MAG
    if (App.device.getDeviceKind() === 'mag') {
        App.device.standBy = false;
        App.device.standByTimer = null;
        App.device.onEvent = function(code) {
            switch (code) {
                default:
                    break;
                case 0x20: // HDMI connected
                    if (Helper.toInt(App.settings.getCustomSetting('handle-hdmi-events')) == 1) {
                        clearTimeout(App.device.standByTimer);
                        if (App.device.standBy) {
                            App.device.stb.StandBy(false);
                            App.device.standBy = false;
                        }
                    }
                    break;
                case 0x21: // HDMI disconnected
                    if (Helper.toInt(App.settings.getCustomSetting('handle-hdmi-events')) == 1) {
                        clearTimeout(App.device.standByTimer);
                        App.device.standByTimer = setTimeout(function () {
                            if (!App.device.standBy) {
                                if (App.player.isActive()) {
                                    App.player.stop();
                                    App.display.showScreen('tvchannels');
                                }
                                App.device.stb.StandBy(true);
                                App.device.standBy = true;
                            }
                        }, 60 * 5 * 1000);
                    }
                    break;
            }
        }
    }
};

OnAccountLoginSuccessful = function()
{
    // Изменение формата отображения оставшихся дней активации на dd/mm/yyyy
    var value = App.data.getActivationDaysLeft();
    if (parseInt(value) <= 0) {
        value = App.lang.get('auto-renewal');
    } else {
        var d = new Date(new Date().getTime()+(parseInt(value)*24*60*60*1000));
        var dd = d.getDate();
        var mm = d.getMonth() + 1;
        var y = d.getFullYear();
        value = dd + '/' + mm + '/' + y;
    }
    Helper.setHtml('info-menu-activation-days-left', value);
};

6.5 Кастомизация стилей оформления портала

Smarty позволяет для каждого устройства задать внешний css-файл для кастомного оформления портала, например, установить своё фоновое изображение, сменить цвет шрифта или фокуса.

Для этого необходимо открыть в панели администрирования “Общие настройки” -> “Настройки STB и приложений” -> <устройство для настройки> и прописать в поле “Внешний CSS” путь до файла с новыми стилями. Как правило, данный файл располагают на том же веб-сервере, что и портал.

Для создания файла с внешними стилями достаточно с помощью отладчика любого браузера проследить какие классы и идентификаторы отвечают за тот или иной элемент экрана в портале, после чего перезаписать/дописать нужные свойства к ним. Ниже представлены самые часто встречающиеся примеры кастомизации для шаблонов futuristic и impuls.

Пример внешнего css-файла для кастомизации шаблона futuristic.

/* Установка кастомного фонового изображения */

.screen, .android_stb .screen {
    background: url('example-bg.jpg') no-repeat;
}

/* Установка кастомного фонового изображения для верхней панели с лого оператора */

#statusbar-screen {
    background: transparent url('statusbar-bg.png') no-repeat;
}

/* Установка кастомного изображения для фокуса главного меню  */

div#main-menu-selection {
    background: transparent url('example-selection-bg.png') no-repeat center 0px;
}

/* Установка кастомного шрифта */

@font-face {
    font-family: 'Nunito';
    src: url('../fonts/Nunito/nunito-v12-latin_cyrillic.eot');
    src: url('../fonts/Nunito/nunito-v12-latin_cyrillic.eot?#iefix') format('embedded-opentype'),
    url('../fonts/Nunito/nunito-v12-latin_cyrillic.woff2') format('woff2'),
    url('../fonts/Nunito/nunito-v12-latin_cyrillic.woff') format('woff'),
    url('../fonts/Nunito/nunito-v12-latin_cyrillic.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

body {
    font-family: "Nunito", "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}

Пример внешнего css-файла для кастомизации шаблона impuls.

/* Установка кастомного лоадера */

.screen-container.loader, #player-mode-icon.loader, #loading-bar {
    background: transparent url("loader-example.gif") center center no-repeat;
}

#firstloading-loader {
    background: url('loader-example.gif') no-repeat;
    height: 65px;
    width: 120px;
}

.loader#video-actions-panel {
    background: transparent url("loader-example.gif") center left no-repeat;
    height: 120px;
}

/* Установка кастомного фонового изображения */

.screen, body, .play .screen, .png-transparency .screen, .play.png-transparency .screen,
.transparent.png-transparency .screen, .transparent .screen {
    background: url('example-bg.jpg') no-repeat;
}

body.play {
    background: transparent;
}

/* Установка кастомных координат для логотипа оператора */

.client-logo {
    margin-top: 75px !important;
    margin-right: 30px;
}

Note

Нужно учесть, что для корректной работы внешних стилей, необходимо, чтобы все дополнительные ресурсы (изображения, шрифты), используемые в них, были доступны и имели правильные пути.

Note

После установки обновлений шаблонов необходимо внимательно читать changelog и тщательно тестировать портал на предмет корректности работы внешнего CSS, так как внутренние css- и html-файлы могут претерпевать изменения, что так или иначе влияет на отображение кастомных стилей.

A. problem solving and recommendations

The company “Microimpulse” provides professional technical support on projects, including administration and server configuration, Smarty, portals, management systems database, and customize data replication, load balancing, caching, redundancy and more.

Detailed information on the cost of technical support can be obtained from your Manager.

In addition, to ask a question or find a solution to a particular problem in the technical community http://forum.micro.im

A. 1. Problems with the server Middleware, and associated systems and solutions

Not displayed list of TV channels on the subscriber’s device

Possible causes and solutions:

  • For a subscriber/account no installed packages containing the required set of channels and streaming services.
  • The composition is connected for a subscriber/account tariff packages not found any available streaming service.
  • Cache the list of channels is empty, you must run the command cache_channel_list, see Caching channel list.
  • After installing the update is not performed flushall that led to damage of the cache. Cm. in Install updates Smarty.

In the application of the subscriber errors occur and/or when you turn on the console an error occurs, the authorization

Possible causes and solutions:

  • After installing the update is not performed flushall that led to damage of the cache. Cm. in Install updates Smarty.
  • If you are using a single Redis server and directory to save the dump over the place, this can lead to errors “MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk”. You need to release free space and disable the option stop-writes-on-bgsave-error, see configure caching.

In the TV program on the subscriber’s device does not display the icons of the availability of recorded shows

Problem: when enabled and configured the PVR service subscriber is unavailable switch gears from the record.

Possible causes and solutions:

  • For a subscriber/account is not selected tariff package that contains the appropriate and accessible streaming service.
  • Created technical work affecting the operation of the service, see Technical work.

High CPU load on the MongoDB server

Problem: the CPU consumption on the server MongoDB close to 100% across all cores, and reports are not available in viewership.

Possible causes and solutions:

During the installation of the update Smarty arose a surge load on the server, Middleware and DBMS

Possible causes and solutions:

  • If you upgrade the scheduler has been running the import command EPG, try to execute the command flushall could lead to invalidation conflict of interest, since one process creates them, and the other invalidates. This can result in the mass invalidation of objects in the cache. To prevent such a situation when you install the update you must complete a background command epg_import and cache_channel_list. Cm. in Install updates Smarty.

At a mass number of subscribers there is an increased load on the CPU and it does not decrease

Possible causes and solutions:

  • Not enough workarou uwsgi or nginx. It is necessary to conduct the optimal configuration of the application server and web server in accordance with General guidelines under high load.
  • Insufficient RAM or CPU. Cm. in System requirements. A temporary solution might be to enable nginx cache, it is necessary for the most frequent queries to use the handler @cached in the nginx configuration, for example:
location /tvmiddleware/api/channel/list/ {
  try_files $uri @cached;
}
location /tvmiddleware/api/program/list/ {
  try_files $uri @cached;
}

Periodically there splek network load on the Middleware server

Possible causes and solutions:

  • Enabled “Enable auto-refresh the data without restarting the device” device settings (see Settings STB and widgets). If this load is undesirable, you should disable opico. Then a full list of TV channels and EPG will not be performed.
  • If an incorrect network or the virtualization could be a situation the retention of packets in queues, when queue release may lead to a surge of requests, and as a result a surge of traffic. You need to troubleshoot network problems and provide fast data transfer.

Some pages of the admin panel open with a significant delay also delays operation of devices

Possible causes and solutions:

Application server, uwsgi is not loaded, Smarty is not available

Possible causes and solutions:

  • No write permissions for user www-data directory to /var/log/microimpuls or /var/log/microimpuls/smarty. You must allow writing to these directories.
  • Another reason - see the logs /var/log/uwsgi/.

The import command stops epg_import EPG, EPG is not imported from the admin panel

Possible causes and solutions:

  • No write permissions in /usr/share/nginx/html/microimpuls/smarty/media. You must assign user and group www-data to the smarty directory, perform the command: chown-R www-data:www-data /usr/share/nginx/html/microimpuls.
  • Another reason - see the logs /var/log/microimpuls/smarty/smarty_epg.log.

In the application the subscriber is not displayed icons of television and picture transmission

Possible causes and solutions:

  • Incorrect option value MEDIA_BASE_URL (see description of the main parameters) or incorrectly configured nginx. For debugging, you must open the portal in the browser and using symfony developer tools (e.g. Firebug) to track requests for pictures.

In the application of the subscriber after some time, get off the clock and EPG

Possible causes and solutions:

  • If the device is used to synchronize time with NTP when the connection with the NTP server time may deteriorate. It is necessary to ensure proper operation and accessibility of the NTP server. Time on the Middleware server must also be synchronized with the time on the server PVR.

Not working the servers MicroTS, errors occur in the interaction Smarty video servers Microimpuls

Problem: monitoring data is collected, the monitoring does not appear transcoding streams, tasks, records etc.

Possible causes and solutions:

  • The port of the JSON-RPC API of the respective service unavailable server Smarty. It is necessary to ensure their availability.
  • Installed wrong version of package python-jsonrpctcp. You need to install the package from the repository Microimpuls, see Installing Smarty and modules.

A third party application that uses TVMiddleware API, can’t access from another domain due to CORS policy

Possible causes and solutions:

  • In the config file of Smarty you need to set the CORS exception for that domain in the options CORS_ORIGIN_WHITELIST, then in the HTTP headers for requests from that domain will be granted the necessary permissions. Example: CORS_ORIGIN_WHITELIST = ( ‘example.com’, )

Do not load the cover art and movie description from IMDb

Possible causes and solutions:

  • If you frequently use the function to download information from IMDb in the admin panel, the IP address of the server Smarty can be blocked by the system of protection against bots Either. To resolve this problem, it is necessary to reduce the activity of the queries or contact technical support service Kinopoisk.

Медленно обрабатываются запросы к Billing API, медленно сохраняются изменения в панели администратора при редактировании тяжелых объектов

Possible causes and solutions:

  • При длительной работе Smarty накапливает много данных в кэше для быстрой работы приложений. При редактировании данных администратором, при обработке API-запросов от биллинга может возникнуть необходимость инвалидации данных по большому числу связанных объектов, что вызывает длительную работу сервера для обработки такого запроса. Чтобы данные операции производились в фоновом режиме и не тормозили работу необходимо включить поддержку потоков, установив опцию enable-threads в значение true в файле конфигурации uwsgi, после чего перезапустить uwsgi.

A. 2. Recommendations

Recommended kernel parameters

Changes you need to make the file /etc/sysctl.conf:

kernel.shmmax = 2473822720
kernel.shmall = 4097152000
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_default = 8388608
net.core.wmem_max = 16777216
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_tw_reuse = 0
net.ipv4.tcp_keepalive_time = 10
net.ipv4.tcp_fin_timeout = 5

Then run the command to apply the changes:

sysctl -p

B. Additional materials

B.1. cx_Oracle driver installation on Debian and an example of Smarty to Oracle connection setup

  1. Install the package oracle-instantclient11.2-basic.

    When installing on Debian you need to convert the rpm package provided by Oracle into deb package using the utility alien:

    alien oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm
    dpkg -i oracle-instantclient11.2-basic_11.2.0.4.0-2_amd64.deb
    
  2. Install the package oracle-instantclient11.2-devel:

    alien oracle-instantclient11.2-devel-11.2.0.4.0-1.x86_64.rpm
    dpkg -i oracle-instantclient11.2-devel_11.2.0.4.0-2_amd64.deb
    
  3. Install the package oracle-instantclient11.2-sqlplus:

    alien oracle-instantclient11.2-sqlplus-11.2.0.4.0-1.x86_64.rpm
    dpkg -i oracle-instantclient11.2-sqlplus_11.2.0.4.0-2_amd64.deb
    
  4. Install the python module cx_Oracle:

    pip install cx_Oracle
    
  5. Install libaio1:

    apt-get install libaio1 libaio-dev
    

B.1.1. Smarty to Oracle connection setup

This is needed to be written into the database connection settings section of the Smarty configuration file:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.oracle',
        'NAME': "smarty",
        'USER': "smarty", # Имя схемы/пользователя
        'PASSWORD': "password", # Пароль пользователя
        'HOST': "10.0.0.10", # Адрес сервера Oracle
        'PORT': '1521',
        'OPTIONS': {
            'threaded': True,
            'use_returning_into': False,
        },
        'CONN_MAX_AGE': 600,
    }
}

B.2. Настройка подключения Smarty к PostgreSQL

This is needed to be written into the database connection settings section of the Smarty configuration file:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'smarty',
        'HOST': 'localhost',
    }
}

Параметр Host является обязательным. Также для PostgreSQL появляется новая зависимость: psycopg2. Устанавливается через pip:

pip install psycopg2-binary