Triggers

From Memento Database Wiki
Revision as of 14:26, 20 September 2016 by UnConnoisseur (talk | contribs)
Jump to navigation Jump to search
« Page as of 2016-09-09, editions Mobile 4.0.0, Desktop 1.0.5 »

This page is incomplete, incorrect, in the midst of translation, and under development.

A Trigger is a script that initiates certain actions or events. Trigger scripts are written in JavaScript. When a trigger script is executed, it may change an existing entry, create a new entry, execute an http request, create a file, perform data validation, etc.

Creating a trigger

Each library can have any number of triggers. To see the list of triggers, open the library, open the menu, and then select Triggers.

To create a trigger, open the library's list of triggers and click +. You must then define the event and write a trigger script that performs the necessary action.

Event that initiates execution of the trigger

The launch of the trigger is defined by two parameters:

Action
is any action preformed by the user on an entry.
Phase of an action
a subdivision, or specific step, of an action. A trigger can be fired during a phase of an action. Each action type can have a different set of phases.

Script execution

The phase that activates the trigger also defines how the trigger will be executed — synchronously or asynchronously.

Synchronous script execution
implies the application suspends user interaction and executes the script. It is not recommended to perform time-consuming operations in this case.
Asynchronous script execution
results in the script running in the background; user interaction is not suspended. Usually, asynchronous scripts are used in the last phases of the action.

Security

Since the scripts have access to more actions than a user does, they require additional permissions.

The user must define these permissions manually for each library.

To open the dialog to set permissions for scripts — open library triggers list and click Shield on the toolbar. Permissions must be set separately on each device. Permissions are not synchronized between devices.

Permissions for scripts

Library permissions
determines which other libraries can be affected by the script. You can grant access to all libraries or select only certain libraries. This authorization is required for the libByName function.
Read permissions
grants the script read access to a file
Write permissions
grants the script write access to a file
Network
grants to the script the right to execute http requests

Actions

Act Phase Performance
Creating an entry opening forms creation synchronous
before saving the recording synchronous
After the record is saved asynchronous
Changing the recording opening notation changes synchronous
before saving the recording synchronous
After the record is saved asynchronous
Deleting entries before deleting records synchronous
after the removal of records asynchronous
Opening the Recording card in front of the window display synchronous
after the window display asynchronous
Adding entries to Favorites before the operation synchronous
after operation asynchronous
Deleting an entry from shortlist before the operation synchronous
after operation asynchronous

Library and Entry

Global Functions

entry()

Get an entry in the context of which the script was going on. Those. if the script is running on action Change the recording, this function returns the variable record.
access function for all actions and implementation phases, with the exception of "Creating a file - opening form creation," for this activity, use the function entryDefault.
Result: Object Entry, the current record.

entryDefault()

Get the object for the default values ​​are not created record yet. This feature is available for action Creating an entry and execution phaseOpening a form of creation.
Result: The object DefaultEntry.

lib()

Get a library in the context of which the script was going on.
Result: Object Library, the current library.

libByName(name)

Find the library named. In the security settings must be set to authorize the use of library.
Result: Object Library, found a library.

Object Library

Through this object provides access to library records. You can work with the current library - the lib () or to any other library database - libByName () . In addition to the functions of receiving records this object provides the ability to create a new record.

Methods

entries()
Get all the recording library.
Result: Array [Entry] array of records. Entries are sorted by time of their creation - from newest to oldest.
find(query)
Search for entries in the library field values. Search similar search through the interface of the program.
Parameters: query — the search string.
Result: Array [Entry] array of records found. Entries are sorted by time of their creation - from newest to oldest.
findByKey(name)
Records search by the name of the library. For the library must be enabled for unique names.
Parameters: name — the name of the recording.
Result: Object Entry.
create(values)
Creating a new entry in the library.
Parameters: values ​​- an object of class Object containing the field values.
Result: Object Entry, create an entry.

Properties

Title
The name of the library

Object Entry

This place is a record library and provides the ability to get and set field values.

Methods

set(name, value)
Set the value of the field. After calling once there is a record value in the database.
Parameters: name — the name of the field, value — the value of the field
field(name)
Get the value of a field
Parameters
name — the name of the field
Result
The value of the field type of the result depends on the type of field.

Properties

Title
Account name
Description
Description recording
Favorites
Returns true — if the record is in Favorites
Deleted
Returns true — if the record is deleted (it is in the basket)

Object DefaultEntry

Template with default values for a new record.

Methods

set(name, value)
Set the value of the field.
Parameters: name — the name of the field, value — the value of the field.

Examples

Data Validation

Using scripts, you can check the correctness of input data. For example, for a field integer values ​​are allowed only from 0 to 200.

var num = entry().field("Number")
if (num < 0 || num > 200) {
 message("Wrong range");
 cancel();
}
  1. We get the value of the field Number
  2. Tests for values ​​matching the allowable range
  3. If the value is out of range then display a message Wrong range
  4. Cancels the operation

This script should be used for the action Create recording or change the recording and phase before saving .

Set default values

If the standard tools can not be set to the desired value of the field by default, it can be done through a script.

Previous value of another field

There is a library containing the records of the daily running of the car, bicycle or your walks. The library has StartingMileage field and Mileage.When you create a record is required in the field StartMileage enter data from the field Mileage previous record.

var entries = lib().entries();
if (entries.length > 0) {
prevMileage = entries[0].field("Mileage");
entryDefault().set("StartMileage" , prevMileage )
}
  1. Get the current library the lib () and a list of entries it records ().
  2. Check that the list is not empty entries, otherwise stop the script, so we do not have a previous record.
  3. Records list is sorted from newest to oldest, respectively, the previous record is at the beginning of the list with an index value of 0. Get the Mileage field from the previous record.
  4. We set the value of the field Mileage from the previous record as the default value for the field StartMileage.

The script must be set for action Creating and recording phase opening of the form.

Beginning the next day

If you want the date/time field when creating a record, set the beginning of the next day, it can make the following script. For the script, you must connect the JavaScript-library moment.js moment.js

var m = moment().add(1,'d')
m.hour(8).minute(0)
entryDefault().set("Date" , m.toDate().getTime())
  1. With the moment () function library moment.js obtain the current time and add 1 day.
  2. Set time of 8 hours and 0 minutes.
  3. Write a default value for the field Date.

The script must be set for action Creating a record and phase Opening a form.

Working with files

With scripts you can read or write files located in the device's internal memory or on the SD card. All file operations performed by the File object, which is obtained through a method call file().

To work with the files for the library to be set to a resolution - on the reading and / or writing files.

Global Functions

file(name)

Open a file for read or write operations.

Parameters:

Name
The name and the full path to the file.
For example, if the file is located on the SD card, the path should look /sdcard/example.txt.
Result
Object file

Object File

This object is returned file () function and provide access to the requested file. If the file specified in the file () function name does not exist yet, but it will be created. After a read or write the file should be closed function close ().

Methods

readAll()
Reads all lines of the file, and then closes the file.
readLine()
Read a line.
readLines()
Read the remaining lines in the file and return them in an array.
readChar()
Read a character.
write(text)
Write strings. This function takes a variable number of arguments, converts each argument to a string, and writes that string to the file.
writeLine(text)
Write strings and a newline.
close()
Close the file. It may be reopened.

Свойства

exists
true - if and only if the file denoted by this object exists; false otherwise
length
The length, in bytes, of the file denoted by this object, or 0L if the file does not exist.
getLineNumber
Get the current line number.

Examples

Writing & reading from a file

f= file("/sdcard/myfile.txt")
file.writeLine("one");                       
file.writeLine("two");
file.writeLine("three");
file.close();     
var a = file.readLines();
  1. Open myfile.txt file on the sdcard. If the file does not exist, it is created.
  2. Write the file into a string "one"
  1. Close the file, only then saved the file.
  2. Read the file from all the rows, the result is an array of strings to a.

Save a file to a record

Необходимо сохранить запись в формате xml. Запись имеет следующие поля: id , title , date.

var xml = '<record id="' + entry().field("id") + '">' + 
'<title>' + entry().field("title") + '</title>' +
'<date>' + entry().field("date") + '</date>' +
'</record>';
f= file("/sdcard/" + entry().field("title") + ".xml");
f.write(xml);
f.close();
  1. Формируем xml данные из значений полей для записи в файл.
  1. Открываем файл, имя файла будет таким же как и имя записи.
  2. Сохраняем в файл xml-данные
  3. Закрываем файл

Выполнение http запросов

С помощью скриптов можно выполнять http-запросы, что позволяет обмениваться информацией с веб-службами предоставляющими API. Также через http запросы вы можете интегрировать Memento со своей системой. Все операции с файлами производятся через объект Http, который получается через вызов глобального метода http().

Http запросы доступны при соблюдении двух условий:

  1. Выполнение скрипта должно быть асинхронным (фоновым), так как обработка запроса по сети может занимать много времени. Таким образом выполнять http-запросы можно только в последних фазах действий.
  2. В библиотеки должно быть установлено разрешение - Network.

Объект Http

Интерфейс выполнения http запросов.

Методы

get(url)
Выполнить get запрос.
Параметры: url - http адрес, должен начинаться с http или https
Результат: HttpResult - объект содержащий результат выполнения http запроса.

Объект HttpResult

Результат выполнения http запроса

Свойства

code
http код ответа, если запрос выполнен успешно, то он обычно равен 200.
body
тело ответа в виде текста.

Примеры

Конвертация валюты

Библиотека содержит два поля PriceUSD и PriceEUR. Пользователь заполняет только поле PriceUSD, требуется чтобы в поле PriceEUR записывалась цена в евро по текущему курсу. Создадим триггер на действие Создание записи, фаза выполнения будет После сохранения.

result = http().get("http://api.fixer.io/latest?base=USD")
usdToEur = JSON.parse(result.body)["rates"]["Eur"] 
entry().set("PriceEUR" , entry().field( "PriceUSD") * usdToEur )
  1. Для получения курсов валют пользуемся сервисом http://fixer.io/. Сервис по запросу http://api.fixer.io/latest?base=USD возвращает курсы валют в JSON формате.
  2. Воспользуется стандартным JavaScript объектом JSON чтобы распарсить ответ.
  3. Умножаем цену из поля PriceUSD на коэффициент конвертации валюты и устанавливаем полученное значение в поле PriceEUR.

Создание задачи в приложении Todoist

Todoist — это веб-сервис и программа для управления задачами. Веб-сервис предоставляет возможность через api создавать задачи. Приведем скрипт для создания задачи, текст задачи будет браться из записи.

var commands='[{"uuid":"' + guid() + '","temp_id":"' + guid() + '","type":"item_add","args":{"content":"' + entry().field("Task") + '"}}]'
result = http().get("https://todoist.com/API/v7/sync?token=15281e8e4d499dаff817af0b14112eac3176f9dc&commands=" + encodeURIComponent(commands))
if (result.code == 200) message('Task has been successfully created")
  1. Составляем команду в json формате для создания задачи в todoist, формат команды описан здесь: https://developer.todoist.com/#add-an-item. В команде должны присутствовать уникальные идентификаторы, для их получения используем глобальную функцию guid().
  2. Выполняем http запрос. Атрибут token используется для авторизации в todoist, его можно получить в Настройках Todoist вкладка Аккаунт. Так как текст задачи может содержать символы недопустимые в URL-запроса, то экранируем их с помощью стандартной функции encodeURIComponent().
  3. Выводим пользователю сообщение об успешно созданной задачи.

Взаимодействие с системой

Глобальные Функции

message(text)

Отобразить пользователю небольшое всплывающее сообщение.
Параметры: text - текст для отображения.

cancel()

Отменить операцию вызвавшую данный триггер. Многие действия возникают при каких либо операциях с записями (создание, модификация, удаление и .д.). Если фаза действия предшествует операции, то возможно отменить эту операцию с помощью данной функции. Например, применять эту функцию можно при проверки корректности вводимых данных перед сохранением записи.

system()

Получить информацию о системе.
Результат: Объект System с информацией о системе.

log(text)

Вывести строку в лог-файл выполнения скрипта. Функция будет полезна для отладки скриптов.
Параметры: Text - текст который будет выведен в лог.

guid()

Генерация случайного текстового идентификатора.
Результат: Случайная строка-идентификатор.

intent(action)

Создать объект обмена сообщениями - Intent. С помощью данного объекта можно передать данные другому приложению, или заставить другое приложение выполнить какое-либо действие.
Функция доступна только для Android.
Параметры: action - Строка, определяющая стандартное действие, которое требуется выполнить (например, view (просмотр) или pick (выбор)).
Результат: Intent - объект обмена сообщениями.
После получения объекта требуется добавить в него отправляемые данные и вызывать метод send().
В Android есть множество встроенных действий, список и описание которых вы можете найти здесь.

Объект System

Данный объект содержит информацию о системе.

Свойства

os
имя операционной системы на которой запущен скрипт.

Объект Intent

Объект обмена сообщениями. Объект создается с помощью вызова глобальной функции intent().

Методы

data(uri)
Установить URI ссылающийся на данные.
Параметры:uri - URI, ссылающийся на данные, с которыми будет выполняться действие. Это может быть идентификатор контакта, путь к файлу, номер телефона и т.д.
mimeType(mime)
Установить MIME тип данных.
Параметры:mime - MIME тип данных с которыми будет выполняться действие.
extra(key, value)
Установить дополнительные данные в виде ключ-значение, которые необходимы для выполнения запрошенного действия. Точно так же, как некоторые действия используют определенные виды URI данных, некоторые действия используют определенные дополнительные данные.
Параметры:
extraLong(key, value)
Установить дополнительные данные в виде ключ-значение, где значение должно быть типом Long.
send()
Отправить сообщение.

Примеры

Скрипт открывающий окно набора номера

В библиотеке должно быть поле Phone, содержащие номер телефона.

i = intent("android.intent.action.DIAL")
i.data("tel:"+entry().field("Phone"))
i.send()
  1. Создаем объект обмена сообщениями Intent и указываем действие которое откроет окно набора номера - android.intent.action.DIAL.
  2. В качестве данных требуется указать номер телефона в формате tel:номер. Номер телефона берем из поля записи Phone.
  3. Отправляем сообщение.

Скрипт открывающий приложение для отправки смс-сообщения

Номер телефона будет определяться полем записи - Phone, а текст сообщения составляется из полей ContactName и Notes.

msg = "Dear, " + entry().field("ContactName") + "\n" + entry().field("Notes")
i = intent("android.intent.action.SENDTO")
i.data("smsto:"+entry().field("Phone"))
i.extra("sms_body" , msg)
i.send()
  1. Составляем сообщение из значений полей ContactName и Notes
  2. Создаем объект обмена сообщениями Intent и указываем действие которое откроет приложение для отправки сообщений- android.intent.action.SENDTO.
  3. В качестве данных требуется указать номер телефона в формате smsto:номер. Номер телефона берем из поля записи Phone.
  4. Текст сообщение передаем в дополнительный параметр sms_body.
  5. Отправляем сообщение.

Скрипт открывающий форму создания события в Гугл-Календаре.

Время события и название события будут определяться полями записи.

i = intent("android.intent.action.INSERT")
i.data("content://com.android.calendar/events")
i.extra("title", entry().field("Title"))
i.extra("description" , entry().field("Description"))
i.extraLong("beginTime" , entry().field("Begin").getTime())
i.extraLong("endTime" , entry().field("End").getTime())
i.send()
  1. Создаем объект обмена сообщениями Intent и указываем действие которое требуется выполнить, а именно создание объекта - android.intent.action.INSERT.
  2. Для события android.intent.action.INSERT в data требуется передать базовый Uri создаваемого объекта. Событие в Google-календаре имеет базовый Uri - content://com.android.calendar/events.
  3. Устанавливаем название события, которое берем из поля Title.
  4. Устанавливаем описание события, которое берем из поля Description.
  5. Устанавливаем время начала события, которое берем из поля Begin. Поле Begin должно иметь тип Date/Time. Дополнительный параметр beginTime должен иметь тип Long, поэтому используется метод extraLong.
  6. Устанавливаем время окончания события, которое берем из поля End. Поле End должно иметь тип Date/Time. Дополнительный параметр endTime должен иметь тип Long, поэтому используется метод extraLong.
  7. Отправляем сообщение.