1from loguru import logger
2from requests.exceptions import RequestException
3
4from flexget import plugin
5from flexget.config_schema import one_or_more
6from flexget.event import event
7from flexget.plugin import PluginWarning
8from flexget.utils.requests import Session as RequestSession
9from flexget.utils.requests import TimedLimiter
10
11plugin_name = 'join'
12logger = logger.bind(name=plugin_name)
13
14requests = RequestSession(max_retries=3)
15requests.add_domain_limiter(TimedLimiter('appspot.com', '5 seconds'))
16
17JOIN_URL = 'https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush'
18
19
20class JoinNotifier:
21    """
22    Example::
23
24      notify:
25        entries:
26          via:
27            - join:
28                [api_key: <API_KEY> (your join api key. Only required for 'group' notifications)]
29                [group: <GROUP_NAME> (name of group of join devices to notify. 'all', 'android', etc.)
30                [device: <DEVICE_ID> (can also be a list of device ids)]
31                [url: <NOTIFICATION_URL>]
32                [sms_number: <NOTIFICATION_SMS_NUMBER>]
33                [icon: <NOTIFICATION_ICON>]
34    """
35
36    schema = {
37        'type': 'object',
38        'properties': {
39            'api_key': {'type': 'string'},
40            'group': {
41                'type': 'string',
42                'enum': ['all', 'android', 'chrome', 'windows10', 'phone', 'tablet', 'pc'],
43            },
44            'device': one_or_more({'type': 'string'}),
45            'device_name': one_or_more({'type': 'string'}),
46            'url': {'type': 'string'},
47            'icon': {'type': 'string'},
48            'sms_number': {'type': 'string'},
49            'priority': {'type': 'integer', 'minimum': -2, 'maximum': 2},
50        },
51        'required': ['api_key'],
52        'not': {'required': ['device', 'group']},
53        'error_not': 'Cannot select both \'device\' and \'group\'',
54        'additionalProperties': False,
55    }
56
57    def notify(self, title, message, config):
58        """
59        Send Join notifications.
60        """
61        notification = {
62            'title': title,
63            'text': message,
64            'url': config.get('url'),
65            'icon': config.get('icon'),
66            'priority': config.get('priority'),
67            'apikey': config['api_key'],
68        }
69        if config.get('device'):
70            if isinstance(config['device'], list):
71                notification['deviceIds'] = ','.join(config['device'])
72            else:
73                notification['deviceId'] = config['device']
74        elif config.get('group'):
75            notification['deviceId'] = 'group.' + config['group']
76        else:
77            notification['deviceId'] = 'group.all'
78
79        if config.get('device_name'):
80            if isinstance(config['device_name'], list):
81                notification['deviceNames'] = ','.join(config['device_name'])
82            else:
83                notification['deviceNames'] = config['device_name']
84
85        if config.get('sms_number'):
86            notification['smsnumber'] = config['sms_number']
87            notification['smstext'] = message
88
89        try:
90            response = requests.get(JOIN_URL, params=notification)
91        except RequestException as e:
92            raise PluginWarning(e.args[0])
93        else:
94            error = response.json().get('errorMessage')
95            if error:
96                raise PluginWarning(error)
97
98
99@event('plugin.register')
100def register_plugin():
101    plugin.register(JoinNotifier, plugin_name, api_ver=2, interfaces=['notifiers'])
102