From 561a8029cf9abc62be8e8ecd604c0ac5cc17f443 Mon Sep 17 00:00:00 2001
From: Thomas NOEL <tnoel@entrouvert.com>
Date: Wed, 16 Jan 2019 15:36:13 +0100
Subject: [PATCH] add phone calls connector (#29829)

---
 passerelle/apps/phonecalls/__init__.py        |   0
 .../phonecalls/migrations/0001_initial.py     |  55 +++++++
 .../apps/phonecalls/migrations/__init__.py    |   0
 passerelle/apps/phonecalls/models.py          | 148 ++++++++++++++++++
 passerelle/settings.py                        |   1 +
 5 files changed, 204 insertions(+)
 create mode 100644 passerelle/apps/phonecalls/__init__.py
 create mode 100644 passerelle/apps/phonecalls/migrations/0001_initial.py
 create mode 100644 passerelle/apps/phonecalls/migrations/__init__.py
 create mode 100644 passerelle/apps/phonecalls/models.py

diff --git a/passerelle/apps/phonecalls/__init__.py b/passerelle/apps/phonecalls/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/passerelle/apps/phonecalls/migrations/0001_initial.py b/passerelle/apps/phonecalls/migrations/0001_initial.py
new file mode 100644
index 0000000..b45418a
--- /dev/null
+++ b/passerelle/apps/phonecalls/migrations/0001_initial.py
@@ -0,0 +1,55 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.17 on 2019-01-16 14:36
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+import jsonfield.fields
+
+
+class Migration(migrations.Migration):
+
+    initial = True
+
+    dependencies = [
+        ('base', '0010_loggingparameters_trace_emails'),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='Call',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('callee', models.CharField(max_length=64)),
+                ('caller', models.CharField(max_length=64)),
+                ('start_timestamp', models.DateTimeField(auto_now_add=True)),
+                ('end_timestamp', models.DateTimeField(default=None, null=True)),
+                ('details', jsonfield.fields.JSONField(default={})),
+            ],
+            options={
+                'ordering': ['-end_timestamp', '-start_timestamp'],
+                'get_latest_by': 'start_timestamp',
+                'verbose_name': 'Phone Call',
+            },
+        ),
+        migrations.CreateModel(
+            name='PhoneCalls',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('title', models.CharField(max_length=50, verbose_name='Title')),
+                ('description', models.TextField(verbose_name='Description')),
+                ('slug', models.SlugField(unique=True)),
+                ('max_call_duration', models.PositiveIntegerField(default=120, verbose_name='Maximum duration of a call, in minutes.')),
+                ('data_retention_period', models.PositiveIntegerField(default=60, verbose_name='Data retention period, in days.')),
+                ('users', models.ManyToManyField(blank=True, to='base.ApiUser')),
+            ],
+            options={
+                'verbose_name': 'Phone Calls',
+            },
+        ),
+        migrations.AddField(
+            model_name='call',
+            name='resource',
+            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='phonecalls.PhoneCalls'),
+        ),
+    ]
diff --git a/passerelle/apps/phonecalls/migrations/__init__.py b/passerelle/apps/phonecalls/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/passerelle/apps/phonecalls/models.py b/passerelle/apps/phonecalls/models.py
new file mode 100644
index 0000000..6e9a69a
--- /dev/null
+++ b/passerelle/apps/phonecalls/models.py
@@ -0,0 +1,148 @@
+# passerelle - uniform access to multiple data sources and services
+# Copyright (C) 2019  Entr'ouvert
+#
+# This program is free software: you can redistribute it and/or modify it
+# under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+from django.db import models
+from django.utils.timezone import datetime, timedelta, now, make_naive
+from django.utils.translation import ugettext_lazy as _
+from jsonfield import JSONField
+
+from passerelle.base.models import BaseResource
+from passerelle.utils.api import endpoint
+
+
+class PhoneCalls(BaseResource):
+    category = _('Telephony')
+
+    max_call_duration = models.PositiveIntegerField(
+            _('Maximum duration of a call, in minutes.'),
+            help_text=_('Each hour, too long calls are closed.'),
+            default=120)
+    data_retention_period = models.PositiveIntegerField(
+            _('Data retention period, in days.'),
+            help_text=_('Each day, old calls are removed.'),
+            default=60)
+
+    class Meta:
+        verbose_name = _('Phone Calls')
+
+    @endpoint(name='call-start',
+              perm='can_access',
+              parameters={
+                  'callee': {'description': _('Callee number'),
+                             'example_value': '142'},
+                  'caller': {'description': _('Caller number'),
+                             'example_value': '0143350135'},
+              })
+    def call_start(self, request, callee, caller, **kwargs):
+        # close current callee/caller calls
+        Call.objects.filter(resource=self, callee=callee, caller=caller,
+                            end_timestamp=None).update(end_timestamp=now())
+        # create the new call
+        new_call = Call(resource=self, callee=callee, caller=caller, details=kwargs)
+        new_call.save()
+        return {'data': new_call.json()}
+
+    @endpoint(name='call-stop',
+              perm='can_access',
+              parameters={
+                  'callee': {'description': _('Callee number'),
+                             'example_value': '142'},
+                  'caller': {'description': _('Caller number'),
+                             'example_value': '0143350135'},
+              })
+    def call_stop(self, request, callee, caller, **kwargs):
+        # close all current callee/caller calls, returns the last one
+        current_calls = Call.objects.filter(resource=self, callee=callee, caller=caller,
+                                            end_timestamp=None)
+        current_calls_ids = list(current_calls.values_list('id', flat=True))
+        current_calls.update(end_timestamp=now())
+        # return current_calls with their new end_timestamp
+        return {'data': [call.json() for call in Call.objects.filter(id__in=current_calls_ids)]}
+
+    @endpoint(name='calls',
+              perm='can_access',
+              parameters={
+                  'callee': {'description': _('Callee number'),
+                             'example_value': '142'},
+                  'limit': {'description': _('Maximal number of results')},
+              })
+    def calls(self, request, callee=None, caller=None, limit=30):
+        calls = Call.objects.filter(resource=self)
+        if callee:
+            calls = calls.filter(callee=callee)
+        if caller:
+            calls = calls.filter(caller=caller)
+
+        def json_list(calls):
+            return [call.json() for call in calls[:limit]]
+        return {
+            'data': {
+                'current': json_list(calls.filter(end_timestamp__isnull=True)),
+                'past': json_list(calls.filter(end_timestamp__isnull=False)),
+            }
+        }
+
+    def hourly(self):
+        super(PhoneCalls, self).hourly()
+        # close unfinished long calls
+        maximal_time = now() - timedelta(minutes=self.max_call_duration)
+        Call.objects.filter(resource=self, end_timestamp=None,
+                            start_timestamp__lt=maximal_time).update(end_timestamp=now())
+
+    def daily(self):
+        super(PhoneCalls, self).daily()
+        # remove finished old calls
+        maximal_datetime = now() - timedelta(days=self.data_retention_period)
+        Call.objects.filter(resource=self, end_timestamp__isnull=False,
+                            end_timestamp__lt=maximal_datetime).delete()
+
+
+class Call(models.Model):
+    resource = models.ForeignKey(PhoneCalls)
+    callee = models.CharField(blank=False, max_length=64)
+    caller = models.CharField(blank=False, max_length=64)
+    start_timestamp = models.DateTimeField(auto_now_add=True)
+    end_timestamp = models.DateTimeField(null=True, default=None)
+    details = JSONField(default={})
+
+    class Meta:
+        verbose_name = _('Phone Call')
+        ordering = ['-start_timestamp']
+
+    def json(self):
+        # We use make_naive to send localtime, because this API will be used
+        # by javascript, which it will not be comfortable with UTC datetimes
+        if self.end_timestamp:
+            current = False
+            end_timestamp = make_naive(self.end_timestamp)
+            duration = self.end_timestamp - self.start_timestamp
+        else:
+            current = True
+            end_timestamp = None
+            duration = now() - self.start_timestamp
+        return {
+            'caller': self.caller,
+            'callee': self.callee,
+            'start_timestamp': make_naive(self.start_timestamp),
+            'end_timestamp': end_timestamp,
+            'current': current,
+            'duration': duration.seconds,
+            'details': self.details,
+        }
+
+    def __repr__(self):
+        return ('Call %(caller)s to %(callee)s - '
+                'start %(start_timestamp)s, end %(end_timestamp)s') % self.json()
diff --git a/passerelle/settings.py b/passerelle/settings.py
index e108d27..bbcb5de 100644
--- a/passerelle/settings.py
+++ b/passerelle/settings.py
@@ -138,6 +138,7 @@ INSTALLED_APPS = (
     'passerelle.apps.ovh',
     'passerelle.apps.oxyd',
     'passerelle.apps.pastell',
+    'passerelle.apps.phonecalls',
     'passerelle.apps.solis',
     'passerelle.apps.arpege_ecp',
     # backoffice templates and static
-- 
2.20.1

