API

# Server

Для работы mobile уведомлений требуется **mongodb**. Все необходимые зависимости описаны в **Gemfile**

За отправку уведомлений с сервера отвечают несколько основных классов:

1. **pns.rb** - реализация главного класса **Pns** отвечающего за отправку уведомлений на все платформы
2. **push\_provider.rb** - класс отправки уведомлений на **Mobile**
3. **webpush\_provider.rb** - класс отправки **Web** уведомлений

## Пример отправки сообщения (файл **debug\_pns.rb**)

```
class DebugPnsService
  include Slots
  def initialize
    # активация базы
    Mongoid.load!("../../configs/mongoid.yml", :development)
  end

  def test
    # создание сервиса уведомлений
    pns = Pns.instance
    # формирование сообщения (описание формата ниже)
    msg = {
      "message" => "hi people",
      "payload" => "bugaga",
      "title" => "Slots",
      "image" => "https://storage.googleapis.com/ flash-slots-static-test/notification_2.png",
      "small_image" => "https://storage.googleapis.com/ slots-static/SlotsPush2.png",
      "bg_color" => "#ffffff",
      "bg_color_small" => "#ce0100",
      "text_color" => "#000000",
      "text_color_small" => "#000000",
      "show_icon" => true,
      "url" => "" => "https://storage.googleapis.com/ flash-slots-static-test/notification_2.png",
      "networks" => [ "android",  "ios", "wp", "fb", "vk", "ok"]
    }
    # отправка сообщения
    pns.send(msg)
  end
end

t = DebugPnsService.new
t.test()

```

## Формат сообщения

Каждая из платформ возьмет только то что она поддерживает

* **title** - заголовок
* **message** - текст уведомления
* **payload** - текст передаваемый в приложения после клика на уведомление
* **image** - иконка (в андройде фон развернутого сообщения)
* **networks** - строковый массив платформ для которых предназначено уведомление

только для Android:

* **small\_image** - фоновая картинка
* **bg\_color** - цвет фона
* **bg\_color\_small** - цвет свёрнутого фона
* **text\_color** - цвет текста
* **text\_color\_small** - цвет текста свёрнутого сообщения
* **show\_icon** - флаг отображения иконки

только для Web

* **url** - ссылка для перехода по клику на уведомление

## Поддерживаемые платформы

**Mobile:**

1. "android" - Android
2. "ios" - iOS
3. "wp" - Windows Phone

**Web:**

1. "fb" - Facebook
2. "vk" - Vkontakte
3. "ok" - Odnoklasinki

## API Request Format

```
POST /api/push HTTP/1.1
Authorization: Basic <master authorization string>
Content-Type: application/json
Accept: application/json; version=3;

```

All API requests are over HTTP, using the base url `https://go.urbanairship.com/`. For requests with a body, the body must be in JSON format. When sending a request with a JSON body, set the`Content-type` header to `application/json`.

## Version Syntax

You must specify the version of the API you are using with the `Accept`HTTP header. If you do not specify an API version in the `Accept` header, a `406 Not Acceptable` is returned.

The content type used is a vendor-specific media type (see RFC 4288), and must be specified as follows:

`application/vnd.urbanairship+json; version=3`

https://docs.urbanairship.com/api/ua/

https://en.wikipedia.org/wiki/Basic\_access\_authentication#Client\_side

## Date/Time Format

All date/time values are represented according to ISO 8601 in UTC. A `T`separator is preferred but not required; it will be included in all date/time values generated by the API.

### JSON Parameters

audience - An identifying the devices to push to.

notification - A defining the notification payload.

## Push Object

A *push object* describes everything about a push, including theaudience and push payload. A push object is composed of up to six attributes:

* `"audience"` - Required
* `"notification"` - Required if `"message"` is not present, optional if it is
* `"device_types"` Required. Can either be `"all"` or an array of one or more of the following values: `"ios", "android", "amazon", "wns", "mpns"`
* `"options"` - Optional, a place to specify non-payload-specific delivery options for the push. See Push Options.
* `"in_app"` - Optional, an In-App message
* `"message"` - Optional, a Rich Push message

"OR" "AND" масив в Json это, конечно, сильно

## Push Object

```
{
   "audience": {
      "OR": [
         {
            "tag": [
               "sports",
               "entertainment"
            ]
         },
         {
            "ios_channel": "871922F4F7C6DF9D51AC7ABAE9AA5FCD7188D7BFA19A2FA99E1D2EC5F2D76506"
         }
      ]
   },
   "notification": {
      "alert": "Hi from Urban Airship!",
      "ios": {
         "extra": {
            "url": "http://www.urbanairship.com"
         }
      }
   },
   "options": {
      "expiry": "2017-04-01T12:00:00"
   },
   "message": {
      "title": "Message title",
      "body": "<Your message here>",
      "content_type": "text/html"
   },
   "in_app": {
      "alert": "This part appears in-app!",
      "display_type": "banner",
      "expiry": "2015-04-01T12:00:00",
      "display": {
         "position": "top"
      }
   },
   "device_types": [ "ios", "wns", "android" ]
}

```

A *push object* describes everything about a push, including theaudience and push payload. A push object is composed of up to six attributes:

* `"audience"` - Required
* `"notification"` - Required if `"message"` is not present, optional if it is
* `"device_types"` Required. Can either be `"all"` or an array of one or more of the following values: `"ios", "android", "amazon", "wns", "mpns"`
* `"options"` - Optional, a place to specify non-payload-specific delivery options for the push. See Push Options.
* `"in_app"` - Optional, an In-App message
* `"message"` - Optional, a Rich Push message

## Audience Selection

An *audience selector* forms the expression that determines the set of devices to which a notification will be sent. A valid *audience selector* is a JSON expression which can identify an app installation by means of one of the following four selector types:

* Atomic selector
* Compound selector
* Location expression
* Special selector

### Atomic Selectors

```
{
    "audience" : {
        "tag" : "Giants Fans"
    }
}

```

```
{
   "audience": {
      "tag": "platinum-member",
      "group": "loyalty"
   }
}

```

```
{
   "audience": {
      "static_list": "subscriptions"
   }
}

```

```
{
   "audience": {
      "ios_channel": "9c36e8c7-5a73-47c0-9716-99fd3d4197d5"
   }
}

```

```
{
   "audience": {
      "amazon_channel": ["user-1", "user-2"]
   }
}

```

```
{
    "audience" : {
        "device_token" : "C9E454F6105B0F442CABD48CB678E9A230C9A141F83CF4CC03665375EB78AD3A"
    }
}

```

```
{
    "audience" : {
        "android_channel" : "b8f9b663-0a3b-cf45-587a-be880946e880"
    }
}

```

```
{
    "audience" : {
        "amazon_channel" : "b8f9b663-0a3b-cf45-587a-be880946e880"
    }
}

```

```
{
    "audience" : {
        "wns" : "3644dada-d807-a2da-19d0-90d902ea7636"
    }
}

```

```
{
    "audience" : {
        "mpns" : "7048a456-0ce9-1c33-77d0-5975d980ffa0"
    }
}

```

```
{
    "audience" : {
        "segment" : "<segment-id>"
    }
}

```

```
{
   "audience" : {
      "named_user" : "user-id-54320"
   }
}

```

```
{
    "audience" : {
        "alias" : "room_237"
    }
}

```

Atomic selectors are the simplest way to identify a single device, i.e., app installation, or a group of devices. These selectors are either a unique identifier for the device such as a channel ID or metadata that maps to the device (or multiple devices) such as a tag. Atomic selectors may be one of:

`tag`
A tag is an arbitrary bit of metadata used to group different devices together. A tag specifier may or may not have an associated `group`declaration, which specifies what tag group the tag belongs to. If no tag group is specified, the default `"device"` group is used.
`segment`
a Segment is a subset of your audience that is predefined by combining Tags and/or devices that meet your specified location-targeting criteria
`static_list`
a list is a subset of your audience defined by a CSV file containing channel IDs, Named Users, or Aliases
`named_user`
a named\_user
`alias`
an alias is an alternate, non-unique name, often mapped to a user profile in a different database, that can be used to target devices associated with that profile. Superseded by `named_user`.
`ios_channel`
the unique channel identifier used to target an iOS device
`device_token`
the unique identifier used to target an iOS device, superseded by`ios_channel`
`android_channel`
the unique channel identifier used to target an Android device
`apid`
the unique identifier used to target an Android device, superseded by `android_channel`
`amazon_channel`
the unique channel identifier used to target an Amazon device
`wns`
the unique identifier used to target a Windows device
`mpns`
the unique identifier used to target a Windows Phone device

### Compound Selectors

```
{
   "audience" : {
      "tag" : ["apples", "oranges", "bananas"]
   }
}

```

```
{
   "audience" : {
      "OR" : [
         { "tag" : "apples" },
         { "tag" : "oranges" },
         { "tag" : "bananas" }
      ]
   }
}

```

Compound selectors combine boolean operators (AND, OR, or NOT) with one or more of the atomic expressions mentioned above. The syntax can be either *implicit*, using an array of values associated with an atomic selector, as seen in this example:

### Logical Expressions

```
{
   "audience": {
      "AND": [
         {"OR": [
            {"tag": "sports"},
            {"tag": "entertainment"}
         ]},
         {"tag": "language_en"}
      ]
   }
}

```

```
{
   "audience": {
      "AND": [
         { "tag": "Group1" },
         { "NOT":
            { "alias": "UserA" }
         }
      ]
   }
}

```

An explicit logical expression is a JSON object consisting of a logical operator as the key, and an array of one or more expressions (which can be atomic, implicit OR, or other explicit logical expressions – anything except “all”).

### Use Caution with NOT Operators

One or more `NOT` statements may cause latency when sending notifications, as `NOT` operations are inherently more expensive to perform than `OR` or `AND` operations.

Latency is greater with larger audiences. We recommend using `AND`statements in place of `NOT` statments whenever possible as a best practice.

Example:

There are two types of people who have your app. Those who like Justin Bieber and those who hate Justin Bieber.

Tag Strategy

* Users who like Justin Bieber tag “`belieber`” and “`nonhater`“
* Users who hate Justin Bieber tag “`hater`” and “`nonbelieber`“

Using tags this way assigns a *positive* and *non-negative* tag attribute to a user when possible, making it easier and faster to identify audience with the absence of an attribute.

### Location Expressions

```
{
   "audience": {
      "location": {
         "id": "4oFrxA7ncddPratuelEQIV",
         "date": {
            "days": {
               "start": "2015-10-15",
               "end": "2015-10-21"
            }
         }
      }
   }
}

```

```
{
   "audience": {
      "location": {
         "<alias-type>": "some_alias_value",
         "date": {
            "days": {
               "start": "2015-10-15",
               "end": "2015-10-21"
            }
         }
      }
   }
}

```

When sending to a location, include a location expression in the `audience` object, identifying the intended polygon by means of:

1. either an `id` or location alias and
2. the window of time for the targeted message

The notification will match devices that have checked in with a location within the given polygon during the given time window. The time window is required and must be specified by a Time Period Specifier.

### JSON Parameters

id

Optional, a polygon ID

<alias-type>

Optional, a polygon alias, with the key indicating the type of alias. One of `id` or alias must be provided. See: Boundary Types and Aliases Catalog for more information.

date

Required, a Time Period Specifier

## Schedule object

http://ru.nevopush.wikia.com/wiki/Серверная\_часть(Ruby)