Triggers

From Memento Database Wiki
Revision as of 10:27, 19 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 is triggered by certain actions or events. As a scripting language used by JavaScript, the script may change or create a recording, perform an http-request, create a file, validate data, and more.

Creating a trigger

Each library can have multiple triggers. To open the list of triggers, go to the library, open the menu, and then click Triggers.

To create a trigger, open the library's list of triggers and click +. You must then select the start time and write a trigger script realizing your needs.

Since the launch of the trigger

The launch of the trigger is defined by two parameters:

Act
is any user to perform a recording operation. (Huh?)
Phase actions
specify a precise moment of the trigger for each type of action available to its phase.

Execution of the script

The phase in which the trigger is triggered also determines how the script will be executed — synchronously or asynchronously.

Simultaneous script execution
The application suspends user interaction for the duration of the script. It is not recommended to perform time-consuming operations in these scripts.
Asynchronous script execution
The script runs in the background; the application does not stop user interaction. Usually, scripts are executed synchronously, in the last phases of the action.

Security

Some features available from scripts (file operations, the implementation of http-requests, access to other libraries) for safety reasons requires a permit. These permissions a user must manually set separately for each library.

To open the dialogue set permissions for scripts — open library triggers list and click Shield on the toolbar. Set permissions must be done on each device separately. Selected resolution is not synchronized between devices.

Permissions scripts

Libraries
Determines which libraries will be available in addition to the native script. You can grant access to all libraries, or select certain libraries. This authorization is required for libByName function.
Read files
It provides access to the script file read from the storage device. This authorization is required for file functions.
Write files
It provides access to the script creation and editing files in the memory.This authorization is required for file functions.
Network
It provides the right to perform the script http requests. This authorization is required for the function of http.

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.
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.

Работа с файлами

С помощью скриптов можно выполнять чтение или запись файлов расположенных во внутренней памяти устройства или на сд-карте. Все операции с файлами производятся через объект File, который получается через вызов метода file().

Для работы с файлами для библиотеки должно быть установлено разрешение - на чтение и/или на запись файлов.

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

file(name)

Открыть файл для операций чтения или записи.

Параметр: name - имя и полный путь к файлу. Например, если файл расположен на sd-card, путь должен иметь вид /sdcard/example.txt.
Результат: Объект File.

Объект File

Данный объект возвращается функцией file() и предоставляет доступ к запрошенному файлу. Если файл с указанным в функции file() именем ещё не существует, то но будет создан. После операций чтения или записи файл должен быть закрыть функцией close().

Методы

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.

Примеры

Запись и чтение из файла

f= file("/sdcard/myfile.txt")
file.writeLine("one");                       
file.writeLine("two");
file.writeLine("three");
file.close();     
var a = file.readLines();
  1. Открываем файл myfile.txt на sdcard. Если файл еще не существует, то он будет создан.
  2. Записываем в файл строку "one"
  1. Закрываем файл, только после этого файл сохраняется.
  2. Считываем из файла все строки, в результате получаем массив строк в переменной a.

Сохранить в файл запись

Необходимо сохранить запись в формате 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. Отправляем сообщение.