# HG changeset patch
# User Arthur Lutz <arthur.lutz@logilab.fr>
# Date 1463580387 -7200
#      Wed May 18 16:06:27 2016 +0200
# Node ID 4e15941f6ce191d0f946955a8048e0249488f88d
# Parent  680de326f545d419bf86d0431bf40873d8c0f3c4
[hooks] initial version of hook to index content when created or changed

diff --git a/hooks.py b/hooks.py
--- a/hooks.py
+++ b/hooks.py
@@ -16,3 +16,43 @@
 # along with this program. If not, see <http://www.gnu.org/licenses/>.
 
 """cubicweb-elasticsearch specific hooks and operations"""
+
+import logging
+
+from elasticsearch import Elasticsearch
+from elasticsearch.exceptions import ConnectionError
+from urllib3.exceptions import ProtocolError
+
+from cubicweb.server import hook
+from cubicweb.predicates import score_entity
+from cubes.elasticsearch.es import indexable_types
+
+log = logging.getLogger(__name__)
+
+
+def entity_indexable(entity):
+    return entity.cw_etype in indexable_types(entity._cw.vreg.schema)
+
+
+class ContentUpdateIndexES(hook.Hook):
+
+    """detect content change and updates ES indexing"""
+
+    __regid__ = 'elasticsearch.contentupdatetoes'
+    __select__ = hook.Hook.__select__ & score_entity(entity_indexable)
+    events = ('after_update_entity', 'after_add_entity')
+    category = 'es'
+
+    def __call__(self):
+        locations = self._cw.vreg.config['elasticsearch-locations']
+        index_name = self._cw.vreg.config['index-name']
+        serializer = self.entity.cw_adapt_to('ISerializable')
+        json = serializer.serialize()
+        es = Elasticsearch(locations and locations.split(',') or None)
+        try:
+            # TODO option pour coté async ?
+            es.index(index=index_name,
+                     doc_type=self.entity.cw_etype,
+                     body=json)
+        except (ConnectionError, ProtocolError):
+            log.debug('Failed to index in hook, could not connect to ES')