Triggers

From Memento Database Wiki
Revision as of 02:57, 5 October 2016 by Admin (talk | contribs)
Jump to navigation Jump to search
« Page as of 2016-10-02, 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 defines the processing of an entry based on an Event that has taken place. 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.

Terminology

So, we define the following terms:

Event type
One of the following:
  • Creating an entry
  • Updating an entry
  • Deleting an entry
  • Opening an Entry Edit card
  • Adding an entry to Favorites
  • Removing an entry from Favorites
Event or Phase
One of a predefined set of moments (Event type & Phase) during entry processing during which the user can intervene via a trigger script. See the table of events below.
The Event and the Phase are essentially synonymous.
Depending upon context, either term may be more appropriate than the other.
Trigger or Trigger Script
A script that may be defined to run when an event occurs for an entry
The trigger (Event type & Phase) and the corresponding trigger script are one-to-one.
When referring specifically to the script, it is called the trigger script. When referring to the Event type & Phase and its listing in the trigger list, it is referred to merely as a trigger.

Mode of script execution

The phase in which the trigger is activated defines its mode of execution — synchronous or asynchronous.

Synchronous script execution mode
implies the application suspends user interaction and then executes the script. It is not recommended to perform time-consuming operations in this case.
Asynchronous script execution mode
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.

Creating a trigger

Each library can have a number of triggers — up to one for each Event. 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 identify the Event and write a trigger script that performs the necessary actions.

Events

These are the defined Event types, Phases, and their corresponding moves of execution.

THE DEFINED EVENT TYPES & THEIR PHASES
Event type Phase Execution mode
Creating an entry opening an Entry Edit card for add synchronous
before saving the entry synchronous
after saving the entry asynchronous
Updating an entry opening an Entry Edit card for update synchronous
before saving the entry synchronous
after saving the entry asynchronous
Deleting an entry before deleting an entry synchronous
after deleting an entry asynchronous
Opening an Entry View card before window display synchronous
after window display asynchronous
Adding entries to Favorites before the operation synchronous
after the operation asynchronous
Deleting an entry from Favorites before the operation synchronous
after the operation asynchronous

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 the 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() method.
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

Libraries and Entries

Global Methods

entry()

Get the entry of the Event. For example, if script is triggered by an Update Entry event, this method will return the entry being updated.
This method is available to all Events and Phases, with the exception of "Creating a file > Opening an Entry Edit card for add"; for this action, use the method entryDefault().
Result
Entry object — the current entry

entryDefault()

Get the Entry object containing the default field values for the Entry not yet created. This feature is available for the Event Creating an entry > Opening an Entry Edit card.
Result
The DefaultEntry object

lib()

Get the library of the Event
Result
Library object — the current library

libByName(name)

Get the named library. Permission to use the library is required.
Argument
The name of the library to get (type String)
Result
Library object — the library identified by the argument name (type Library)

Object Library

This object provides access to library entries. You can work with the current library — the lib() — or any other library database — libByName(). This method provides the ability to update existing entries and create new ones.

Methods

entries()
Get all the entries of the library
Result
array object containing entries, sorted by the time of their creation, from newest to oldest (type Array of Object)
find(query)
Search for entries in the library matching the given query. This search is similar to searching via Memento's user interface.
Argument
query — the search string (type String)
Result
Array object containing matching entries. Entries are sorted by the time of their creation, from newest to oldest. (type Array of Entry)
findByKey(name)
Search for all entries by the Entry Name field value. The library must be set for unique Entry Names.
Argument
name — the Entry Name field value
Result
Entry object
create(values)
Create a new entry in the library
Argument
values — containing the field values (type Object)
Result
Entry object — the new entry in the library (type Entry)

Properties

Title — The name of the library

Object Entry

This object holds an entry of the current library, primarily including field values. Methods provide access to the field values.

Entry Methods

set(name, value)
Set the value of the named field. After being called once, there is an entry with values in the library.
Arguments
name — the name of the field (type String)
value — the value of the field (type Value)
field(name)
Get the value of the named field
Argument
name — the name of the field (type String)
Result
The value of the field. The type of the field. (type subclass of Value)

Entry Properties

Title — account name (type String)
Description — description (type String)
Favorites — true, if the entry is in Favorites (type Boolean)
Deleted — true, if the record is deleted (it is in the basket) (type Boolean)

Object DefaultEntry

Template with default values for a new record

Methods

set(name, value)
Set the value of the field
Arguments
name — the name of the field (type String)
value — the value of the field (type Object)

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 entry or Change entry.

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 daily walks or use of a car or bicycle. The library has a StartingMileage field and a Mileage field. When an entry is created, the field StartMileage must get data from the field Mileage in the previous entry.

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

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

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.

Argument
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, assuming /sdcard as the path on your platform to the SD card.
Result
Object file

Object File

This object is returned by the file() method and provides access to the requested file. If the file with the specified name does not exist yet, it will be created. After reading or writing, the file should be closed using the method close().

Methods

readAll()
Reads all lines of the file, and then closes the file.
readLine()
Reads a line.
readLines()
Reads the remaining lines in the file, returning them in an array.
readChar()
Reads a character.
write(text)
Write string(s). 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 can be subsequently reopened.

Properties

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

JavaScript links

W3Schools
JavaScript Tutorial A pleasant, fairly complete, and useful tutorial on JavaScript
Best on a computer or tablet in landscape. On a phone or tablet in portrait, scroll to the bottom for navigation.
Mozilla Developer Network
JavaScript Guide Shows you how to use JavaScript, gives an overview of the language, and presents its capabilities & features
JavaScript Reference The entire JavaScript language described in detail
Introduction to JavaScript Introduces JavaScript and discusses some of its fundamental concepts
JavaScript Tutorial A re-introduction. JavaScript is often derided as being a toy, but beneath its simplicity, powerful language features await.
JavaScript 1.7 The JavaScript release upon which Memento is currently based
About JavaScript Jumping off point in learning about JavaScript