{"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/parameters.py","language":"python","identifier":"ReturnCoreObject._build_sub_core","parameters":"(cls, core)","argument_list":"","return_statement":"return attr","docstring":"Build return for a core object attached to another.","docstring_summary":"Build return for a core object attached to another.","docstring_tokens":["Build","return","for","a","core","object","attached","to","another","."],"function":"def _build_sub_core(cls, core):\n \"\"\"Build return for a core object attached to another.\"\"\"\n attr = {}\n for col in core._model_class._columns.keys():\n value = getattr(core, col)\n if isinstance(value, (list, tuple)):\n new_value = []\n for val in value:\n if hasattr(val, 'to_dict'):\n new_value.append(val.to_dict())\n else:\n new_value.append(val)\n value = new_value\n elif hasattr(value, 'to_dict'):\n value = value.to_dict()\n attr.update({col: value})\n return attr","function_tokens":["def","_build_sub_core","(","cls",",","core",")",":","attr","=","{","}","for","col","in","core",".","_model_class",".","_columns",".","keys","(",")",":","value","=","getattr","(","core",",","col",")","if","isinstance","(","value",",","(","list",",","tuple",")",")",":","new_value","=","[","]","for","val","in","value",":","if","hasattr","(","val",",","'to_dict'",")",":","new_value",".","append","(","val",".","to_dict","(",")",")","else",":","new_value",".","append","(","val",")","value","=","new_value","elif","hasattr","(","value",",","'to_dict'",")",":","value","=","value",".","to_dict","(",")","attr",".","update","(","{","col",":","value","}",")","return","attr"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/parameters.py#L37-L53"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/parameters.py","language":"python","identifier":"ReturnCoreObject.build","parameters":"(cls, core)","argument_list":"","return_statement":"return obj","docstring":"Main method to build a return object from a core.","docstring_summary":"Main method to build a return object from a core.","docstring_tokens":["Main","method","to","build","a","return","object","from","a","core","."],"function":"def build(cls, core):\n \"\"\"Main method to build a return object from a core.\"\"\"\n kls = cls._return_class\n obj = kls()\n for k, v in obj._data.iteritems():\n if cls._aliases.get(k):\n core_key = cls._aliases[k]\n else:\n core_key = k\n attr = getattr(core, core_key)\n if hasattr(cls._core_class, '_relations') \\\n and k in cls._core_class._relations:\n # XXX bad design using data key\n if 'data' in attr:\n attr = attr['data']\n attr = [x.to_dict() for x in attr]\n if isinstance(attr, BaseCore):\n attr = cls._build_sub_core(attr)\n elif isinstance(attr, (list, tuple)):\n new_attr = []\n for val in attr:\n if hasattr(val, 'to_dict'):\n value = val.to_dict()\n else:\n value = val\n new_attr.append(value)\n attr = new_attr\n if attr is None and v is not None:\n setattr(obj, k, v)\n else:\n if hasattr(attr, 'to_dict'):\n setattr(obj, k, attr.to_dict())\n else:\n setattr(obj, k, attr)\n obj.validate()\n return obj","function_tokens":["def","build","(","cls",",","core",")",":","kls","=","cls",".","_return_class","obj","=","kls","(",")","for","k",",","v","in","obj",".","_data",".","iteritems","(",")",":","if","cls",".","_aliases",".","get","(","k",")",":","core_key","=","cls",".","_aliases","[","k","]","else",":","core_key","=","k","attr","=","getattr","(","core",",","core_key",")","if","hasattr","(","cls",".","_core_class",",","'_relations'",")","and","k","in","cls",".","_core_class",".","_relations",":","# XXX bad design using data key","if","'data'","in","attr",":","attr","=","attr","[","'data'","]","attr","=","[","x",".","to_dict","(",")","for","x","in","attr","]","if","isinstance","(","attr",",","BaseCore",")",":","attr","=","cls",".","_build_sub_core","(","attr",")","elif","isinstance","(","attr",",","(","list",",","tuple",")",")",":","new_attr","=","[","]","for","val","in","attr",":","if","hasattr","(","val",",","'to_dict'",")",":","value","=","val",".","to_dict","(",")","else",":","value","=","val","new_attr",".","append","(","value",")","attr","=","new_attr","if","attr","is","None","and","v","is","not","None",":","setattr","(","obj",",","k",",","v",")","else",":","if","hasattr","(","attr",",","'to_dict'",")",":","setattr","(","obj",",","k",",","attr",".","to_dict","(",")",")","else",":","setattr","(","obj",",","k",",","attr",")","obj",".","validate","(",")","return","obj"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/parameters.py#L56-L91"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/parameters.py","language":"python","identifier":"ReturnIndexObject.build","parameters":"(cls, entry)","argument_list":"","return_statement":"return obj","docstring":"Main method to build a return object from an index entry.","docstring_summary":"Main method to build a return object from an index entry.","docstring_tokens":["Main","method","to","build","a","return","object","from","an","index","entry","."],"function":"def build(cls, entry):\n \"\"\"Main method to build a return object from an index entry.\"\"\"\n kls = cls._return_class\n obj = kls()\n for k, v in obj._data.iteritems():\n if cls._aliases.get(k):\n idx_key = cls._aliases[k]\n else:\n idx_key = k\n attr = entry.get(idx_key, cls._default.get(idx_key))\n setattr(obj, k, attr)\n obj.validate()\n return obj","function_tokens":["def","build","(","cls",",","entry",")",":","kls","=","cls",".","_return_class","obj","=","kls","(",")","for","k",",","v","in","obj",".","_data",".","iteritems","(",")",":","if","cls",".","_aliases",".","get","(","k",")",":","idx_key","=","cls",".","_aliases","[","k","]","else",":","idx_key","=","k","attr","=","entry",".","get","(","idx_key",",","cls",".","_default",".","get","(","idx_key",")",")","setattr","(","obj",",","k",",","attr",")","obj",".","validate","(",")","return","obj"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/parameters.py#L109-L121"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/config.py","language":"python","identifier":"Configuration.load","parameters":"(cls, filename, name=None)","argument_list":"","return_statement":"return cls(name)","docstring":"Load configuration from `filename`.\n\n An optional `name` is recommended to use many environment.","docstring_summary":"Load configuration from `filename`.","docstring_tokens":["Load","configuration","from","filename","."],"function":"def load(cls, filename, name=None):\n \"\"\"\n Load configuration from `filename`.\n\n An optional `name` is recommended to use many environment.\n \"\"\"\n name = name or filename\n\n if name not in cls._conffiles:\n with open(filename) as fdesc:\n cls._conffiles[name] = yaml.load(fdesc, YAMLLoader)\n return cls(name)","function_tokens":["def","load","(","cls",",","filename",",","name","=","None",")",":","name","=","name","or","filename","if","name","not","in","cls",".","_conffiles",":","with","open","(","filename",")","as","fdesc",":","cls",".","_conffiles","[","name","]","=","yaml",".","load","(","fdesc",",","YAMLLoader",")","return","cls","(","name",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/config.py#L25-L36"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/config.py","language":"python","identifier":"Configuration.configuration","parameters":"(self)","argument_list":"","return_statement":"return self._conffiles[self._name]","docstring":"Get the configuration for current object.\n\n .. deprecated:: use the :meth:`get` instead","docstring_summary":"Get the configuration for current object.","docstring_tokens":["Get","the","configuration","for","current","object","."],"function":"def configuration(self):\n \"\"\" Get the configuration for current object.\n\n .. deprecated:: use the :meth:`get` instead\n \"\"\"\n return self._conffiles[self._name]","function_tokens":["def","configuration","(","self",")",":","return","self",".","_conffiles","[","self",".","_name","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/config.py#L39-L44"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/config.py","language":"python","identifier":"Configuration.get","parameters":"(self, key, default=None, separator='.')","argument_list":"","return_statement":"","docstring":"Retrieve a configuration setting.\n\n :param key: a dot separated string\n :type key: str","docstring_summary":"Retrieve a configuration setting.","docstring_tokens":["Retrieve","a","configuration","setting","."],"function":"def get(self, key, default=None, separator='.'):\n \"\"\" Retrieve a configuration setting.\n\n :param key: a dot separated string\n :type key: str\n \"\"\"\n key = key.split(separator)\n value = self.configuration\n try:\n for k in key:\n value = value[k]\n return value\n except KeyError:\n return default","function_tokens":["def","get","(","self",",","key",",","default","=","None",",","separator","=","'.'",")",":","key","=","key",".","split","(","separator",")","value","=","self",".","configuration","try",":","for","k","in","key",":","value","=","value","[","k","]","return","value","except","KeyError",":","return","default"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/config.py#L46-L59"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py","language":"python","identifier":"MixinCoreRelation._expand_relation","parameters":"(self, reltype)","argument_list":"","return_statement":"return res['data'] if res else []","docstring":"Return collection for given relation.","docstring_summary":"Return collection for given relation.","docstring_tokens":["Return","collection","for","given","relation","."],"function":"def _expand_relation(self, reltype):\n \"\"\"Return collection for given relation.\"\"\"\n res = self._relations[reltype].find(self.user, self)\n return res['data'] if res else []","function_tokens":["def","_expand_relation","(","self",",","reltype",")",":","res","=","self",".","_relations","[","reltype","]",".","find","(","self",".","user",",","self",")","return","res","[","'data'","]","if","res","else","[","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py#L16-L19"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py","language":"python","identifier":"MixinCoreRelation._get_relation","parameters":"(self, reltype, id)","argument_list":"","return_statement":"return result['data'][0] if result and result['data'] else None","docstring":"Get a specific core by in in relation.","docstring_summary":"Get a specific core by in in relation.","docstring_tokens":["Get","a","specific","core","by","in","in","relation","."],"function":"def _get_relation(self, reltype, id):\n \"\"\"Get a specific core by in in relation.\"\"\"\n rel_pkey = self._relations[reltype]._pkey_name\n result = self._relations[reltype].find(self.user,\n self,\n {rel_pkey: id})\n return result['data'][0] if result and result['data'] else None","function_tokens":["def","_get_relation","(","self",",","reltype",",","id",")",":","rel_pkey","=","self",".","_relations","[","reltype","]",".","_pkey_name","result","=","self",".","_relations","[","reltype","]",".","find","(","self",".","user",",","self",",","{","rel_pkey",":","id","}",")","return","result","[","'data'","]","[","0","]","if","result","and","result","[","'data'","]","else","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py#L21-L27"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py","language":"python","identifier":"MixinCoreRelation._add_relation","parameters":"(self, reltype, param)","argument_list":"","return_statement":"return new_obj","docstring":"Add a new core to given relation.","docstring_summary":"Add a new core to given relation.","docstring_tokens":["Add","a","new","core","to","given","relation","."],"function":"def _add_relation(self, reltype, param):\n \"\"\"Add a new core to given relation.\"\"\"\n param.validate()\n if hasattr(param, 'is_primary') and param.is_primary:\n existing = self._expand_relation(reltype)\n for obj in existing:\n if obj.is_primary:\n obj.is_primary = False\n obj.save()\n # XXX don't forget to update index\n\n # Transform param into core object\n # XXX find a better method ?\n attrs = {k: v for k, v in param.to_primitive().iteritems()\n if v is not None}\n new_obj = self._relations[reltype].create(self.user,\n self,\n **attrs)\n rel_list = getattr(self, reltype)\n rel_list.append(new_obj.get_id())\n self.save()\n if self._index_class:\n self._add_relation_index(reltype, attrs)\n if hasattr(self, '_lookup_objects') and \\\n reltype in self._lookup_objects:\n lookupkls = self._lookup_class\n look = lookupkls.create(user_id=self.user.user_id,\n value=new_obj.get_id(),\n contact_id=self.contact_id,\n type=reltype,\n lookup_id=new_obj.get_id())\n log.debug('Created lookup object for relation %s:%r' %\n (reltype, look))\n\n return new_obj","function_tokens":["def","_add_relation","(","self",",","reltype",",","param",")",":","param",".","validate","(",")","if","hasattr","(","param",",","'is_primary'",")","and","param",".","is_primary",":","existing","=","self",".","_expand_relation","(","reltype",")","for","obj","in","existing",":","if","obj",".","is_primary",":","obj",".","is_primary","=","False","obj",".","save","(",")","# XXX don't forget to update index","# Transform param into core object","# XXX find a better method ?","attrs","=","{","k",":","v","for","k",",","v","in","param",".","to_primitive","(",")",".","iteritems","(",")","if","v","is","not","None","}","new_obj","=","self",".","_relations","[","reltype","]",".","create","(","self",".","user",",","self",",","*","*","attrs",")","rel_list","=","getattr","(","self",",","reltype",")","rel_list",".","append","(","new_obj",".","get_id","(",")",")","self",".","save","(",")","if","self",".","_index_class",":","self",".","_add_relation_index","(","reltype",",","attrs",")","if","hasattr","(","self",",","'_lookup_objects'",")","and","reltype","in","self",".","_lookup_objects",":","lookupkls","=","self",".","_lookup_class","look","=","lookupkls",".","create","(","user_id","=","self",".","user",".","user_id",",","value","=","new_obj",".","get_id","(",")",",","contact_id","=","self",".","contact_id",",","type","=","reltype",",","lookup_id","=","new_obj",".","get_id","(",")",")","log",".","debug","(","'Created lookup object for relation %s:%r'","%","(","reltype",",","look",")",")","return","new_obj"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py#L29-L63"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py","language":"python","identifier":"MixinCoreRelation._delete_relation","parameters":"(self, reltype, id)","argument_list":"","return_statement":"return True","docstring":"Delete core from relation.","docstring_summary":"Delete core from relation.","docstring_tokens":["Delete","core","from","relation","."],"function":"def _delete_relation(self, reltype, id):\n \"\"\"Delete core from relation.\"\"\"\n rel_list = getattr(self, reltype)\n if id in rel_list:\n rel_list.remove(id)\n self.save()\n related = self._get_relation(reltype, id)\n if self._index_class and related:\n pkey = related._pkey_name\n self._delete_relation_index(reltype, pkey, id)\n if related:\n related.model.delete()\n else:\n raise NotFound\n if hasattr(self, '_lookup_objects') and \\\n reltype in self._lookup_objects:\n lookupkls = self._lookup_class\n lookup = lookupkls.get(self.user, id)\n if lookup:\n lookup.delete()\n else:\n log.warn('Lookup object not found when deleting relation')\n return True","function_tokens":["def","_delete_relation","(","self",",","reltype",",","id",")",":","rel_list","=","getattr","(","self",",","reltype",")","if","id","in","rel_list",":","rel_list",".","remove","(","id",")","self",".","save","(",")","related","=","self",".","_get_relation","(","reltype",",","id",")","if","self",".","_index_class","and","related",":","pkey","=","related",".","_pkey_name","self",".","_delete_relation_index","(","reltype",",","pkey",",","id",")","if","related",":","related",".","model",".","delete","(",")","else",":","raise","NotFound","if","hasattr","(","self",",","'_lookup_objects'",")","and","reltype","in","self",".","_lookup_objects",":","lookupkls","=","self",".","_lookup_class","lookup","=","lookupkls",".","get","(","self",".","user",",","id",")","if","lookup",":","lookup",".","delete","(",")","else",":","log",".","warn","(","'Lookup object not found when deleting relation'",")","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py#L65-L87"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py","language":"python","identifier":"MixinCoreRelation._add_relation_index","parameters":"(self, reltype, attrs)","argument_list":"","return_statement":"return True","docstring":"Add a relation to indexed object.","docstring_summary":"Add a relation to indexed object.","docstring_tokens":["Add","a","relation","to","indexed","object","."],"function":"def _add_relation_index(self, reltype, attrs):\n \"\"\"Add a relation to indexed object.\"\"\"\n idx = self._index_class.get(self.user_id, self.get_id())\n nested = getattr(idx, reltype)\n if not nested:\n log.warn('Nested index {} not found for {}'.format(reltype, self))\n return False\n nested.append(attrs)\n return True","function_tokens":["def","_add_relation_index","(","self",",","reltype",",","attrs",")",":","idx","=","self",".","_index_class",".","get","(","self",".","user_id",",","self",".","get_id","(",")",")","nested","=","getattr","(","idx",",","reltype",")","if","not","nested",":","log",".","warn","(","'Nested index {} not found for {}'",".","format","(","reltype",",","self",")",")","return","False","nested",".","append","(","attrs",")","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py#L89-L97"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py","language":"python","identifier":"MixinCoreRelation._delete_relation_index","parameters":"(self, reltype, key, id)","argument_list":"","return_statement":"return True","docstring":"Delete a relation from an indexed object.","docstring_summary":"Delete a relation from an indexed object.","docstring_tokens":["Delete","a","relation","from","an","indexed","object","."],"function":"def _delete_relation_index(self, reltype, key, id):\n \"\"\"Delete a relation from an indexed object.\"\"\"\n idx = self._index_class.get(self.user_id, self.get_id())\n # Look for existing entry\n found = None\n nested = getattr(idx, reltype)\n if not nested:\n log.warn('Nested index {} not found for {}'.format(reltype, self))\n return False\n for child in nested:\n if getattr(child, key) == id:\n found = child\n if not found:\n log.warn('Relation %s %s with id %s not found in index' %\n (reltype, key, id))\n nested.remove(found)\n return True","function_tokens":["def","_delete_relation_index","(","self",",","reltype",",","key",",","id",")",":","idx","=","self",".","_index_class",".","get","(","self",".","user_id",",","self",".","get_id","(",")",")","# Look for existing entry","found","=","None","nested","=","getattr","(","idx",",","reltype",")","if","not","nested",":","log",".","warn","(","'Nested index {} not found for {}'",".","format","(","reltype",",","self",")",")","return","False","for","child","in","nested",":","if","getattr","(","child",",","key",")","==","id",":","found","=","child","if","not","found",":","log",".","warn","(","'Relation %s %s with id %s not found in index'","%","(","reltype",",","key",",","id",")",")","nested",".","remove","(","found",")","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py#L99-L115"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py","language":"python","identifier":"MixinCoreNested._add_nested","parameters":"(self, column, nested)","argument_list":"","return_statement":"return value","docstring":"Add a nested object to a list.","docstring_summary":"Add a nested object to a list.","docstring_tokens":["Add","a","nested","object","to","a","list","."],"function":"def _add_nested(self, column, nested):\n \"\"\"Add a nested object to a list.\"\"\"\n nested.validate()\n kls = self._nested.get(column)\n if not kls:\n raise Exception('No nested class for {}'.format(column))\n column = getattr(self.model, column)\n # Ensure unicity\n if hasattr(kls, 'uniq_name'):\n for value in column:\n uniq = getattr(value, kls.uniq_name)\n if uniq == getattr(nested, kls.uniq_name):\n raise Exception('Unicity conflict for {}'.format(uniq))\n if hasattr(nested, 'is_primary') and nested.is_primary:\n for old_primary in column:\n column.is_primary = False\n value = nested.to_primitive()\n pkey = getattr(kls, '_pkey')\n value[pkey] = uuid.uuid4()\n log.debug('Will insert nested {} : {}'.format(column, value))\n column.append(kls(**value))\n return value","function_tokens":["def","_add_nested","(","self",",","column",",","nested",")",":","nested",".","validate","(",")","kls","=","self",".","_nested",".","get","(","column",")","if","not","kls",":","raise","Exception","(","'No nested class for {}'",".","format","(","column",")",")","column","=","getattr","(","self",".","model",",","column",")","# Ensure unicity","if","hasattr","(","kls",",","'uniq_name'",")",":","for","value","in","column",":","uniq","=","getattr","(","value",",","kls",".","uniq_name",")","if","uniq","==","getattr","(","nested",",","kls",".","uniq_name",")",":","raise","Exception","(","'Unicity conflict for {}'",".","format","(","uniq",")",")","if","hasattr","(","nested",",","'is_primary'",")","and","nested",".","is_primary",":","for","old_primary","in","column",":","column",".","is_primary","=","False","value","=","nested",".","to_primitive","(",")","pkey","=","getattr","(","kls",",","'_pkey'",")","value","[","pkey","]","=","uuid",".","uuid4","(",")","log",".","debug","(","'Will insert nested {} : {}'",".","format","(","column",",","value",")",")","column",".","append","(","kls","(","*","*","value",")",")","return","value"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py#L122-L143"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py","language":"python","identifier":"MixinCoreNested._delete_nested","parameters":"(self, column, nested_id)","argument_list":"","return_statement":"return attr.pop(found)","docstring":"Delete a nested object with its id from a list.","docstring_summary":"Delete a nested object with its id from a list.","docstring_tokens":["Delete","a","nested","object","with","its","id","from","a","list","."],"function":"def _delete_nested(self, column, nested_id):\n \"\"\"Delete a nested object with its id from a list.\"\"\"\n attr = getattr(self, column)\n log.debug('Will delete {} with id {}'.format(column, nested_id))\n found = -1\n for pos in xrange(0, len(attr)):\n nested = attr[pos]\n current_id = str(getattr(nested, nested._pkey))\n if current_id == nested_id:\n found = pos\n if found == -1:\n log.warn('Nested object {}#{} not found for deletion'.\n format(column, nested_id))\n return None\n return attr.pop(found)","function_tokens":["def","_delete_nested","(","self",",","column",",","nested_id",")",":","attr","=","getattr","(","self",",","column",")","log",".","debug","(","'Will delete {} with id {}'",".","format","(","column",",","nested_id",")",")","found","=","-","1","for","pos","in","xrange","(","0",",","len","(","attr",")",")",":","nested","=","attr","[","pos","]","current_id","=","str","(","getattr","(","nested",",","nested",".","_pkey",")",")","if","current_id","==","nested_id",":","found","=","pos","if","found","==","-","1",":","log",".","warn","(","'Nested object {}#{} not found for deletion'",".","format","(","column",",","nested_id",")",")","return","None","return","attr",".","pop","(","found",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py#L145-L159"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py","language":"python","identifier":"MixinCoreNested.create_nested","parameters":"(cls, values, kls)","argument_list":"","return_statement":"return nested","docstring":"Create nested objects in store format.","docstring_summary":"Create nested objects in store format.","docstring_tokens":["Create","nested","objects","in","store","format","."],"function":"def create_nested(cls, values, kls):\n \"\"\"Create nested objects in store format.\"\"\"\n nested = []\n for param in values:\n param.validate()\n attrs = param.to_primitive()\n if hasattr(kls, '_pkey'):\n # XXX default value not correctly handled\n attrs[getattr(kls, '_pkey')] = uuid.uuid4()\n nested.append(kls(**attrs))\n return nested","function_tokens":["def","create_nested","(","cls",",","values",",","kls",")",":","nested","=","[","]","for","param","in","values",":","param",".","validate","(",")","attrs","=","param",".","to_primitive","(",")","if","hasattr","(","kls",",","'_pkey'",")",":","# XXX default value not correctly handled","attrs","[","getattr","(","kls",",","'_pkey'",")","]","=","uuid",".","uuid4","(",")","nested",".","append","(","kls","(","*","*","attrs",")",")","return","nested"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/core\/mixin.py#L162-L172"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/helpers\/connection.py","language":"python","identifier":"connect_storage","parameters":"()","argument_list":"","return_statement":"","docstring":"Connect to storage engines.","docstring_summary":"Connect to storage engines.","docstring_tokens":["Connect","to","storage","engines","."],"function":"def connect_storage():\n \"\"\"Connect to storage engines.\"\"\"\n try:\n from cassandra.io.libevreactor import LibevConnection\n kwargs = {'connection_class': LibevConnection}\n except ImportError:\n kwargs = {}\n hosts = Configuration('global').get('cassandra.hosts')\n keyspace = Configuration('global').get('cassandra.keyspace')\n consistency = Configuration('global').get('cassandra.consistency_level')\n protocol = Configuration('global').get('cassandra.protocol_version')\n setup_cassandra(hosts, keyspace, consistency,\n lazy_connect=True,\n protocol_version=protocol,\n **kwargs)","function_tokens":["def","connect_storage","(",")",":","try",":","from","cassandra",".","io",".","libevreactor","import","LibevConnection","kwargs","=","{","'connection_class'",":","LibevConnection","}","except","ImportError",":","kwargs","=","{","}","hosts","=","Configuration","(","'global'",")",".","get","(","'cassandra.hosts'",")","keyspace","=","Configuration","(","'global'",")",".","get","(","'cassandra.keyspace'",")","consistency","=","Configuration","(","'global'",")",".","get","(","'cassandra.consistency_level'",")","protocol","=","Configuration","(","'global'",")",".","get","(","'cassandra.protocol_version'",")","setup_cassandra","(","hosts",",","keyspace",",","consistency",",","lazy_connect","=","True",",","protocol_version","=","protocol",",","*","*","kwargs",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/helpers\/connection.py#L9-L23"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/helpers\/connection.py","language":"python","identifier":"get_index_connection","parameters":"()","argument_list":"","return_statement":"return Elasticsearch(url)","docstring":"Return a connection to index store.","docstring_summary":"Return a connection to index store.","docstring_tokens":["Return","a","connection","to","index","store","."],"function":"def get_index_connection():\n \"\"\"Return a connection to index store.\"\"\"\n url = Configuration('global').get('elasticsearch.url')\n return Elasticsearch(url)","function_tokens":["def","get_index_connection","(",")",":","url","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.url'",")","return","Elasticsearch","(","url",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/helpers\/connection.py#L26-L29"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/helpers\/json.py","language":"python","identifier":"to_json","parameters":"(data)","argument_list":"","return_statement":"return json.dumps(data, cls=JSONEncoder)","docstring":"Helper to dump using correct encoder.","docstring_summary":"Helper to dump using correct encoder.","docstring_tokens":["Helper","to","dump","using","correct","encoder","."],"function":"def to_json(data):\n \"\"\"Helper to dump using correct encoder.\"\"\"\n return json.dumps(data, cls=JSONEncoder)","function_tokens":["def","to_json","(","data",")",":","return","json",".","dumps","(","data",",","cls","=","JSONEncoder",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/helpers\/json.py#L31-L33"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/helpers\/json.py","language":"python","identifier":"JSONEncoder.default","parameters":"(self, obj)","argument_list":"","return_statement":"return super(JSONEncoder, self).default(obj)","docstring":"Convert object to JSON encodable type.","docstring_summary":"Convert object to JSON encodable type.","docstring_tokens":["Convert","object","to","JSON","encodable","type","."],"function":"def default(self, obj):\n \"\"\"Convert object to JSON encodable type.\"\"\"\n if isinstance(obj, Decimal):\n return float(obj)\n if isinstance(obj, self._datetypes):\n return RFC3339Milli(obj)\n if isinstance(obj, UUID):\n return str(obj)\n return super(JSONEncoder, self).default(obj)","function_tokens":["def","default","(","self",",","obj",")",":","if","isinstance","(","obj",",","Decimal",")",":","return","float","(","obj",")","if","isinstance","(","obj",",","self",".","_datetypes",")",":","return","RFC3339Milli","(","obj",")","if","isinstance","(","obj",",","UUID",")",":","return","str","(","obj",")","return","super","(","JSONEncoder",",","self",")",".","default","(","obj",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/helpers\/json.py#L20-L28"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py","language":"python","identifier":"BaseModel.create","parameters":"(cls, **kwargs)","argument_list":"","return_statement":"return obj","docstring":"Create a new model record.","docstring_summary":"Create a new model record.","docstring_tokens":["Create","a","new","model","record","."],"function":"def create(cls, **kwargs):\n \"\"\"Create a new model record.\"\"\"\n attrs = {key: val for key, val in kwargs.items()\n if key in cls._columns}\n obj = super(BaseModel, cls).create(**attrs)\n if obj._index_class:\n extras = kwargs.get('_indexed_extra', {})\n obj.create_index(**extras)\n return obj","function_tokens":["def","create","(","cls",",","*","*","kwargs",")",":","attrs","=","{","key",":","val","for","key",",","val","in","kwargs",".","items","(",")","if","key","in","cls",".","_columns","}","obj","=","super","(","BaseModel",",","cls",")",".","create","(","*","*","attrs",")","if","obj",".","_index_class",":","extras","=","kwargs",".","get","(","'_indexed_extra'",",","{","}",")","obj",".","create_index","(","*","*","extras",")","return","obj"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py#L27-L35"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py","language":"python","identifier":"BaseModel.get","parameters":"(cls, **kwargs)","argument_list":"","return_statement":"","docstring":"Raise our exception when model not found.","docstring_summary":"Raise our exception when model not found.","docstring_tokens":["Raise","our","exception","when","model","not","found","."],"function":"def get(cls, **kwargs):\n \"\"\"Raise our exception when model not found.\"\"\"\n try:\n return super(BaseModel, cls).get(**kwargs)\n except DoesNotExist as exc:\n raise NotFound(exc)\n except:\n raise","function_tokens":["def","get","(","cls",",","*","*","kwargs",")",":","try",":","return","super","(","BaseModel",",","cls",")",".","get","(","*","*","kwargs",")","except","DoesNotExist","as","exc",":","raise","NotFound","(","exc",")","except",":","raise"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py#L38-L45"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py","language":"python","identifier":"BaseModel.filter","parameters":"(cls, **kwargs)","argument_list":"","return_statement":"return cls.objects.filter(**kwargs)","docstring":"Filter storable objects.","docstring_summary":"Filter storable objects.","docstring_tokens":["Filter","storable","objects","."],"function":"def filter(cls, **kwargs):\n \"\"\"Filter storable objects.\"\"\"\n return cls.objects.filter(**kwargs)","function_tokens":["def","filter","(","cls",",","*","*","kwargs",")",":","return","cls",".","objects",".","filter","(","*","*","kwargs",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py#L48-L50"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py","language":"python","identifier":"BaseModel.all","parameters":"(cls)","argument_list":"","return_statement":"return cls.objects.all()","docstring":"Return all storable objects.","docstring_summary":"Return all storable objects.","docstring_tokens":["Return","all","storable","objects","."],"function":"def all(cls):\n \"\"\"Return all storable objects.\"\"\"\n return cls.objects.all()","function_tokens":["def","all","(","cls",")",":","return","cls",".","objects",".","all","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py#L53-L55"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py","language":"python","identifier":"BaseIndexDocument.client","parameters":"(cls)","argument_list":"","return_statement":"return Elasticsearch(cls.__url__)","docstring":"Return an elasticsearch client.","docstring_summary":"Return an elasticsearch client.","docstring_tokens":["Return","an","elasticsearch","client","."],"function":"def client(cls):\n \"\"\"Return an elasticsearch client.\"\"\"\n return Elasticsearch(cls.__url__)","function_tokens":["def","client","(","cls",")",":","return","Elasticsearch","(","cls",".","__url__",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py#L65-L67"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py","language":"python","identifier":"BaseIndexDocument.create_mapping","parameters":"(cls, index_name)","argument_list":"","return_statement":"","docstring":"Create and save elasticsearch mapping for the cls.doc_type.","docstring_summary":"Create and save elasticsearch mapping for the cls.doc_type.","docstring_tokens":["Create","and","save","elasticsearch","mapping","for","the","cls",".","doc_type","."],"function":"def create_mapping(cls, index_name):\n \"\"\"Create and save elasticsearch mapping for the cls.doc_type.\"\"\"\n\n if hasattr(cls, 'build_mapping'):\n log.info('Create index {} mapping for doc_type {}'.\n format(index_name, cls.doc_type))\n try:\n cls.build_mapping().save(using=cls.client(), index=index_name)\n except Exception as exc:\n log.error(\"failed to put mapping for {} : {}\".\n format(index_name, exc))\n raise exc","function_tokens":["def","create_mapping","(","cls",",","index_name",")",":","if","hasattr","(","cls",",","'build_mapping'",")",":","log",".","info","(","'Create index {} mapping for doc_type {}'",".","format","(","index_name",",","cls",".","doc_type",")",")","try",":","cls",".","build_mapping","(",")",".","save","(","using","=","cls",".","client","(",")",",","index","=","index_name",")","except","Exception","as","exc",":","log",".","error","(","\"failed to put mapping for {} : {}\"",".","format","(","index_name",",","exc",")",")","raise","exc"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/model.py#L70-L81"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py","language":"python","identifier":"IndexedModelMixin.__process_udt","parameters":"(self, column, idx)","argument_list":"","return_statement":"","docstring":"Process a cassandra UDT column to translate into nested index.","docstring_summary":"Process a cassandra UDT column to translate into nested index.","docstring_tokens":["Process","a","cassandra","UDT","column","to","translate","into","nested","index","."],"function":"def __process_udt(self, column, idx):\n \"\"\"Process a cassandra UDT column to translate into nested index.\"\"\"\n\n def map_udt_attributes(item):\n ret = {}\n for col_name, col_value in item.items():\n if col_value is not None:\n if isinstance(col_value, (columns.UUID, uuid.UUID)):\n value = str(col_value)\n else:\n value = col_value\n ret[col_name] = value\n return ret\n\n attr_udt = getattr(self, column.column_name)\n if isinstance(attr_udt, list):\n udts = []\n for item in attr_udt:\n udts.append(map_udt_attributes(item))\n setattr(idx, column.column_name, udts)\n else:\n if attr_udt:\n setattr(idx, column.column_name, map_udt_attributes(attr_udt))","function_tokens":["def","__process_udt","(","self",",","column",",","idx",")",":","def","map_udt_attributes","(","item",")",":","ret","=","{","}","for","col_name",",","col_value","in","item",".","items","(",")",":","if","col_value","is","not","None",":","if","isinstance","(","col_value",",","(","columns",".","UUID",",","uuid",".","UUID",")",")",":","value","=","str","(","col_value",")","else",":","value","=","col_value","ret","[","col_name","]","=","value","return","ret","attr_udt","=","getattr","(","self",",","column",".","column_name",")","if","isinstance","(","attr_udt",",","list",")",":","udts","=","[","]","for","item","in","attr_udt",":","udts",".","append","(","map_udt_attributes","(","item",")",")","setattr","(","idx",",","column",".","column_name",",","udts",")","else",":","if","attr_udt",":","setattr","(","idx",",","column",".","column_name",",","map_udt_attributes","(","attr_udt",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py#L21-L43"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py","language":"python","identifier":"IndexedModelMixin._process_column","parameters":"(self, column, idx)","argument_list":"","return_statement":"","docstring":"Process a core column and translate into index document.","docstring_summary":"Process a core column and translate into index document.","docstring_tokens":["Process","a","core","column","and","translate","into","index","document","."],"function":"def _process_column(self, column, idx):\n \"\"\"Process a core column and translate into index document.\"\"\"\n col_name = column.column_name\n col_value = getattr(self, col_name)\n try:\n getattr(idx, col_name)\n except AttributeError:\n log.debug('No such column in index mapping {}'.\n format(column.column_name))\n return\n if isinstance(column, columns.List):\n is_udt = isinstance(column.sub_types[0], columns.UserDefinedType)\n if is_udt:\n self.__process_udt(column, idx)\n else:\n setattr(idx, col_name, col_value)\n elif isinstance(column, columns.UserDefinedType):\n self.__process_udt(column, idx)\n else:\n setattr(idx, col_name, col_value)","function_tokens":["def","_process_column","(","self",",","column",",","idx",")",":","col_name","=","column",".","column_name","col_value","=","getattr","(","self",",","col_name",")","try",":","getattr","(","idx",",","col_name",")","except","AttributeError",":","log",".","debug","(","'No such column in index mapping {}'",".","format","(","column",".","column_name",")",")","return","if","isinstance","(","column",",","columns",".","List",")",":","is_udt","=","isinstance","(","column",".","sub_types","[","0","]",",","columns",".","UserDefinedType",")","if","is_udt",":","self",".","__process_udt","(","column",",","idx",")","else",":","setattr","(","idx",",","col_name",",","col_value",")","elif","isinstance","(","column",",","columns",".","UserDefinedType",")",":","self",".","__process_udt","(","column",",","idx",")","else",":","setattr","(","idx",",","col_name",",","col_value",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py#L45-L64"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py","language":"python","identifier":"IndexedModelMixin.create_index","parameters":"(self, **extras)","argument_list":"","return_statement":"return True","docstring":"Translate a model object into an indexed document.","docstring_summary":"Translate a model object into an indexed document.","docstring_tokens":["Translate","a","model","object","into","an","indexed","document","."],"function":"def create_index(self, **extras):\n \"\"\"Translate a model object into an indexed document.\"\"\"\n if not self._index_class:\n return False\n idx = self._index_class()\n # XXX TODO TEMPORARY FIX\n # Design on core object did not follow correctly user.shard_id logic\n\n idx.meta.index = get_user_index(self.user_id)\n\n for name, desc in self._columns.items():\n if desc.is_primary_key:\n if name != 'user_id':\n idx.meta.id = getattr(self, name)\n else:\n self._process_column(desc, idx)\n else:\n self._process_column(desc, idx)\n for k, v in extras.items():\n setattr(idx, k, v)\n idx.save(using=idx.client())\n return True","function_tokens":["def","create_index","(","self",",","*","*","extras",")",":","if","not","self",".","_index_class",":","return","False","idx","=","self",".","_index_class","(",")","# XXX TODO TEMPORARY FIX","# Design on core object did not follow correctly user.shard_id logic","idx",".","meta",".","index","=","get_user_index","(","self",".","user_id",")","for","name",",","desc","in","self",".","_columns",".","items","(",")",":","if","desc",".","is_primary_key",":","if","name","!=","'user_id'",":","idx",".","meta",".","id","=","getattr","(","self",",","name",")","else",":","self",".","_process_column","(","desc",",","idx",")","else",":","self",".","_process_column","(","desc",",","idx",")","for","k",",","v","in","extras",".","items","(",")",":","setattr","(","idx",",","k",",","v",")","idx",".","save","(","using","=","idx",".","client","(",")",")","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py#L66-L87"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py","language":"python","identifier":"IndexedModelMixin.update_index","parameters":"(self, object_id, changed_columns)","argument_list":"","return_statement":"","docstring":"Update an existing index with a list of new values","docstring_summary":"Update an existing index with a list of new values","docstring_tokens":["Update","an","existing","index","with","a","list","of","new","values"],"function":"def update_index(self, object_id, changed_columns):\n \"\"\"Update an existing index with a list of new values\"\"\"\n\n idx = self._index_class()\n idx.meta.index = get_user_index(self.user_id)\n idx.meta.id = object_id\n\n update_doc = {}\n for name in changed_columns:\n if name == 'user_id':\n raise Exception('Can not change user_id column')\n column = self._columns[name]\n self._process_column(column, idx)\n update_doc[name] = getattr(idx, name)\n\n # serialize index doc keeping empty or None value\n out = {}\n for k, v in idx._d_.iteritems():\n try:\n f = idx._doc_type.mapping[k]\n if f._coerce:\n v = f.serialize(v)\n except KeyError:\n pass\n out[k] = v\n # XXX This method is no more used, deprecate it smoothly\n log.warning('Deprecation warning on IndexedModelMixin.update_index')\n idx.update(using=idx.client(), **out)","function_tokens":["def","update_index","(","self",",","object_id",",","changed_columns",")",":","idx","=","self",".","_index_class","(",")","idx",".","meta",".","index","=","get_user_index","(","self",".","user_id",")","idx",".","meta",".","id","=","object_id","update_doc","=","{","}","for","name","in","changed_columns",":","if","name","==","'user_id'",":","raise","Exception","(","'Can not change user_id column'",")","column","=","self",".","_columns","[","name","]","self",".","_process_column","(","column",",","idx",")","update_doc","[","name","]","=","getattr","(","idx",",","name",")","# serialize index doc keeping empty or None value","out","=","{","}","for","k",",","v","in","idx",".","_d_",".","iteritems","(",")",":","try",":","f","=","idx",".","_doc_type",".","mapping","[","k","]","if","f",".","_coerce",":","v","=","f",".","serialize","(","v",")","except","KeyError",":","pass","out","[","k","]","=","v","# XXX This method is no more used, deprecate it smoothly","log",".","warning","(","'Deprecation warning on IndexedModelMixin.update_index'",")","idx",".","update","(","using","=","idx",".","client","(",")",",","*","*","out",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py#L89-L116"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py","language":"python","identifier":"IndexedModelMixin.search","parameters":"(cls, user, limit=None, offset=0,\n min_pi=0, max_pi=0, sort=None, **params)","argument_list":"","return_statement":"return resp","docstring":"Search in index using a dict parameter.","docstring_summary":"Search in index using a dict parameter.","docstring_tokens":["Search","in","index","using","a","dict","parameter","."],"function":"def search(cls, user, limit=None, offset=0,\n min_pi=0, max_pi=0, sort=None, **params):\n \"\"\"Search in index using a dict parameter.\"\"\"\n search = cls._index_class.search(using=cls._index_class.client(),\n index=user.shard_id)\n search.filter('term', user_id=user.user_id)\n for k, v in params.items():\n term = {k: v}\n search = search.filter('match', **term)\n if limit:\n search = search[offset:offset + limit]\n else:\n log.warn('Pagination not set for search query,'\n ' using default storage one')\n if sort:\n search = search.sort(sort)\n log.debug('Search is {}'.format(search.to_dict()))\n resp = search.execute()\n log.debug('Search result {}'.format(resp))\n # XXX This method is no more used, deprecate it smoothly\n log.warning('Deprecation warning on IndexedModelMixin.update_index')\n return resp","function_tokens":["def","search","(","cls",",","user",",","limit","=","None",",","offset","=","0",",","min_pi","=","0",",","max_pi","=","0",",","sort","=","None",",","*","*","params",")",":","search","=","cls",".","_index_class",".","search","(","using","=","cls",".","_index_class",".","client","(",")",",","index","=","user",".","shard_id",")","search",".","filter","(","'term'",",","user_id","=","user",".","user_id",")","for","k",",","v","in","params",".","items","(",")",":","term","=","{","k",":","v","}","search","=","search",".","filter","(","'match'",",","*","*","term",")","if","limit",":","search","=","search","[","offset",":","offset","+","limit","]","else",":","log",".","warn","(","'Pagination not set for search query,'","' using default storage one'",")","if","sort",":","search","=","search",".","sort","(","sort",")","log",".","debug","(","'Search is {}'",".","format","(","search",".","to_dict","(",")",")",")","resp","=","search",".","execute","(",")","log",".","debug","(","'Search result {}'",".","format","(","resp",")",")","# XXX This method is no more used, deprecate it smoothly","log",".","warning","(","'Deprecation warning on IndexedModelMixin.update_index'",")","return","resp"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.storage\/caliopen_storage\/store\/mixin.py#L119-L140"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/related.py","language":"python","identifier":"BaseUserRelatedCore.create","parameters":"(cls, user, resource_id, **kwargs)","argument_list":"","return_statement":"return cls(obj)","docstring":"Create a related user and resource entity.","docstring_summary":"Create a related user and resource entity.","docstring_tokens":["Create","a","related","user","and","resource","entity","."],"function":"def create(cls, user, resource_id, **kwargs):\n \"\"\"Create a related user and resource entity.\"\"\"\n obj = cls._model_class.create(user_id=user.user_id,\n resource_id=resource_id,\n **kwargs)\n return cls(obj)","function_tokens":["def","create","(","cls",",","user",",","resource_id",",","*","*","kwargs",")",":","obj","=","cls",".","_model_class",".","create","(","user_id","=","user",".","user_id",",","resource_id","=","resource_id",",","*","*","kwargs",")","return","cls","(","obj",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/related.py#L17-L22"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/related.py","language":"python","identifier":"BaseUserRelatedCore.get","parameters":"(cls, user, resource_id, value)","argument_list":"","return_statement":"","docstring":"Get a related entity.","docstring_summary":"Get a related entity.","docstring_tokens":["Get","a","related","entity","."],"function":"def get(cls, user, resource_id, value):\n \"\"\"Get a related entity.\"\"\"\n kwargs = {'user_id': user.user_id,\n 'resource_id': resource_id,\n cls._pkey_name: value}\n try:\n obj = cls._model_class.get(**kwargs)\n return cls(obj)\n except Exception as exc:\n log.exception('Unexpected error during retrieve of resource %s'\n % exc)\n return None","function_tokens":["def","get","(","cls",",","user",",","resource_id",",","value",")",":","kwargs","=","{","'user_id'",":","user",".","user_id",",","'resource_id'",":","resource_id",",","cls",".","_pkey_name",":","value","}","try",":","obj","=","cls",".","_model_class",".","get","(","*","*","kwargs",")","return","cls","(","obj",")","except","Exception","as","exc",":","log",".","exception","(","'Unexpected error during retrieve of resource %s'","%","exc",")","return","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/related.py#L25-L36"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/related.py","language":"python","identifier":"BaseUserRelatedCore.find","parameters":"(cls, user, resource_id, filters=None)","argument_list":"","return_statement":"return {'total': len(objs), 'data': [cls(x) for x in objs]}","docstring":"Find related object for an user and an given resource.","docstring_summary":"Find related object for an user and an given resource.","docstring_tokens":["Find","related","object","for","an","user","and","an","given","resource","."],"function":"def find(cls, user, resource_id, filters=None):\n \"\"\"Find related object for an user and an given resource.\"\"\"\n filters = filters if filters else {}\n filters.update({'user_id': user.user_id,\n 'resource_id': resource_id})\n q = cls._model_class.filter(**filters)\n if not filters:\n objs = q\n else:\n objs = q.filter(**filters)\n return {'total': len(objs), 'data': [cls(x) for x in objs]}","function_tokens":["def","find","(","cls",",","user",",","resource_id",",","filters","=","None",")",":","filters","=","filters","if","filters","else","{","}","filters",".","update","(","{","'user_id'",":","user",".","user_id",",","'resource_id'",":","resource_id","}",")","q","=","cls",".","_model_class",".","filter","(","*","*","filters",")","if","not","filters",":","objs","=","q","else",":","objs","=","q",".","filter","(","*","*","filters",")","return","{","'total'",":","len","(","objs",")",",","'data'",":","[","cls","(","x",")","for","x","in","objs","]","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/related.py#L39-L49"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/related.py","language":"python","identifier":"BaseUserRelatedCore.to_dict","parameters":"(self)","argument_list":"","return_statement":"return {col: getattr(self, col)\n for col in self._model_class._columns.keys()}","docstring":"Return a dict representation.","docstring_summary":"Return a dict representation.","docstring_tokens":["Return","a","dict","representation","."],"function":"def to_dict(self):\n \"\"\"Return a dict representation.\"\"\"\n return {col: getattr(self, col)\n for col in self._model_class._columns.keys()}","function_tokens":["def","to_dict","(","self",")",":","return","{","col",":","getattr","(","self",",","col",")","for","col","in","self",".","_model_class",".","_columns",".","keys","(",")","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/related.py#L51-L54"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/pubkey.py","language":"python","identifier":"PublicKey.find","parameters":"(cls, user, resource_id)","argument_list":"","return_statement":"","docstring":"Get public keys for an user and a resource.","docstring_summary":"Get public keys for an user and a resource.","docstring_tokens":["Get","public","keys","for","an","user","and","a","resource","."],"function":"def find(cls, user, resource_id):\n \"\"\"Get public keys for an user and a resource.\"\"\"\n models = cls._model_class.filter(user_id=user.user_id,\n resource_id=resource_id)\n for m in models:\n yield cls(m)","function_tokens":["def","find","(","cls",",","user",",","resource_id",")",":","models","=","cls",".","_model_class",".","filter","(","user_id","=","user",".","user_id",",","resource_id","=","resource_id",")","for","m","in","models",":","yield","cls","(","m",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/pubkey.py#L18-L23"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/pubkey.py","language":"python","identifier":"PublicKey.create","parameters":"(cls, user, resource_id, resource_type, **kwargs)","argument_list":"","return_statement":"return cls(obj)","docstring":"Create a new public key related to an user and a resource.","docstring_summary":"Create a new public key related to an user and a resource.","docstring_tokens":["Create","a","new","public","key","related","to","an","user","and","a","resource","."],"function":"def create(cls, user, resource_id, resource_type, **kwargs):\n \"\"\"Create a new public key related to an user and a resource.\"\"\"\n if 'key_id' not in kwargs:\n kwargs['key_id'] = uuid.uuid4()\n obj = cls._model_class.create(user_id=user.user_id,\n resource_id=resource_id,\n resource_type=resource_type,\n **kwargs)\n return cls(obj)","function_tokens":["def","create","(","cls",",","user",",","resource_id",",","resource_type",",","*","*","kwargs",")",":","if","'key_id'","not","in","kwargs",":","kwargs","[","'key_id'","]","=","uuid",".","uuid4","(",")","obj","=","cls",".","_model_class",".","create","(","user_id","=","user",".","user_id",",","resource_id","=","resource_id",",","resource_type","=","resource_type",",","*","*","kwargs",")","return","cls","(","obj",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/pubkey.py#L26-L34"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py","language":"python","identifier":"BaseUserCore.user","parameters":"(self)","argument_list":"","return_statement":"return self._user","docstring":"Return user related to this object.","docstring_summary":"Return user related to this object.","docstring_tokens":["Return","user","related","to","this","object","."],"function":"def user(self):\n \"\"\"Return user related to this object.\"\"\"\n from caliopen_main.user.core import User\n\n if not self._user:\n self._user = User.get(self.user_id)\n return self._user","function_tokens":["def","user","(","self",")",":","from","caliopen_main",".","user",".","core","import","User","if","not","self",".","_user",":","self",".","_user","=","User",".","get","(","self",".","user_id",")","return","self",".","_user"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py#L13-L19"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py","language":"python","identifier":"BaseUserCore.get","parameters":"(cls, user, obj_id)","argument_list":"","return_statement":"","docstring":"Get a core object belong to user, with model related id.","docstring_summary":"Get a core object belong to user, with model related id.","docstring_tokens":["Get","a","core","object","belong","to","user","with","model","related","id","."],"function":"def get(cls, user, obj_id):\n \"\"\"Get a core object belong to user, with model related id.\"\"\"\n param = {cls._pkey_name: obj_id}\n obj = cls._model_class.get(user_id=user.user_id, **param)\n if obj:\n return cls(obj)\n raise NotFound('%s #%s not found for user %s' %\n (cls.__class__.name, obj_id, user.user_id))","function_tokens":["def","get","(","cls",",","user",",","obj_id",")",":","param","=","{","cls",".","_pkey_name",":","obj_id","}","obj","=","cls",".","_model_class",".","get","(","user_id","=","user",".","user_id",",","*","*","param",")","if","obj",":","return","cls","(","obj",")","raise","NotFound","(","'%s #%s not found for user %s'","%","(","cls",".","__class__",".","name",",","obj_id",",","user",".","user_id",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py#L22-L29"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py","language":"python","identifier":"BaseUserCore.get_by_user_id","parameters":"(cls, user_id, obj_id)","argument_list":"","return_statement":"","docstring":"Get a core object belong to user, with model related id.","docstring_summary":"Get a core object belong to user, with model related id.","docstring_tokens":["Get","a","core","object","belong","to","user","with","model","related","id","."],"function":"def get_by_user_id(cls, user_id, obj_id):\n \"\"\"Get a core object belong to user, with model related id.\"\"\"\n param = {cls._pkey_name: obj_id}\n obj = cls._model_class.get(user_id=user_id, **param)\n if obj:\n return cls(obj)\n raise NotFound('%s #%s not found for user %s' %\n (cls.__class__.name, obj_id, user_id))","function_tokens":["def","get_by_user_id","(","cls",",","user_id",",","obj_id",")",":","param","=","{","cls",".","_pkey_name",":","obj_id","}","obj","=","cls",".","_model_class",".","get","(","user_id","=","user_id",",","*","*","param",")","if","obj",":","return","cls","(","obj",")","raise","NotFound","(","'%s #%s not found for user %s'","%","(","cls",".","__class__",".","name",",","obj_id",",","user_id",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py#L32-L39"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py","language":"python","identifier":"BaseUserCore.find","parameters":"(cls, user, filters=None, limit=None, offset=0, count=False)","argument_list":"","return_statement":"return {'objects': [cls(x) for x in objs], 'total': len(q)}","docstring":"Find core objects that belong to an user.\n\n can only use columns part of primary key","docstring_summary":"Find core objects that belong to an user.","docstring_tokens":["Find","core","objects","that","belong","to","an","user","."],"function":"def find(cls, user, filters=None, limit=None, offset=0, count=False):\n \"\"\"\n Find core objects that belong to an user.\n\n can only use columns part of primary key\n \"\"\"\n q = cls._model_class.filter(user_id=user.user_id)\n if not filters:\n objs = q\n else:\n objs = q.filter(**filters)\n if count:\n return objs.count()\n if limit or offset:\n objs = objs[offset:(limit + offset)]\n\n return {'objects': [cls(x) for x in objs], 'total': len(q)}","function_tokens":["def","find","(","cls",",","user",",","filters","=","None",",","limit","=","None",",","offset","=","0",",","count","=","False",")",":","q","=","cls",".","_model_class",".","filter","(","user_id","=","user",".","user_id",")","if","not","filters",":","objs","=","q","else",":","objs","=","q",".","filter","(","*","*","filters",")","if","count",":","return","objs",".","count","(",")","if","limit","or","offset",":","objs","=","objs","[","offset",":","(","limit","+","offset",")","]","return","{","'objects'",":","[","cls","(","x",")","for","x","in","objs","]",",","'total'",":","len","(","q",")","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py#L42-L58"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py","language":"python","identifier":"BaseUserCore.count","parameters":"(cls, user, filters=None)","argument_list":"","return_statement":"return cls.find(user, filters, count=True)","docstring":"Count core objects that belong to an user.","docstring_summary":"Count core objects that belong to an user.","docstring_tokens":["Count","core","objects","that","belong","to","an","user","."],"function":"def count(cls, user, filters=None):\n \"\"\"Count core objects that belong to an user.\"\"\"\n return cls.find(user, filters, count=True)","function_tokens":["def","count","(","cls",",","user",",","filters","=","None",")",":","return","cls",".","find","(","user",",","filters",",","count","=","True",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py#L61-L63"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py","language":"python","identifier":"BaseUserCore.create","parameters":"(cls, user, **attrs)","argument_list":"","return_statement":"return cls(obj)","docstring":"Create a core object belong to an user.","docstring_summary":"Create a core object belong to an user.","docstring_tokens":["Create","a","core","object","belong","to","an","user","."],"function":"def create(cls, user, **attrs):\n \"\"\"Create a core object belong to an user.\"\"\"\n obj = cls._model_class.create(user_id=user.user_id, **attrs)\n return cls(obj)","function_tokens":["def","create","(","cls",",","user",",","*","*","attrs",")",":","obj","=","cls",".","_model_class",".","create","(","user_id","=","user",".","user_id",",","*","*","attrs",")","return","cls","(","obj",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py#L66-L69"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py","language":"python","identifier":"BaseUserCore.belongs_to_user","parameters":"(cls, user_id, object_id)","argument_list":"","return_statement":"return False","docstring":"Test if an object belong to an user.","docstring_summary":"Test if an object belong to an user.","docstring_tokens":["Test","if","an","object","belong","to","an","user","."],"function":"def belongs_to_user(cls, user_id, object_id):\n \"\"\"Test if an object belong to an user.\"\"\"\n param = {cls._pkey_name: object_id}\n obj = cls._model_class.get(user_id=user_id, **param)\n if obj:\n return True\n return False","function_tokens":["def","belongs_to_user","(","cls",",","user_id",",","object_id",")",":","param","=","{","cls",".","_pkey_name",":","object_id","}","obj","=","cls",".","_model_class",".","get","(","user_id","=","user_id",",","*","*","param",")","if","obj",":","return","True","return","False"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/core\/base.py#L72-L78"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"unmarshall_item","parameters":"(document, key, target_object, target_attr_type,\n is_creation)","argument_list":"","return_statement":"","docstring":"general function to cast a dict item (ie: document[key])\n into the corresponding target_object's attr (ie: target_object.key)\n\n :param document: source dict\n :param key: source dict key to unmarshall\n :param target_object: object to unmarshall document[key] into\n :param target_attr_type: the types.type of corresponding attr in target obj.\n :param is_creation: if true, we are in the context of the creation of an obj\n :return: nothing, target object is modified in-place","docstring_summary":"general function to cast a dict item (ie: document[key])\n into the corresponding target_object's attr (ie: target_object.key)","docstring_tokens":["general","function","to","cast","a","dict","item","(","ie",":","document","[","key","]",")","into","the","corresponding","target_object","s","attr","(","ie",":","target_object",".","key",")"],"function":"def unmarshall_item(document, key, target_object, target_attr_type,\n is_creation):\n \"\"\"\n general function to cast a dict item (ie: document[key])\n into the corresponding target_object's attr (ie: target_object.key)\n\n :param document: source dict\n :param key: source dict key to unmarshall\n :param target_object: object to unmarshall document[key] into\n :param target_attr_type: the types.type of corresponding attr in target obj.\n :param is_creation: if true, we are in the context of the creation of an obj\n :return: nothing, target object is modified in-place\n \"\"\"\n\n if isinstance(target_attr_type, list):\n lst = []\n if issubclass(target_attr_type[0], ObjectDictifiable):\n for item in document[key]:\n sub_obj = target_attr_type[0]()\n sub_obj.unmarshall_dict(item)\n if is_creation and isinstance(sub_obj, ObjectStorable):\n sub_obj.set_uuid()\n lst.append(sub_obj)\n elif issubclass(target_attr_type[0], uuid.UUID):\n for item in document[key]:\n sub_obj = uuid.UUID(str(item))\n lst.append(sub_obj)\n else:\n lst = document[key]\n setattr(target_object, key, lst)\n\n elif issubclass(target_attr_type, ObjectDictifiable):\n if hasattr(target_object, 'user'):\n opts = {'user': target_object.user}\n else:\n opts = {}\n sub_obj = target_attr_type(**opts)\n sub_obj.unmarshall_dict(document[key])\n setattr(target_object, key, sub_obj)\n\n elif issubclass(target_attr_type, uuid.UUID):\n setattr(target_object, key, uuid.UUID(str(document[key])))\n\n elif issubclass(target_attr_type, datetime.datetime):\n if document[key] is not None \\\n and document[key].tzinfo is None:\n setattr(target_object, key, document[key].replace(tzinfo=\n pytz.utc))\n else:\n setattr(target_object, key, document[key])\n else:\n new_attr = document[key]\n if hasattr(target_attr_type, \"validate\"):\n new_attr = target_attr_type().validate(document[key])\n setattr(target_object, key, new_attr)","function_tokens":["def","unmarshall_item","(","document",",","key",",","target_object",",","target_attr_type",",","is_creation",")",":","if","isinstance","(","target_attr_type",",","list",")",":","lst","=","[","]","if","issubclass","(","target_attr_type","[","0","]",",","ObjectDictifiable",")",":","for","item","in","document","[","key","]",":","sub_obj","=","target_attr_type","[","0","]","(",")","sub_obj",".","unmarshall_dict","(","item",")","if","is_creation","and","isinstance","(","sub_obj",",","ObjectStorable",")",":","sub_obj",".","set_uuid","(",")","lst",".","append","(","sub_obj",")","elif","issubclass","(","target_attr_type","[","0","]",",","uuid",".","UUID",")",":","for","item","in","document","[","key","]",":","sub_obj","=","uuid",".","UUID","(","str","(","item",")",")","lst",".","append","(","sub_obj",")","else",":","lst","=","document","[","key","]","setattr","(","target_object",",","key",",","lst",")","elif","issubclass","(","target_attr_type",",","ObjectDictifiable",")",":","if","hasattr","(","target_object",",","'user'",")",":","opts","=","{","'user'",":","target_object",".","user","}","else",":","opts","=","{","}","sub_obj","=","target_attr_type","(","*","*","opts",")","sub_obj",".","unmarshall_dict","(","document","[","key","]",")","setattr","(","target_object",",","key",",","sub_obj",")","elif","issubclass","(","target_attr_type",",","uuid",".","UUID",")",":","setattr","(","target_object",",","key",",","uuid",".","UUID","(","str","(","document","[","key","]",")",")",")","elif","issubclass","(","target_attr_type",",","datetime",".","datetime",")",":","if","document","[","key","]","is","not","None","and","document","[","key","]",".","tzinfo","is","None",":","setattr","(","target_object",",","key",",","document","[","key","]",".","replace","(","tzinfo","=","pytz",".","utc",")",")","else",":","setattr","(","target_object",",","key",",","document","[","key","]",")","else",":","new_attr","=","document","[","key","]","if","hasattr","(","target_attr_type",",","\"validate\"",")",":","new_attr","=","target_attr_type","(",")",".","validate","(","document","[","key","]",")","setattr","(","target_object",",","key",",","new_attr",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L626-L680"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"CaliopenObject.keys","parameters":"(self)","argument_list":"","return_statement":"return [k for k in self._attrs if hasattr(self, k)]","docstring":"returns a list of current attributes","docstring_summary":"returns a list of current attributes","docstring_tokens":["returns","a","list","of","current","attributes"],"function":"def keys(self):\n \"\"\"returns a list of current attributes\"\"\"\n\n return [k for k in self._attrs if hasattr(self, k)]","function_tokens":["def","keys","(","self",")",":","return","[","k","for","k","in","self",".","_attrs","if","hasattr","(","self",",","k",")","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L63-L66"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"CaliopenObject.update_with","parameters":"(self, sibling)","argument_list":"","return_statement":"","docstring":"update self attributes with those from sibling\n\n\n returns a list of first level attributes that have been modified","docstring_summary":"update self attributes with those from sibling","docstring_tokens":["update","self","attributes","with","those","from","sibling"],"function":"def update_with(self, sibling):\n \"\"\"update self attributes with those from sibling\n\n\n returns a list of first level attributes that have been modified\n \"\"\"\n pass","function_tokens":["def","update_with","(","self",",","sibling",")",":","pass"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L68-L74"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectDictifiable.marshall_dict","parameters":"(self, **options)","argument_list":"","return_statement":"return self_dict","docstring":"output a dict representation of self 'public' attributes","docstring_summary":"output a dict representation of self 'public' attributes","docstring_tokens":["output","a","dict","representation","of","self","public","attributes"],"function":"def marshall_dict(self, **options):\n \"\"\"output a dict representation of self 'public' attributes\"\"\"\n\n self_dict = {}\n for att, val in vars(self).items():\n if not att.startswith(\"_\") and val is not None:\n if isinstance(self._attrs[att], types.ListType):\n lst = []\n if len(att) > 0:\n if issubclass(self._attrs[att][0], ObjectDictifiable):\n for item in val:\n lst.append(item.marshall_dict())\n else:\n lst = val\n self_dict[att] = lst\n else:\n self_dict[att] = lst\n elif issubclass(self._attrs[att], ObjectDictifiable):\n self_dict[att] = val.marshall_dict()\n else:\n self_dict[att] = val\n\n return self_dict","function_tokens":["def","marshall_dict","(","self",",","*","*","options",")",":","self_dict","=","{","}","for","att",",","val","in","vars","(","self",")",".","items","(",")",":","if","not","att",".","startswith","(","\"_\"",")","and","val","is","not","None",":","if","isinstance","(","self",".","_attrs","[","att","]",",","types",".","ListType",")",":","lst","=","[","]","if","len","(","att",")",">","0",":","if","issubclass","(","self",".","_attrs","[","att","]","[","0","]",",","ObjectDictifiable",")",":","for","item","in","val",":","lst",".","append","(","item",".","marshall_dict","(",")",")","else",":","lst","=","val","self_dict","[","att","]","=","lst","else",":","self_dict","[","att","]","=","lst","elif","issubclass","(","self",".","_attrs","[","att","]",",","ObjectDictifiable",")",":","self_dict","[","att","]","=","val",".","marshall_dict","(",")","else",":","self_dict","[","att","]","=","val","return","self_dict"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L81-L103"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectDictifiable.unmarshall_dict","parameters":"(self, document, **options)","argument_list":"","return_statement":"","docstring":"squash self.attrs with dict input document\n\n all self.attrs are reset if not in document","docstring_summary":"squash self.attrs with dict input document","docstring_tokens":["squash","self",".","attrs","with","dict","input","document"],"function":"def unmarshall_dict(self, document, **options):\n \"\"\"squash self.attrs with dict input document\n\n all self.attrs are reset if not in document\n \"\"\"\n for attr, attrtype in self._attrs.items():\n if attr in document and document[attr] is not None:\n unmarshall_item(document, attr, self, attrtype,\n is_creation=False)\n else:\n if isinstance(attrtype, types.ListType):\n setattr(self, attr, [])\n elif issubclass(attrtype, types.DictType):\n setattr(self, attr, {})\n elif issubclass(attrtype, types.BooleanType):\n setattr(self, attr, False)\n elif issubclass(attrtype, types.StringType):\n setattr(self, attr, \"\")\n elif issubclass(attrtype, types.IntType):\n setattr(self, attr, 0)\n else:\n setattr(self, attr, None)","function_tokens":["def","unmarshall_dict","(","self",",","document",",","*","*","options",")",":","for","attr",",","attrtype","in","self",".","_attrs",".","items","(",")",":","if","attr","in","document","and","document","[","attr","]","is","not","None",":","unmarshall_item","(","document",",","attr",",","self",",","attrtype",",","is_creation","=","False",")","else",":","if","isinstance","(","attrtype",",","types",".","ListType",")",":","setattr","(","self",",","attr",",","[","]",")","elif","issubclass","(","attrtype",",","types",".","DictType",")",":","setattr","(","self",",","attr",",","{","}",")","elif","issubclass","(","attrtype",",","types",".","BooleanType",")",":","setattr","(","self",",","attr",",","False",")","elif","issubclass","(","attrtype",",","types",".","StringType",")",":","setattr","(","self",",","attr",",","\"\"",")","elif","issubclass","(","attrtype",",","types",".","IntType",")",":","setattr","(","self",",","attr",",","0",")","else",":","setattr","(","self",",","attr",",","None",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L105-L126"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectJsonDictifiable.unmarshall_json_dict","parameters":"(self, document, **options)","argument_list":"","return_statement":"","docstring":"TODO: handle conversion of basic json type into obj. types","docstring_summary":"TODO: handle conversion of basic json type into obj. types","docstring_tokens":["TODO",":","handle","conversion","of","basic","json","type","into","obj",".","types"],"function":"def unmarshall_json_dict(self, document, **options):\n \"\"\" TODO: handle conversion of basic json type into obj. types\"\"\"\n\n # validate document against json_model before trying to unmarshal\n valid_doc = self._json_model(document)\n try:\n valid_doc.validate()\n except Exception as exc:\n log.warn(\"document validation failed with error {}\".format(exc))\n raise exc\n\n self.unmarshall_dict(document, **options)","function_tokens":["def","unmarshall_json_dict","(","self",",","document",",","*","*","options",")",":","# validate document against json_model before trying to unmarshal","valid_doc","=","self",".","_json_model","(","document",")","try",":","valid_doc",".","validate","(",")","except","Exception","as","exc",":","log",".","warn","(","\"document validation failed with error {}\"",".","format","(","exc",")",")","raise","exc","self",".","unmarshall_dict","(","document",",","*","*","options",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L148-L159"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectUser.marshall_dict","parameters":"(self, **options)","argument_list":"","return_statement":"return self_dict","docstring":"output a dict representation of self 'public' attributes","docstring_summary":"output a dict representation of self 'public' attributes","docstring_tokens":["output","a","dict","representation","of","self","public","attributes"],"function":"def marshall_dict(self, **options):\n \"\"\"output a dict representation of self 'public' attributes\"\"\"\n\n self_dict = {}\n for att, val in vars(self).items():\n if not att.startswith(\"_\") and val is not None and att != 'user':\n if isinstance(self._attrs[att], types.ListType):\n lst = []\n if len(att) > 0:\n if issubclass(self._attrs[att][0], ObjectDictifiable):\n for item in val:\n lst.append(item.marshall_dict())\n else:\n lst = val\n self_dict[att] = lst\n else:\n self_dict[att] = lst\n elif issubclass(self._attrs[att], ObjectDictifiable):\n self_dict[att] = val.marshall_dict()\n else:\n self_dict[att] = val\n\n return self_dict","function_tokens":["def","marshall_dict","(","self",",","*","*","options",")",":","self_dict","=","{","}","for","att",",","val","in","vars","(","self",")",".","items","(",")",":","if","not","att",".","startswith","(","\"_\"",")","and","val","is","not","None","and","att","!=","'user'",":","if","isinstance","(","self",".","_attrs","[","att","]",",","types",".","ListType",")",":","lst","=","[","]","if","len","(","att",")",">","0",":","if","issubclass","(","self",".","_attrs","[","att","]","[","0","]",",","ObjectDictifiable",")",":","for","item","in","val",":","lst",".","append","(","item",".","marshall_dict","(",")",")","else",":","lst","=","val","self_dict","[","att","]","=","lst","else",":","self_dict","[","att","]","=","lst","elif","issubclass","(","self",".","_attrs","[","att","]",",","ObjectDictifiable",")",":","self_dict","[","att","]","=","val",".","marshall_dict","(",")","else",":","self_dict","[","att","]","=","val","return","self_dict"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L282-L304"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectUser.list_db","parameters":"(cls, user)","argument_list":"","return_statement":"return objects","docstring":"List all objects that belong to an user.","docstring_summary":"List all objects that belong to an user.","docstring_tokens":["List","all","objects","that","belong","to","an","user","."],"function":"def list_db(cls, user):\n \"\"\"List all objects that belong to an user.\"\"\"\n models = cls._model_class.filter(user_id=user.user_id)\n objects = []\n for model in models:\n obj = cls(user)\n obj._db = model\n obj.unmarshall_db()\n objects.append(obj)\n return objects","function_tokens":["def","list_db","(","cls",",","user",")",":","models","=","cls",".","_model_class",".","filter","(","user_id","=","user",".","user_id",")","objects","=","[","]","for","model","in","models",":","obj","=","cls","(","user",")","obj",".","_db","=","model","obj",".","unmarshall_db","(",")","objects",".","append","(","obj",")","return","objects"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L307-L316"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectUser.get_db","parameters":"(self, **options)","argument_list":"","return_statement":"","docstring":"Get an object belonging to an user and put it in self._db attrs","docstring_summary":"Get an object belonging to an user and put it in self._db attrs","docstring_tokens":["Get","an","object","belonging","to","an","user","and","put","it","in","self",".","_db","attrs"],"function":"def get_db(self, **options):\n \"\"\"Get an object belonging to an user and put it in self._db attrs\"\"\"\n if self._pkey_name:\n param = {\n self._pkey_name: getattr(self, self._pkey_name)\n }\n else:\n param = {}\n\n try:\n self._db = self._model_class.get(user_id=self.user_id, **param)\n except NotFound:\n raise NotFound('%s %s not found for user %s' %\n (self.__class__.__name__,\n param[self._pkey_name], self.user_id))","function_tokens":["def","get_db","(","self",",","*","*","options",")",":","if","self",".","_pkey_name",":","param","=","{","self",".","_pkey_name",":","getattr","(","self",",","self",".","_pkey_name",")","}","else",":","param","=","{","}","try",":","self",".","_db","=","self",".","_model_class",".","get","(","user_id","=","self",".","user_id",",","*","*","param",")","except","NotFound",":","raise","NotFound","(","'%s %s not found for user %s'","%","(","self",".","__class__",".","__name__",",","param","[","self",".","_pkey_name","]",",","self",".","user_id",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L318-L332"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectUser.apply_patch","parameters":"(self, patch, **options)","argument_list":"","return_statement":"","docstring":"Update self attributes with patch rfc7396 and Caliopen's specifications\n if, and only if, patch is consistent with current obj db instance\n\n :param patch: json-dict object describing the patch to apply\n with a \"current_state\" key. see caliopen rfc for explanation\n :param options: whether patch should be propagated to db and\/or index\n :return: Exception or None","docstring_summary":"Update self attributes with patch rfc7396 and Caliopen's specifications\n if, and only if, patch is consistent with current obj db instance","docstring_tokens":["Update","self","attributes","with","patch","rfc7396","and","Caliopen","s","specifications","if","and","only","if","patch","is","consistent","with","current","obj","db","instance"],"function":"def apply_patch(self, patch, **options):\n \"\"\"\n Update self attributes with patch rfc7396 and Caliopen's specifications\n if, and only if, patch is consistent with current obj db instance\n\n :param patch: json-dict object describing the patch to apply\n with a \"current_state\" key. see caliopen rfc for explanation\n :param options: whether patch should be propagated to db and\/or index\n :return: Exception or None\n \"\"\"\n if patch is None or \"current_state\" not in patch:\n raise PatchUnprocessable(message='Invalid patch')\n\n patch_current = patch.pop(\"current_state\")\n\n # build 3 siblings : 2 from patch and last one from db\n obj_patch_new = self.__class__(user_id=self.user_id)\n obj_patch_old = self.__class__(user_id=self.user_id)\n try:\n obj_patch_new.unmarshall_json_dict(patch)\n except Exception as exc:\n log.exception(exc)\n raise PatchUnprocessable(message=\"unmarshall patch \"\n \"error: %r\" % exc)\n try:\n obj_patch_old.unmarshall_json_dict(patch_current)\n except Exception as exc:\n log.exception(exc)\n raise PatchUnprocessable(message=\"unmarshall current \"\n \"patch error: %r\" % exc)\n self.get_db()\n\n # TODO : manage protected attributes, to prevent patch on them\n if \"tags\" in patch.keys():\n raise ForbiddenAction(\n message=\"patching tags through parent object is forbidden\")\n\n # check if patch is consistent with db current state\n # if it is, squash self attributes\n self.unmarshall_db()\n\n for key in patch.keys():\n current_attr = self._attrs[key]\n try:\n self._check_key_consistency(current_attr, key,\n obj_patch_old,\n obj_patch_new)\n except Exception as exc:\n log.exception(\"key consistency checking failed: {}\".\n format(exc))\n raise exc\n\n # all controls passed, we can actually set the new attribute\n create_sub_object = False\n if key not in patch_current.keys():\n create_sub_object = True\n else:\n if patch_current[key] in (None, [], {}):\n create_sub_object = True\n if isinstance(patch_current[key], list) and len(\n patch[key]) > len(patch_current[key]):\n create_sub_object = True\n\n if patch[key] is not None:\n unmarshall_item(patch, key, self, self._attrs[key],\n create_sub_object)\n\n if \"db\" in options and options[\"db\"] is True:\n # apply changes to db model and update db\n if \"with_validation\" in options and options[\n \"with_validation\"] is True:\n d = self.marshall_dict()\n try:\n self._json_model(d).validate()\n except Exception as exc:\n log.exception(\"document is not valid: {}\".format(exc))\n raise PatchUnprocessable(\n message=\"document is not valid,\"\n \" can't insert it into db: <{}>\".format(exc))\n\n self.marshall_db()\n try:\n self.update_db()\n except Exception as exc:\n log.exception(exc)\n raise PatchError(message=\"Error when updating db\")","function_tokens":["def","apply_patch","(","self",",","patch",",","*","*","options",")",":","if","patch","is","None","or","\"current_state\"","not","in","patch",":","raise","PatchUnprocessable","(","message","=","'Invalid patch'",")","patch_current","=","patch",".","pop","(","\"current_state\"",")","# build 3 siblings : 2 from patch and last one from db","obj_patch_new","=","self",".","__class__","(","user_id","=","self",".","user_id",")","obj_patch_old","=","self",".","__class__","(","user_id","=","self",".","user_id",")","try",":","obj_patch_new",".","unmarshall_json_dict","(","patch",")","except","Exception","as","exc",":","log",".","exception","(","exc",")","raise","PatchUnprocessable","(","message","=","\"unmarshall patch \"","\"error: %r\"","%","exc",")","try",":","obj_patch_old",".","unmarshall_json_dict","(","patch_current",")","except","Exception","as","exc",":","log",".","exception","(","exc",")","raise","PatchUnprocessable","(","message","=","\"unmarshall current \"","\"patch error: %r\"","%","exc",")","self",".","get_db","(",")","# TODO : manage protected attributes, to prevent patch on them","if","\"tags\"","in","patch",".","keys","(",")",":","raise","ForbiddenAction","(","message","=","\"patching tags through parent object is forbidden\"",")","# check if patch is consistent with db current state","# if it is, squash self attributes","self",".","unmarshall_db","(",")","for","key","in","patch",".","keys","(",")",":","current_attr","=","self",".","_attrs","[","key","]","try",":","self",".","_check_key_consistency","(","current_attr",",","key",",","obj_patch_old",",","obj_patch_new",")","except","Exception","as","exc",":","log",".","exception","(","\"key consistency checking failed: {}\"",".","format","(","exc",")",")","raise","exc","# all controls passed, we can actually set the new attribute","create_sub_object","=","False","if","key","not","in","patch_current",".","keys","(",")",":","create_sub_object","=","True","else",":","if","patch_current","[","key","]","in","(","None",",","[","]",",","{","}",")",":","create_sub_object","=","True","if","isinstance","(","patch_current","[","key","]",",","list",")","and","len","(","patch","[","key","]",")",">","len","(","patch_current","[","key","]",")",":","create_sub_object","=","True","if","patch","[","key","]","is","not","None",":","unmarshall_item","(","patch",",","key",",","self",",","self",".","_attrs","[","key","]",",","create_sub_object",")","if","\"db\"","in","options","and","options","[","\"db\"","]","is","True",":","# apply changes to db model and update db","if","\"with_validation\"","in","options","and","options","[","\"with_validation\"","]","is","True",":","d","=","self",".","marshall_dict","(",")","try",":","self",".","_json_model","(","d",")",".","validate","(",")","except","Exception","as","exc",":","log",".","exception","(","\"document is not valid: {}\"",".","format","(","exc",")",")","raise","PatchUnprocessable","(","message","=","\"document is not valid,\"","\" can't insert it into db: <{}>\"",".","format","(","exc",")",")","self",".","marshall_db","(",")","try",":","self",".","update_db","(",")","except","Exception","as","exc",":","log",".","exception","(","exc",")","raise","PatchError","(","message","=","\"Error when updating db\"",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L334-L419"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectUser._check_key_consistency","parameters":"(self, current_attr, key, obj_patch_old,\n patch_current)","argument_list":"","return_statement":"","docstring":"check if a key provided in patch is consistent with current state","docstring_summary":"check if a key provided in patch is consistent with current state","docstring_tokens":["check","if","a","key","provided","in","patch","is","consistent","with","current","state"],"function":"def _check_key_consistency(self, current_attr, key, obj_patch_old,\n patch_current):\n \"\"\"\n check if a key provided in patch is consistent with current state\n\n \"\"\"\n\n if key not in self._attrs.keys():\n raise PatchUnprocessable(\n message=\"unknown key in patch\")\n old_val = getattr(obj_patch_old, key)\n cur_val = getattr(self, key)\n msg = \"Patch current_state not consistent with db, step {} key {}\"\n\n if isinstance(current_attr, types.ListType):\n if not isinstance(cur_val, types.ListType):\n raise PatchConflict(\n messag=msg.format(0, key))\n\n if key not in patch_current.keys():\n # means patch wants to add the key.\n # Value in db should be null or empty\n if cur_val not in (None, [], {}):\n raise PatchConflict(\n message=msg.format(0.5, key))\n else:\n if isinstance(current_attr, types.ListType):\n if old_val == [] and cur_val != []:\n raise PatchConflict(\n message=msg.format(1, key))\n if cur_val == [] and old_val != []:\n raise PatchConflict(\n message=msg.format(2, key))\n for old in old_val:\n for elem in cur_val:\n if issubclass(current_attr[0], CaliopenObject):\n if elem.__dict__ == old.__dict__:\n break\n else:\n if elem == old:\n break\n else:\n raise PatchConflict(\n message=msg.format(3, key))\n elif issubclass(self._attrs[key], types.DictType):\n if cmp(old_val, cur_val) != 0:\n raise PatchConflict(\n message=msg.format(4, key))\n else:\n # XXX ugly patch but else compare 2 distinct objects\n # and not their representation\n if hasattr(old_val, 'marshall_dict') and \\\n hasattr(cur_val, 'marshall_dict'):\n old_val = old_val.marshall_dict()\n cur_val = cur_val.marshall_dict()\n if old_val != cur_val:\n raise PatchConflict(\n message=msg.format(5, key))","function_tokens":["def","_check_key_consistency","(","self",",","current_attr",",","key",",","obj_patch_old",",","patch_current",")",":","if","key","not","in","self",".","_attrs",".","keys","(",")",":","raise","PatchUnprocessable","(","message","=","\"unknown key in patch\"",")","old_val","=","getattr","(","obj_patch_old",",","key",")","cur_val","=","getattr","(","self",",","key",")","msg","=","\"Patch current_state not consistent with db, step {} key {}\"","if","isinstance","(","current_attr",",","types",".","ListType",")",":","if","not","isinstance","(","cur_val",",","types",".","ListType",")",":","raise","PatchConflict","(","messag","=","msg",".","format","(","0",",","key",")",")","if","key","not","in","patch_current",".","keys","(",")",":","# means patch wants to add the key.","# Value in db should be null or empty","if","cur_val","not","in","(","None",",","[","]",",","{","}",")",":","raise","PatchConflict","(","message","=","msg",".","format","(","0.5",",","key",")",")","else",":","if","isinstance","(","current_attr",",","types",".","ListType",")",":","if","old_val","==","[","]","and","cur_val","!=","[","]",":","raise","PatchConflict","(","message","=","msg",".","format","(","1",",","key",")",")","if","cur_val","==","[","]","and","old_val","!=","[","]",":","raise","PatchConflict","(","message","=","msg",".","format","(","2",",","key",")",")","for","old","in","old_val",":","for","elem","in","cur_val",":","if","issubclass","(","current_attr","[","0","]",",","CaliopenObject",")",":","if","elem",".","__dict__","==","old",".","__dict__",":","break","else",":","if","elem","==","old",":","break","else",":","raise","PatchConflict","(","message","=","msg",".","format","(","3",",","key",")",")","elif","issubclass","(","self",".","_attrs","[","key","]",",","types",".","DictType",")",":","if","cmp","(","old_val",",","cur_val",")","!=","0",":","raise","PatchConflict","(","message","=","msg",".","format","(","4",",","key",")",")","else",":","# XXX ugly patch but else compare 2 distinct objects","# and not their representation","if","hasattr","(","old_val",",","'marshall_dict'",")","and","hasattr","(","cur_val",",","'marshall_dict'",")",":","old_val","=","old_val",".","marshall_dict","(",")","cur_val","=","cur_val",".","marshall_dict","(",")","if","old_val","!=","cur_val",":","raise","PatchConflict","(","message","=","msg",".","format","(","5",",","key",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L421-L478"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectIndexable.get_index","parameters":"(self, **options)","argument_list":"","return_statement":"","docstring":"Get a doc from ES within user's index and put it at self._index","docstring_summary":"Get a doc from ES within user's index and put it at self._index","docstring_tokens":["Get","a","doc","from","ES","within","user","s","index","and","put","it","at","self",".","_index"],"function":"def get_index(self, **options):\n \"\"\"Get a doc from ES within user's index and put it at self._index\"\"\"\n\n obj_id = getattr(self, self._pkey_name)\n try:\n self._index = self._index_class.get(index=self.user.shard_id,\n id=obj_id,\n using=self._index_class.client())\n except Exception as exc:\n if isinstance(exc, ESexceptions.NotFoundError):\n log.exception(\"indexed doc not found\")\n self._index = None\n raise NotFound('%s #%s not found for user %s' %\n (self.__class__.__name__, obj_id, self.user_id))\n else:\n raise exc","function_tokens":["def","get_index","(","self",",","*","*","options",")",":","obj_id","=","getattr","(","self",",","self",".","_pkey_name",")","try",":","self",".","_index","=","self",".","_index_class",".","get","(","index","=","self",".","user",".","shard_id",",","id","=","obj_id",",","using","=","self",".","_index_class",".","client","(",")",")","except","Exception","as","exc",":","if","isinstance","(","exc",",","ESexceptions",".","NotFoundError",")",":","log",".","exception","(","\"indexed doc not found\"",")","self",".","_index","=","None","raise","NotFound","(","'%s #%s not found for user %s'","%","(","self",".","__class__",".","__name__",",","obj_id",",","self",".","user_id",")",")","else",":","raise","exc"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L487-L502"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectIndexable.create_index","parameters":"(self, **options)","argument_list":"","return_statement":"","docstring":"Create indexed document from current self._index state","docstring_summary":"Create indexed document from current self._index state","docstring_tokens":["Create","indexed","document","from","current","self",".","_index","state"],"function":"def create_index(self, **options):\n \"\"\"Create indexed document from current self._index state\"\"\"\n\n self.marshall_index()\n self.save_index()","function_tokens":["def","create_index","(","self",",","*","*","options",")",":","self",".","marshall_index","(",")","self",".","save_index","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L511-L515"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectIndexable.update_index","parameters":"(self, wait_for=False, **options)","argument_list":"","return_statement":"","docstring":"get indexed doc from elastic and update it with self attrs\n\n if indexed doc doesn't exist, create it\n else update changed fields only","docstring_summary":"get indexed doc from elastic and update it with self attrs","docstring_tokens":["get","indexed","doc","from","elastic","and","update","it","with","self","attrs"],"function":"def update_index(self, wait_for=False, **options):\n \"\"\"get indexed doc from elastic and update it with self attrs\n\n if indexed doc doesn't exist, create it\n else update changed fields only\n \"\"\"\n self.get_index()\n if self._index is not None:\n try:\n update_dict = self.marshall_index(update=True)\n if wait_for:\n self._index.update(using=self._index_class.client(),\n refresh=\"wait_for\",\n **update_dict)\n else:\n self._index.update(using=self._index_class.client(),\n **update_dict)\n except Exception as exc:\n log.exception(\"update index failed: {}\".format(exc))\n\n else:\n # for some reasons, index doc not found... create one from scratch\n self.create_index()","function_tokens":["def","update_index","(","self",",","wait_for","=","False",",","*","*","options",")",":","self",".","get_index","(",")","if","self",".","_index","is","not","None",":","try",":","update_dict","=","self",".","marshall_index","(","update","=","True",")","if","wait_for",":","self",".","_index",".","update","(","using","=","self",".","_index_class",".","client","(",")",",","refresh","=","\"wait_for\"",",","*","*","update_dict",")","else",":","self",".","_index",".","update","(","using","=","self",".","_index_class",".","client","(",")",",","*","*","update_dict",")","except","Exception","as","exc",":","log",".","exception","(","\"update index failed: {}\"",".","format","(","exc",")",")","else",":","# for some reasons, index doc not found... create one from scratch","self",".","create_index","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L527-L549"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectIndexable.marshall_index","parameters":"(self, **options)","argument_list":"","return_statement":"","docstring":"squash self._index with self 'public' attributes\n\n options:\n update=True : only changed values will be replace in self._index\n and a dict with changed applied will be returned","docstring_summary":"squash self._index with self 'public' attributes","docstring_tokens":["squash","self",".","_index","with","self","public","attributes"],"function":"def marshall_index(self, **options):\n \"\"\"squash self._index with self 'public' attributes\n\n options:\n update=True : only changed values will be replace in self._index\n and a dict with changed applied will be returned\n \"\"\"\n\n # TODO : manage protected attrs (ie attributes that user should not be able to change directly)\n\n update = False\n\n if \"update\" in options and options[\"update\"] is True:\n update = True\n # index_sibling is instanciated with self._index values to perform\n # object comparaison\n index_sibling = self.__class__(user=self.user)\n index_sibling._index = self._index\n\n index_sibling.unmarshall_index()\n if not isinstance(self._index, self._index_class):\n self._index = self._index_class()\n self._index.meta.index = self.user.shard_id\n self._index.meta.using = self._index.client()\n self._index.meta.id = getattr(self, self._pkey_name)\n\n # update_sibling is an empty sibling that will be filled\n # with attributes from self\n update_sibling = self.__class__(user=self.user)\n m = self._index._doc_type.mapping.to_dict()\n for att in m[self._index._doc_type.name][\"properties\"]:\n if not att.startswith(\"_\") and att in index_sibling.keys():\n if update:\n if getattr(self, att) != getattr(index_sibling, att):\n setattr(update_sibling, att, getattr(self, att))\n else:\n delattr(update_sibling, att)\n else:\n setattr(update_sibling, att, getattr(self, att))\n\n update_dict = update_sibling.marshall_dict()\n for k, v in update_dict.iteritems():\n if k in self._index_class.__dict__:\n # do not try to set a property directly\n if not isinstance(getattr(self._index_class, k), property):\n setattr(self._index, k, v)\n else:\n setattr(self._index, k, v)\n\n if update:\n return update_sibling.marshall_dict()","function_tokens":["def","marshall_index","(","self",",","*","*","options",")",":","# TODO : manage protected attrs (ie attributes that user should not be able to change directly)","update","=","False","if","\"update\"","in","options","and","options","[","\"update\"","]","is","True",":","update","=","True","# index_sibling is instanciated with self._index values to perform","# object comparaison","index_sibling","=","self",".","__class__","(","user","=","self",".","user",")","index_sibling",".","_index","=","self",".","_index","index_sibling",".","unmarshall_index","(",")","if","not","isinstance","(","self",".","_index",",","self",".","_index_class",")",":","self",".","_index","=","self",".","_index_class","(",")","self",".","_index",".","meta",".","index","=","self",".","user",".","shard_id","self",".","_index",".","meta",".","using","=","self",".","_index",".","client","(",")","self",".","_index",".","meta",".","id","=","getattr","(","self",",","self",".","_pkey_name",")","# update_sibling is an empty sibling that will be filled","# with attributes from self","update_sibling","=","self",".","__class__","(","user","=","self",".","user",")","m","=","self",".","_index",".","_doc_type",".","mapping",".","to_dict","(",")","for","att","in","m","[","self",".","_index",".","_doc_type",".","name","]","[","\"properties\"","]",":","if","not","att",".","startswith","(","\"_\"",")","and","att","in","index_sibling",".","keys","(",")",":","if","update",":","if","getattr","(","self",",","att",")","!=","getattr","(","index_sibling",",","att",")",":","setattr","(","update_sibling",",","att",",","getattr","(","self",",","att",")",")","else",":","delattr","(","update_sibling",",","att",")","else",":","setattr","(","update_sibling",",","att",",","getattr","(","self",",","att",")",")","update_dict","=","update_sibling",".","marshall_dict","(",")","for","k",",","v","in","update_dict",".","iteritems","(",")",":","if","k","in","self",".","_index_class",".","__dict__",":","# do not try to set a property directly","if","not","isinstance","(","getattr","(","self",".","_index_class",",","k",")",",","property",")",":","setattr","(","self",".","_index",",","k",",","v",")","else",":","setattr","(","self",".","_index",",","k",",","v",")","if","update",":","return","update_sibling",".","marshall_dict","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L551-L601"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py","language":"python","identifier":"ObjectIndexable.unmarshall_index","parameters":"(self, **options)","argument_list":"","return_statement":"","docstring":"squash self.attrs with index representation","docstring_summary":"squash self.attrs with index representation","docstring_tokens":["squash","self",".","attrs","with","index","representation"],"function":"def unmarshall_index(self, **options):\n \"\"\"squash self.attrs with index representation\"\"\"\n if isinstance(self._index, self._index_class):\n self.unmarshall_dict(self._index.to_dict())","function_tokens":["def","unmarshall_index","(","self",",","*","*","options",")",":","if","isinstance","(","self",".","_index",",","self",".","_index_class",")",":","self",".","unmarshall_dict","(","self",".","_index",".","to_dict","(",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/objects\/base.py#L603-L606"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/helpers\/normalize.py","language":"python","identifier":"clean_email_address","parameters":"(addr)","argument_list":"","return_statement":"return (u'%s@%s' % (name, domain), email)","docstring":"Clean an email address for user resolve.","docstring_summary":"Clean an email address for user resolve.","docstring_tokens":["Clean","an","email","address","for","user","resolve","."],"function":"def clean_email_address(addr):\n \"\"\"Clean an email address for user resolve.\"\"\"\n try:\n real_name, email = parseaddr(addr.replace('\\r', ''))\n except UnicodeError:\n addr = addr.decode('utf-8', errors='ignore')\n real_name, email = parseaddr(addr.replace('\\r', ''))\n err_msg = 'Invalid email address {}'.format(addr)\n if not email or '@' not in email:\n # Try something else\n log.info('Last chance email parsing for {}'.format(addr))\n matches = re.match('(.*)<(.*@.*)>', addr)\n if matches and matches.groups():\n real_name, email = matches.groups()\n else:\n log.warn(err_msg)\n return (\"\", \"\")\n name, domain = email.lower().split('@', 1)\n if '@' in domain:\n log.error(err_msg)\n return (\"\", \"\")\n if '+' in name:\n try:\n name, ext = name.split('+', 1)\n except Exception as exc:\n log.info(exc)\n # unicode everywhere\n return (u'%s@%s' % (name, domain), email)","function_tokens":["def","clean_email_address","(","addr",")",":","try",":","real_name",",","email","=","parseaddr","(","addr",".","replace","(","'\\r'",",","''",")",")","except","UnicodeError",":","addr","=","addr",".","decode","(","'utf-8'",",","errors","=","'ignore'",")","real_name",",","email","=","parseaddr","(","addr",".","replace","(","'\\r'",",","''",")",")","err_msg","=","'Invalid email address {}'",".","format","(","addr",")","if","not","email","or","'@'","not","in","email",":","# Try something else","log",".","info","(","'Last chance email parsing for {}'",".","format","(","addr",")",")","matches","=","re",".","match","(","'(.*)<(.*@.*)>'",",","addr",")","if","matches","and","matches",".","groups","(",")",":","real_name",",","email","=","matches",".","groups","(",")","else",":","log",".","warn","(","err_msg",")","return","(","\"\"",",","\"\"",")","name",",","domain","=","email",".","lower","(",")",".","split","(","'@'",",","1",")","if","'@'","in","domain",":","log",".","error","(","err_msg",")","return","(","\"\"",",","\"\"",")","if","'+'","in","name",":","try",":","name",",","ext","=","name",".","split","(","'+'",",","1",")","except","Exception","as","exc",":","log",".","info","(","exc",")","# unicode everywhere","return","(","u'%s@%s'","%","(","name",",","domain",")",",","email",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/helpers\/normalize.py#L14-L41"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/helpers\/normalize.py","language":"python","identifier":"parse_mastodon_url","parameters":"(url)","argument_list":"","return_statement":"return matches[0]","docstring":"extract username and domain from a mastodon account url\n in the format https:\/\/instance.tld\/@username\n\n :return: tuple (server, username)","docstring_summary":"extract username and domain from a mastodon account url\n in the format https:\/\/instance.tld\/@username","docstring_tokens":["extract","username","and","domain","from","a","mastodon","account","url","in","the","format","https",":","\/\/","instance",".","tld","\/","@username"],"function":"def parse_mastodon_url(url):\n \"\"\"extract username and domain from a mastodon account url\n in the format https:\/\/instance.tld\/@username\n\n :return: tuple (server, username)\n \"\"\"\n\n matches = re.findall(mastodon_url_regex, url)\n if len(matches) != 1 or len(matches[0]) != 2:\n # try legacy fallback\n matches = re.findall(mastodon_url_legacy_regex, url)\n if len(matches) != 1 or len(matches[0]) != 2:\n raise SyntaxError\n\n return matches[0]","function_tokens":["def","parse_mastodon_url","(","url",")",":","matches","=","re",".","findall","(","mastodon_url_regex",",","url",")","if","len","(","matches",")","!=","1","or","len","(","matches","[","0","]",")","!=","2",":","# try legacy fallback","matches","=","re",".","findall","(","mastodon_url_legacy_regex",",","url",")","if","len","(","matches",")","!=","1","or","len","(","matches","[","0","]",")","!=","2",":","raise","SyntaxError","return","matches","[","0","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/helpers\/normalize.py#L52-L66"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/helpers\/strings.py","language":"python","identifier":"unicode_truncate","parameters":"(s, length)","argument_list":"","return_statement":"return re.sub(\"([\\xf6-\\xf7][\\x80-\\xbf]{0,2}|[\\xe0-\\xef][\\x80-\\xbf]{0,1}\"\n \"|[\\xc0-\\xdf])$\", \"\", partial)","docstring":"Truncate string after `length` bytes less trailing unicode char.","docstring_summary":"Truncate string after `length` bytes less trailing unicode char.","docstring_tokens":["Truncate","string","after","length","bytes","less","trailing","unicode","char","."],"function":"def unicode_truncate(s, length):\n \"\"\"\"Truncate string after `length` bytes less trailing unicode char.\"\"\"\n if isinstance(s, str):\n s = s.decode(\"utf8\", 'ignore')\n\n partial = s[:length]\n return re.sub(\"([\\xf6-\\xf7][\\x80-\\xbf]{0,2}|[\\xe0-\\xef][\\x80-\\xbf]{0,1}\"\n \"|[\\xc0-\\xdf])$\", \"\", partial)","function_tokens":["def","unicode_truncate","(","s",",","length",")",":","if","isinstance","(","s",",","str",")",":","s","=","s",".","decode","(","\"utf8\"",",","'ignore'",")","partial","=","s","[",":","length","]","return","re",".","sub","(","\"([\\xf6-\\xf7][\\x80-\\xbf]{0,2}|[\\xe0-\\xef][\\x80-\\xbf]{0,1}\"","\"|[\\xc0-\\xdf])$\"",",","\"\"",",","partial",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/helpers\/strings.py#L11-L18"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/helpers\/strings.py","language":"python","identifier":"to_utf8","parameters":"(input, charset)","argument_list":"","return_statement":"","docstring":"Convert input string to utf-8 return input string if it fails.\n\n :param input: string\n :param charset: string\n :return: utf-8 string","docstring_summary":"Convert input string to utf-8 return input string if it fails.","docstring_tokens":["Convert","input","string","to","utf","-","8","return","input","string","if","it","fails","."],"function":"def to_utf8(input, charset):\n \"\"\"Convert input string to utf-8 return input string if it fails.\n\n :param input: string\n :param charset: string\n :return: utf-8 string\n \"\"\"\n if charset:\n matches = re.match('^charset.*\"(.*)\"', charset)\n if matches and matches.groups():\n charset = matches.groups()[0]\n try:\n return input.decode(charset, \"replace\"). \\\n encode(\"utf-8\", \"replace\")\n except UnicodeError as exc:\n log.warn(\"decoding <{}> string to utf-8 failed \"\n \"with error : {}\".format(input, exc))\n return input\n else:\n try:\n return input.decode(\"us-ascii\", \"replace\"). \\\n encode(\"utf-8\", \"replace\")\n except Exception as exc:\n log.warn(\"decoding <{}> string to utf-8 failed \"\n \"with error : {}\".format(bytes(input), exc))\n return input","function_tokens":["def","to_utf8","(","input",",","charset",")",":","if","charset",":","matches","=","re",".","match","(","'^charset.*\"(.*)\"'",",","charset",")","if","matches","and","matches",".","groups","(",")",":","charset","=","matches",".","groups","(",")","[","0","]","try",":","return","input",".","decode","(","charset",",","\"replace\"",")",".","encode","(","\"utf-8\"",",","\"replace\"",")","except","UnicodeError","as","exc",":","log",".","warn","(","\"decoding <{}> string to utf-8 failed \"","\"with error : {}\"",".","format","(","input",",","exc",")",")","return","input","else",":","try",":","return","input",".","decode","(","\"us-ascii\"",",","\"replace\"",")",".","encode","(","\"utf-8\"",",","\"replace\"",")","except","Exception","as","exc",":","log",".","warn","(","\"decoding <{}> string to utf-8 failed \"","\"with error : {}\"",".","format","(","bytes","(","input",")",",","exc",")",")","return","input"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/helpers\/strings.py#L21-L46"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py","language":"python","identifier":"DbIO.get_db","parameters":"(**options)","argument_list":"","return_statement":"","docstring":"Retreive object from db and place it in a _model_class instance","docstring_summary":"Retreive object from db and place it in a _model_class instance","docstring_tokens":["Retreive","object","from","db","and","place","it","in","a","_model_class","instance"],"function":"def get_db(**options):\n \"\"\"Retreive object from db and place it in a _model_class instance\"\"\"\n raise NotImplementedError","function_tokens":["def","get_db","(","*","*","options",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py#L11-L13"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py","language":"python","identifier":"DbIO.update_db","parameters":"(**options)","argument_list":"","return_statement":"","docstring":"Update values within _model_class from object values and save them","docstring_summary":"Update values within _model_class from object values and save them","docstring_tokens":["Update","values","within","_model_class","from","object","values","and","save","them"],"function":"def update_db(**options):\n \"\"\"Update values within _model_class from object values and save them\"\"\"\n raise NotImplementedError","function_tokens":["def","update_db","(","*","*","options",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py#L27-L29"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py","language":"python","identifier":"DbIO.marshall_db","parameters":"(**options)","argument_list":"","return_statement":"","docstring":"Create a _model_class instance with current object attributes\n\n For now, we rely on cassandra's Encoder.\n We could customize this marshaller in future if needed","docstring_summary":"Create a _model_class instance with current object attributes","docstring_tokens":["Create","a","_model_class","instance","with","current","object","attributes"],"function":"def marshall_db(**options):\n \"\"\"Create a _model_class instance with current object attributes\n\n For now, we rely on cassandra's Encoder.\n We could customize this marshaller in future if needed\n \"\"\"\n raise NotImplementedError","function_tokens":["def","marshall_db","(","*","*","options",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py#L31-L37"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py","language":"python","identifier":"DbIO.unmarshall_db","parameters":"(**options)","argument_list":"","return_statement":"","docstring":"Fill object attributes with values from _db","docstring_summary":"Fill object attributes with values from _db","docstring_tokens":["Fill","object","attributes","with","values","from","_db"],"function":"def unmarshall_db(**options):\n \"\"\"Fill object attributes with values from _db\"\"\"\n raise NotImplementedError","function_tokens":["def","unmarshall_db","(","*","*","options",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py#L39-L41"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py","language":"python","identifier":"IndexIO.marshall_index","parameters":"(**options)","argument_list":"","return_statement":"","docstring":"Create a _index_class instance with current object attributes","docstring_summary":"Create a _index_class instance with current object attributes","docstring_tokens":["Create","a","_index_class","instance","with","current","object","attributes"],"function":"def marshall_index(**options):\n \"\"\"Create a _index_class instance with current object attributes\"\"\"\n raise NotImplementedError","function_tokens":["def","marshall_index","(","*","*","options",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py#L47-L49"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py","language":"python","identifier":"IndexIO.unmarshall_index","parameters":"(**options)","argument_list":"","return_statement":"","docstring":"Fill object's attributes with values from _index","docstring_summary":"Fill object's attributes with values from _index","docstring_tokens":["Fill","object","s","attributes","with","values","from","_index"],"function":"def unmarshall_index(**options):\n \"\"\"Fill object's attributes with values from _index\"\"\"\n raise NotImplementedError","function_tokens":["def","unmarshall_index","(","*","*","options",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/common\/interfaces\/storage.py#L51-L53"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"allocate_user_shard","parameters":"(user_id)","argument_list":"","return_statement":"return shards[shard_idx]","docstring":"Find allocation to a shard for an user.","docstring_summary":"Find allocation to a shard for an user.","docstring_tokens":["Find","allocation","to","a","shard","for","an","user","."],"function":"def allocate_user_shard(user_id):\n \"\"\"Find allocation to a shard for an user.\"\"\"\n shards = Configuration('global').get('elasticsearch.shards')\n if not shards:\n raise Exception('No shards configured for index')\n shard_idx = int(user_id.hex, 16) % len(shards)\n return shards[shard_idx]","function_tokens":["def","allocate_user_shard","(","user_id",")",":","shards","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.shards'",")","if","not","shards",":","raise","Exception","(","'No shards configured for index'",")","shard_idx","=","int","(","user_id",".","hex",",","16",")","%","len","(","shards",")","return","shards","[","shard_idx","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L41-L47"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"FilterRule.create","parameters":"(cls, user, rule)","argument_list":"","return_statement":"return o","docstring":"Create a new filtering rule.","docstring_summary":"Create a new filtering rule.","docstring_tokens":["Create","a","new","filtering","rule","."],"function":"def create(cls, user, rule):\n \"\"\"Create a new filtering rule.\"\"\"\n rule.validate()\n # XXX : expr value is evil\n o = super(FilterRule, cls).create(user_id=user.user_id,\n rule_id=user.new_rule_id(),\n date_insert=datetime.datetime.now(\n tz=pytz.utc),\n name=rule.name,\n filter_expr=rule.expr,\n position=rule.position,\n stop_condition=rule.stop_condition,\n tags=rule.tags)\n return o","function_tokens":["def","create","(","cls",",","user",",","rule",")",":","rule",".","validate","(",")","# XXX : expr value is evil","o","=","super","(","FilterRule",",","cls",")",".","create","(","user_id","=","user",".","user_id",",","rule_id","=","user",".","new_rule_id","(",")",",","date_insert","=","datetime",".","datetime",".","now","(","tz","=","pytz",".","utc",")",",","name","=","rule",".","name",",","filter_expr","=","rule",".","expr",",","position","=","rule",".","position",",","stop_condition","=","rule",".","stop_condition",",","tags","=","rule",".","tags",")","return","o"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L64-L77"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"FilterRule.eval","parameters":"(self, message)","argument_list":"","return_statement":"return [], False","docstring":"Evaluate if this rule apply to the given message.\n\n evaluation return a list of TAGS to add or nothing\n stop condition if set and if result is empty or not\n and match this stop condition, processing of rules\n on this message stop.","docstring_summary":"Evaluate if this rule apply to the given message.","docstring_tokens":["Evaluate","if","this","rule","apply","to","the","given","message","."],"function":"def eval(self, message):\n \"\"\"\n Evaluate if this rule apply to the given message.\n\n evaluation return a list of TAGS to add or nothing\n stop condition if set and if result is empty or not\n and match this stop condition, processing of rules\n on this message stop.\n\n \"\"\"\n # XXXX WARN WARN WARN WARN WARN WARN WARN WARN\n #\n # This is a REALLY BASIC filtering concept with no\n # security consideration abount what is evaluated !!!!\n #\n # XXXX WARN WARN WARN WARN WARN WARN WARN WARN\n\n res = eval(self.filter_expr)\n if self.stop_condition is not None:\n if self.stop_condition and res:\n return self.tags, True\n if not self.stop_condition and not res:\n return self.tags, True\n if res:\n return self.tags, False\n return [], False","function_tokens":["def","eval","(","self",",","message",")",":","# XXXX WARN WARN WARN WARN WARN WARN WARN WARN","#","# This is a REALLY BASIC filtering concept with no","# security consideration abount what is evaluated !!!!","#","# XXXX WARN WARN WARN WARN WARN WARN WARN WARN","res","=","eval","(","self",".","filter_expr",")","if","self",".","stop_condition","is","not","None",":","if","self",".","stop_condition","and","res",":","return","self",".","tags",",","True","if","not","self",".","stop_condition","and","not","res",":","return","self",".","tags",",","True","if","res",":","return","self",".","tags",",","False","return","[","]",",","False"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L79-L104"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User._check_whitelistes","parameters":"(cls, user)","argument_list":"","return_statement":"","docstring":"Check if user is in a white list if apply.","docstring_summary":"Check if user is in a white list if apply.","docstring_tokens":["Check","if","user","is","in","a","white","list","if","apply","."],"function":"def _check_whitelistes(cls, user):\n \"\"\"Check if user is in a white list if apply.\"\"\"\n whitelistes = Configuration('global').get('whitelistes', {})\n emails_file = whitelistes.get('user_emails')\n if emails_file and os.path.isfile(emails_file):\n with open(emails_file) as f:\n emails = [x for x in f.read().split('\\n') if x]\n if user.recovery_email in emails:\n return True\n else:\n raise ValueError('user email not in whitelist')","function_tokens":["def","_check_whitelistes","(","cls",",","user",")",":","whitelistes","=","Configuration","(","'global'",")",".","get","(","'whitelistes'",",","{","}",")","emails_file","=","whitelistes",".","get","(","'user_emails'",")","if","emails_file","and","os",".","path",".","isfile","(","emails_file",")",":","with","open","(","emails_file",")","as","f",":","emails","=","[","x","for","x","in","f",".","read","(",")",".","split","(","'\\n'",")","if","x","]","if","user",".","recovery_email","in","emails",":","return","True","else",":","raise","ValueError","(","'user email not in whitelist'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L146-L156"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User._check_max_users","parameters":"(cls)","argument_list":"","return_statement":"","docstring":"Check if maximum number of users reached.","docstring_summary":"Check if maximum number of users reached.","docstring_tokens":["Check","if","maximum","number","of","users","reached","."],"function":"def _check_max_users(cls):\n \"\"\"Check if maximum number of users reached.\"\"\"\n conf = Configuration('global').get('system', {})\n max_users = conf.get('max_users', 0)\n if max_users:\n nb_users = User._model_class.objects.count()\n if nb_users >= max_users:\n raise ValueError('Max number of users reached')","function_tokens":["def","_check_max_users","(","cls",")",":","conf","=","Configuration","(","'global'",")",".","get","(","'system'",",","{","}",")","max_users","=","conf",".","get","(","'max_users'",",","0",")","if","max_users",":","nb_users","=","User",".","_model_class",".","objects",".","count","(",")","if","nb_users",">=","max_users",":","raise","ValueError","(","'Max number of users reached'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L159-L166"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.create","parameters":"(cls, new_user)","argument_list":"","return_statement":"return core","docstring":"Create a new user.\n\n @param: new_user is a parameters\/user.py.NewUser object\n # 1.check username regex\n # 2.check username is not in reserved_name table\n # 3.check recovery email validity (TODO : check if email is not within\n # the current Caliopen's instance)\n # 4.check username availability\n # 5.add username to user cassa user_name table (to block the\n # availability)\n # 6.check password strength (and regex?)\n # then\n # create user and linked contact","docstring_summary":"Create a new user.","docstring_tokens":["Create","a","new","user","."],"function":"def create(cls, new_user):\n \"\"\"Create a new user.\n\n @param: new_user is a parameters\/user.py.NewUser object\n # 1.check username regex\n # 2.check username is not in reserved_name table\n # 3.check recovery email validity (TODO : check if email is not within\n # the current Caliopen's instance)\n # 4.check username availability\n # 5.add username to user cassa user_name table (to block the\n # availability)\n # 6.check password strength (and regex?)\n # then\n # create user and linked contact\n \"\"\"\n\n def rollback_username_storage(username):\n UserName.get(username).delete()\n\n # 0. check for user email white list and max number of users\n cls._check_whitelistes(new_user)\n cls._check_max_users()\n\n # 1.\n try:\n validators.is_valid_username(new_user.name)\n except SyntaxError:\n raise ValueError(\"Malformed username\")\n\n # 2.\n try:\n ReservedName.get(new_user.name)\n raise ValueError('Reserved user name')\n except NotFound:\n pass\n\n user_id = uuid.uuid4()\n # 3.\n if not new_user.recovery_email:\n raise ValueError(\"Missing recovery email\")\n\n try:\n cls.validate_recovery_email(new_user.recovery_email)\n except Exception as exc:\n log.info(\"recovery email failed validation : {}\".format(exc))\n raise ValueError(exc)\n\n # 4. & 5.\n if User.is_username_available(new_user.name.lower()):\n # save username immediately to prevent concurrent creation\n UserName.create(name=new_user.name.lower(), user_id=user_id)\n # NB : need to rollback this username creation if the below\n # User creation failed for any reason\n else:\n raise ValueError(\"Username already exist\")\n\n # 6.\n try:\n user_inputs = [new_user.name.encode(\"utf-8\"),\n new_user.recovery_email.encode(\"utf-8\")]\n # TODO: add contact inputs if any\n password_strength = zxcvbn(new_user.password,\n user_inputs=user_inputs)\n privacy_features = {\"password_strength\":\n str(password_strength[\"score\"])}\n passwd = new_user.password.encode('utf-8')\n new_user.password = bcrypt.hashpw(passwd, bcrypt.gensalt())\n except Exception as exc:\n log.exception(exc)\n rollback_username_storage(new_user.name)\n raise exc\n\n try:\n new_user.validate() # schematic model validation\n except Exception as exc:\n rollback_username_storage(new_user.name)\n log.info(\"schematics validation error: {}\".format(exc))\n raise ValueError(\"new user malformed\")\n\n try:\n recovery = new_user.recovery_email\n if hasattr(new_user, \"contact\"):\n family_name = new_user.contact.family_name\n given_name = new_user.contact.given_name\n else:\n family_name = \"\"\n given_name = \"\"\n\n # XXX PI compute\n pi = PIModel()\n pi.technic = 0\n pi.comportment = 0\n pi.context = 0\n pi.version = 0\n shard_id = allocate_user_shard(user_id)\n\n core = super(User, cls).create(user_id=user_id,\n name=new_user.name,\n password=new_user.password,\n recovery_email=recovery,\n params=new_user.params,\n date_insert=datetime.datetime.now(\n tz=pytz.utc),\n privacy_features=privacy_features,\n pi=pi,\n family_name=family_name,\n given_name=given_name,\n shard_id=shard_id)\n except Exception as exc:\n log.info(exc)\n rollback_username_storage(new_user.name)\n raise exc\n\n # **** operations below do not raise fatal error and rollback **** #\n # Setup index\n setup_index(core)\n # Setup others entities related to user\n setup_system_tags(core)\n setup_settings(core, new_user.settings)\n\n UserRecoveryEmail.create(recovery_email=recovery, user_id=user_id)\n # Add a default local identity on a default configured domain\n default_domain = Configuration('global').get('default_domain')\n default_local_id = '{}@{}'.format(core.name, default_domain)\n if not core.add_local_identity(default_local_id):\n log.warn('Impossible to create default local identity {}'.\n format(default_local_id))\n\n # save and index linked contact\n if hasattr(new_user, \"contact\"):\n # \u00a0add local email to contact\n local_mail = NewEmail()\n local_mail.address = default_local_id\n new_user.contact.emails.append(local_mail)\n\n # create default contact for user\n contact = CoreContact.create(core, new_user.contact)\n\n core.model.contact_id = contact.contact_id\n\n log.info(\"contact id {} for new user {}\".format(contact.contact_id,\n core.user_id))\n else:\n log.error(\n \"missing contact in new_user params for user {}. \"\n \"Can't create related tables\".format(core.user_id))\n\n core.save()\n return core","function_tokens":["def","create","(","cls",",","new_user",")",":","def","rollback_username_storage","(","username",")",":","UserName",".","get","(","username",")",".","delete","(",")","# 0. check for user email white list and max number of users","cls",".","_check_whitelistes","(","new_user",")","cls",".","_check_max_users","(",")","# 1.","try",":","validators",".","is_valid_username","(","new_user",".","name",")","except","SyntaxError",":","raise","ValueError","(","\"Malformed username\"",")","# 2.","try",":","ReservedName",".","get","(","new_user",".","name",")","raise","ValueError","(","'Reserved user name'",")","except","NotFound",":","pass","user_id","=","uuid",".","uuid4","(",")","# 3.","if","not","new_user",".","recovery_email",":","raise","ValueError","(","\"Missing recovery email\"",")","try",":","cls",".","validate_recovery_email","(","new_user",".","recovery_email",")","except","Exception","as","exc",":","log",".","info","(","\"recovery email failed validation : {}\"",".","format","(","exc",")",")","raise","ValueError","(","exc",")","# 4. & 5.","if","User",".","is_username_available","(","new_user",".","name",".","lower","(",")",")",":","# save username immediately to prevent concurrent creation","UserName",".","create","(","name","=","new_user",".","name",".","lower","(",")",",","user_id","=","user_id",")","# NB : need to rollback this username creation if the below","# User creation failed for any reason","else",":","raise","ValueError","(","\"Username already exist\"",")","# 6.","try",":","user_inputs","=","[","new_user",".","name",".","encode","(","\"utf-8\"",")",",","new_user",".","recovery_email",".","encode","(","\"utf-8\"",")","]","# TODO: add contact inputs if any","password_strength","=","zxcvbn","(","new_user",".","password",",","user_inputs","=","user_inputs",")","privacy_features","=","{","\"password_strength\"",":","str","(","password_strength","[","\"score\"","]",")","}","passwd","=","new_user",".","password",".","encode","(","'utf-8'",")","new_user",".","password","=","bcrypt",".","hashpw","(","passwd",",","bcrypt",".","gensalt","(",")",")","except","Exception","as","exc",":","log",".","exception","(","exc",")","rollback_username_storage","(","new_user",".","name",")","raise","exc","try",":","new_user",".","validate","(",")","# schematic model validation","except","Exception","as","exc",":","rollback_username_storage","(","new_user",".","name",")","log",".","info","(","\"schematics validation error: {}\"",".","format","(","exc",")",")","raise","ValueError","(","\"new user malformed\"",")","try",":","recovery","=","new_user",".","recovery_email","if","hasattr","(","new_user",",","\"contact\"",")",":","family_name","=","new_user",".","contact",".","family_name","given_name","=","new_user",".","contact",".","given_name","else",":","family_name","=","\"\"","given_name","=","\"\"","# XXX PI compute","pi","=","PIModel","(",")","pi",".","technic","=","0","pi",".","comportment","=","0","pi",".","context","=","0","pi",".","version","=","0","shard_id","=","allocate_user_shard","(","user_id",")","core","=","super","(","User",",","cls",")",".","create","(","user_id","=","user_id",",","name","=","new_user",".","name",",","password","=","new_user",".","password",",","recovery_email","=","recovery",",","params","=","new_user",".","params",",","date_insert","=","datetime",".","datetime",".","now","(","tz","=","pytz",".","utc",")",",","privacy_features","=","privacy_features",",","pi","=","pi",",","family_name","=","family_name",",","given_name","=","given_name",",","shard_id","=","shard_id",")","except","Exception","as","exc",":","log",".","info","(","exc",")","rollback_username_storage","(","new_user",".","name",")","raise","exc","# **** operations below do not raise fatal error and rollback **** #","# Setup index","setup_index","(","core",")","# Setup others entities related to user","setup_system_tags","(","core",")","setup_settings","(","core",",","new_user",".","settings",")","UserRecoveryEmail",".","create","(","recovery_email","=","recovery",",","user_id","=","user_id",")","# Add a default local identity on a default configured domain","default_domain","=","Configuration","(","'global'",")",".","get","(","'default_domain'",")","default_local_id","=","'{}@{}'",".","format","(","core",".","name",",","default_domain",")","if","not","core",".","add_local_identity","(","default_local_id",")",":","log",".","warn","(","'Impossible to create default local identity {}'",".","format","(","default_local_id",")",")","# save and index linked contact","if","hasattr","(","new_user",",","\"contact\"",")",":","# \u00a0add local email to contact","local_mail","=","NewEmail","(",")","local_mail",".","address","=","default_local_id","new_user",".","contact",".","emails",".","append","(","local_mail",")","# create default contact for user","contact","=","CoreContact",".","create","(","core",",","new_user",".","contact",")","core",".","model",".","contact_id","=","contact",".","contact_id","log",".","info","(","\"contact id {} for new user {}\"",".","format","(","contact",".","contact_id",",","core",".","user_id",")",")","else",":","log",".","error","(","\"missing contact in new_user params for user {}. \"","\"Can't create related tables\"",".","format","(","core",".","user_id",")",")","core",".","save","(",")","return","core"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L169-L317"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.by_name","parameters":"(cls, name)","argument_list":"","return_statement":"return cls.get(uname.user_id)","docstring":"Get user by name.","docstring_summary":"Get user by name.","docstring_tokens":["Get","user","by","name","."],"function":"def by_name(cls, name):\n \"\"\"Get user by name.\"\"\"\n uname = UserName.get(name.lower())\n return cls.get(uname.user_id)","function_tokens":["def","by_name","(","cls",",","name",")",":","uname","=","UserName",".","get","(","name",".","lower","(",")",")","return","cls",".","get","(","uname",".","user_id",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L320-L323"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.is_username_available","parameters":"(cls, username)","argument_list":"","return_statement":"","docstring":"Return True if username is available.","docstring_summary":"Return True if username is available.","docstring_tokens":["Return","True","if","username","is","available","."],"function":"def is_username_available(cls, username):\n \"\"\"Return True if username is available.\"\"\"\n try:\n UserName.get(username.lower())\n return False\n except NotFound:\n return True","function_tokens":["def","is_username_available","(","cls",",","username",")",":","try",":","UserName",".","get","(","username",".","lower","(",")",")","return","False","except","NotFound",":","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L326-L332"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.by_local_identifier","parameters":"(cls, address, protocol)","argument_list":"","return_statement":"","docstring":"Get a user by one of a local identifier.","docstring_summary":"Get a user by one of a local identifier.","docstring_tokens":["Get","a","user","by","one","of","a","local","identifier","."],"function":"def by_local_identifier(cls, address, protocol):\n \"\"\"Get a user by one of a local identifier.\"\"\"\n identities = UserIdentity.get_by_identifier(address.lower(), protocol,\n None)\n for identity in identities:\n if identity.type == 'local':\n return cls.get(identity.user_id)\n raise NotFound","function_tokens":["def","by_local_identifier","(","cls",",","address",",","protocol",")",":","identities","=","UserIdentity",".","get_by_identifier","(","address",".","lower","(",")",",","protocol",",","None",")","for","identity","in","identities",":","if","identity",".","type","==","'local'",":","return","cls",".","get","(","identity",".","user_id",")","raise","NotFound"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L335-L342"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.authenticate","parameters":"(cls, user_name, password)","argument_list":"","return_statement":"","docstring":"Authenticate an user.","docstring_summary":"Authenticate an user.","docstring_tokens":["Authenticate","an","user","."],"function":"def authenticate(cls, user_name, password):\n \"\"\"Authenticate an user.\"\"\"\n try:\n user = cls.by_name(user_name)\n except NotFound:\n raise CredentialException('Invalid user')\n\n if user.date_delete:\n raise CredentialException('Invalid credentials')\n\n # XXX : decode unicode not this way\n if bcrypt.hashpw(str(password.encode('utf-8')),\n str(user.password)) == user.password:\n return user\n raise CredentialException('Invalid credentials')","function_tokens":["def","authenticate","(","cls",",","user_name",",","password",")",":","try",":","user","=","cls",".","by_name","(","user_name",")","except","NotFound",":","raise","CredentialException","(","'Invalid user'",")","if","user",".","date_delete",":","raise","CredentialException","(","'Invalid credentials'",")","# XXX : decode unicode not this way","if","bcrypt",".","hashpw","(","str","(","password",".","encode","(","'utf-8'",")",")",",","str","(","user",".","password",")",")","==","user",".","password",":","return","user","raise","CredentialException","(","'Invalid credentials'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L345-L359"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.contact","parameters":"(self)","argument_list":"","return_statement":"","docstring":"User is a contact.","docstring_summary":"User is a contact.","docstring_tokens":["User","is","a","contact","."],"function":"def contact(self):\n \"\"\"User is a contact.\"\"\"\n if self.contact_id is None:\n return None\n try:\n return CoreContact.get(self, self.contact_id)\n except NotFound:\n log.warn(\"contact {} not found for user {}\".\n format(self.contact_id, self.user_id))\n return None","function_tokens":["def","contact","(","self",")",":","if","self",".","contact_id","is","None",":","return","None","try",":","return","CoreContact",".","get","(","self",",","self",".","contact_id",")","except","NotFound",":","log",".","warn","(","\"contact {} not found for user {}\"",".","format","(","self",".","contact_id",",","self",".","user_id",")",")","return","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L362-L371"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.tags","parameters":"(self)","argument_list":"","return_statement":"return [Tag(x) for x in objs]","docstring":"Tag objects related to an user.","docstring_summary":"Tag objects related to an user.","docstring_tokens":["Tag","objects","related","to","an","user","."],"function":"def tags(self):\n \"\"\"Tag objects related to an user.\"\"\"\n objs = Tag._model_class.filter(user_id=self.user_id)\n return [Tag(x) for x in objs]","function_tokens":["def","tags","(","self",")",":","objs","=","Tag",".","_model_class",".","filter","(","user_id","=","self",".","user_id",")","return","[","Tag","(","x",")","for","x","in","objs","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L374-L377"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.rules","parameters":"(self)","argument_list":"","return_statement":"return sorted(cores, key=lambda x: x.position)","docstring":"Filtering rules associated to an user, sorted by position.","docstring_summary":"Filtering rules associated to an user, sorted by position.","docstring_tokens":["Filtering","rules","associated","to","an","user","sorted","by","position","."],"function":"def rules(self):\n \"\"\"Filtering rules associated to an user, sorted by position.\"\"\"\n objs = FilterRule._model_class.filter(user_id=self.user_id)\n cores = [FilterRule(x) for x in objs]\n return sorted(cores, key=lambda x: x.position)","function_tokens":["def","rules","(","self",")",":","objs","=","FilterRule",".","_model_class",".","filter","(","user_id","=","self",".","user_id",")","cores","=","[","FilterRule","(","x",")","for","x","in","objs","]","return","sorted","(","cores",",","key","=","lambda","x",":","x",".","position",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L380-L384"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.add_local_identity","parameters":"(self, address)","argument_list":"","return_statement":"","docstring":"Add a local smtp identity to an user and fill related lookup tables","docstring_summary":"Add a local smtp identity to an user and fill related lookup tables","docstring_tokens":["Add","a","local","smtp","identity","to","an","user","and","fill","related","lookup","tables"],"function":"def add_local_identity(self, address):\n \"\"\"\n Add a local smtp identity to an user and fill related lookup tables\n \"\"\"\n formatted = address.lower()\n try:\n local_identity = User.by_local_identifier(address, 'smtp')\n if local_identity:\n log.warn(\"local identifier {} already exist\".format(address))\n return None\n except NotFound:\n try:\n identities = IdentityLookup.find(identifier=formatted)\n if len(identities) == 0: raise NotFound\n for id in identities:\n identity = UserIdentity.get(self, id.identity_id)\n if identity and identity.protocol == 'smtp' and \\\n identity.user_id == self.user_id:\n if identity.identity_id in self.local_identities:\n # Local identity already created. Should raise error ?\n return identity\n raise Exception(\n 'Inconsistent local identity {}'.format(address))\n except NotFound:\n display_name = \"{} {}\".format(self.given_name, self.family_name)\n identity = UserIdentity.create(self, identifier=formatted,\n identity_id=uuid.uuid4(),\n type='local',\n status='active',\n protocol='email',\n display_name=display_name)\n # \u00a0insert entries in relevant lookup tables\n IdentityLookup.create(identifier=identity.identifier,\n protocol=identity.protocol,\n user_id=identity.user_id,\n identity_id=identity.identity_id)\n IdentityTypeLookup.create(type=identity.type,\n user_id=identity.user_id,\n identity_id=identity.identity_id)\n return identity\n except Exception as exc:\n log.error('Unexpected exception {}'.format(exc))\n return None","function_tokens":["def","add_local_identity","(","self",",","address",")",":","formatted","=","address",".","lower","(",")","try",":","local_identity","=","User",".","by_local_identifier","(","address",",","'smtp'",")","if","local_identity",":","log",".","warn","(","\"local identifier {} already exist\"",".","format","(","address",")",")","return","None","except","NotFound",":","try",":","identities","=","IdentityLookup",".","find","(","identifier","=","formatted",")","if","len","(","identities",")","==","0",":","raise","NotFound","for","id","in","identities",":","identity","=","UserIdentity",".","get","(","self",",","id",".","identity_id",")","if","identity","and","identity",".","protocol","==","'smtp'","and","identity",".","user_id","==","self",".","user_id",":","if","identity",".","identity_id","in","self",".","local_identities",":","# Local identity already created. Should raise error ?","return","identity","raise","Exception","(","'Inconsistent local identity {}'",".","format","(","address",")",")","except","NotFound",":","display_name","=","\"{} {}\"",".","format","(","self",".","given_name",",","self",".","family_name",")","identity","=","UserIdentity",".","create","(","self",",","identifier","=","formatted",",","identity_id","=","uuid",".","uuid4","(",")",",","type","=","'local'",",","status","=","'active'",",","protocol","=","'email'",",","display_name","=","display_name",")","# \u00a0insert entries in relevant lookup tables","IdentityLookup",".","create","(","identifier","=","identity",".","identifier",",","protocol","=","identity",".","protocol",",","user_id","=","identity",".","user_id",",","identity_id","=","identity",".","identity_id",")","IdentityTypeLookup",".","create","(","type","=","identity",".","type",",","user_id","=","identity",".","user_id",",","identity_id","=","identity",".","identity_id",")","return","identity","except","Exception","as","exc",":","log",".","error","(","'Unexpected exception {}'",".","format","(","exc",")",")","return","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L386-L428"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py","language":"python","identifier":"User.validate_recovery_email","parameters":"(cls, email)","argument_list":"","return_statement":"","docstring":"provided email has to pass the validations below,\n otherwise this func will raise an error\n @:arg email: string","docstring_summary":"provided email has to pass the validations below,\n otherwise this func will raise an error","docstring_tokens":["provided","email","has","to","pass","the","validations","below","otherwise","this","func","will","raise","an","error"],"function":"def validate_recovery_email(cls, email):\n \"\"\"\n provided email has to pass the validations below,\n otherwise this func will raise an error\n @:arg email: string\n \"\"\"\n\n # 1. is email well-formed ?\n if not validate_email(email):\n raise ValueError(\"recovery email malformed\")\n\n # 2. is email already in our db ? (recovery_email must be unique)\n try:\n UserRecoveryEmail.get(email)\n except NotFound:\n pass\n else:\n raise ValueError(\"recovery email already used in this instance\")\n\n # 3. is email belonging to one of our domains ?\n # (recovery_email must be external)\n domain = email.split(\"@\")[1]\n if domain in Configuration(\"global\").get(\"default_domain\"):\n raise ValueError(\n \"recovery email must be outside of this domain instance\")","function_tokens":["def","validate_recovery_email","(","cls",",","email",")",":","# 1. is email well-formed ?","if","not","validate_email","(","email",")",":","raise","ValueError","(","\"recovery email malformed\"",")","# 2. is email already in our db ? (recovery_email must be unique)","try",":","UserRecoveryEmail",".","get","(","email",")","except","NotFound",":","pass","else",":","raise","ValueError","(","\"recovery email already used in this instance\"",")","# 3. is email belonging to one of our domains ?","# (recovery_email must be external)","domain","=","email",".","split","(","\"@\"",")","[","1","]","if","domain","in","Configuration","(","\"global\"",")",".","get","(","\"default_domain\"",")",":","raise","ValueError","(","\"recovery email must be outside of this domain instance\"",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/user.py#L435-L459"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/setups.py","language":"python","identifier":"setup_index","parameters":"(user)","argument_list":"","return_statement":"","docstring":"Creates user index and setups mappings.","docstring_summary":"Creates user index and setups mappings.","docstring_tokens":["Creates","user","index","and","setups","mappings","."],"function":"def setup_index(user):\n \"\"\"Creates user index and setups mappings.\"\"\"\n url = Configuration('global').get('elasticsearch.url')\n client = Elasticsearch(url)\n\n shard_id = user.shard_id\n # does shard exist ?\n if not client.indices.exists(shard_id):\n setup_shard_index(shard_id)\n\n # Creates a versioned index with our custom analyzers, tokenizers, etc.\n m_version = Configuration('global').get('elasticsearch.mappings_version')\n if m_version == \"\":\n raise Exception('Invalid mapping version for shard {0}'.\n format(shard_id))\n\n index_name = shard_id\n alias_name = user.user_id\n\n # Points an alias to the underlying user's index\n try:\n client.indices.put_alias(index=index_name, name=alias_name)\n except Exception as exc:\n log.exception(\"failed to create alias :\u00a0{0}\".format(exc))\n raise exc","function_tokens":["def","setup_index","(","user",")",":","url","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.url'",")","client","=","Elasticsearch","(","url",")","shard_id","=","user",".","shard_id","# does shard exist ?","if","not","client",".","indices",".","exists","(","shard_id",")",":","setup_shard_index","(","shard_id",")","# Creates a versioned index with our custom analyzers, tokenizers, etc.","m_version","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.mappings_version'",")","if","m_version","==","\"\"",":","raise","Exception","(","'Invalid mapping version for shard {0}'",".","format","(","shard_id",")",")","index_name","=","shard_id","alias_name","=","user",".","user_id","# Points an alias to the underlying user's index","try",":","client",".","indices",".","put_alias","(","index","=","index_name",",","name","=","alias_name",")","except","Exception","as","exc",":","log",".","exception","(","\"failed to create alias :\u00a0{0}\".","f","ormat(","e","xc)",")","","raise","exc"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/setups.py#L18-L42"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/setups.py","language":"python","identifier":"setup_shard_index","parameters":"(shard)","argument_list":"","return_statement":"","docstring":"Setup a shard index.","docstring_summary":"Setup a shard index.","docstring_tokens":["Setup","a","shard","index","."],"function":"def setup_shard_index(shard):\n \"\"\"Setup a shard index.\"\"\"\n url = Configuration('global').get('elasticsearch.url')\n client = Elasticsearch(url)\n\n try:\n log.info('Creating index {0}'.format(shard))\n client.indices.create(\n index=shard,\n body={\n \"settings\": {\n \"analysis\": {\n \"analyzer\": {\n \"text_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"lowercase\",\n \"filter\": [\n \"ascii_folding\"\n ]\n },\n \"email_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"email_tokenizer\",\n \"filter\": [\n \"ascii_folding\"\n ]\n }\n },\n \"filter\": {\n \"ascii_folding\": {\n \"type\": \"asciifolding\",\n \"preserve_original\": True\n }\n },\n \"tokenizer\": {\n \"email_tokenizer\": {\n \"type\": \"ngram\",\n \"min_gram\": 3,\n \"max_gram\": 25\n }\n }\n }\n }\n })\n except Exception as exc:\n log.warn(\"failed to create index {} :\u00a0{}\".format(shard, exc))\n return\n\n # TOFIX\n # core Message is no more in core_registry, use hard coded build mapping\n from caliopen_main.message.store.message_index import IndexedMessage\n from caliopen_main.contact.store.contact_index import IndexedContact\n log.info('Creating index mapping for message and contact in shard {}'.\n format(shard))\n message_mapping = IndexedMessage.build_mapping()\n message_mapping.save(shard, using=client)\n contact_mapping = IndexedContact.build_mapping()\n contact_mapping.save(shard, using=client)","function_tokens":["def","setup_shard_index","(","shard",")",":","url","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.url'",")","client","=","Elasticsearch","(","url",")","try",":","log",".","info","(","'Creating index {0}'",".","format","(","shard",")",")","client",".","indices",".","create","(","index","=","shard",",","body","=","{","\"settings\"",":","{","\"analysis\"",":","{","\"analyzer\"",":","{","\"text_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"lowercase\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}",",","\"email_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"email_tokenizer\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}","}",",","\"filter\"",":","{","\"ascii_folding\"",":","{","\"type\"",":","\"asciifolding\"",",","\"preserve_original\"",":","True","}","}",",","\"tokenizer\"",":","{","\"email_tokenizer\"",":","{","\"type\"",":","\"ngram\"",",","\"min_gram\"",":","3",",","\"max_gram\"",":","25","}","}","}","}","}",")","except","Exception","as","exc",":","log",".","warn","(","\"failed to create index {} :\u00a0{}\".","f","ormat(","s","hard,"," ","xc)",")","","return","# TOFIX","# core Message is no more in core_registry, use hard coded build mapping","from","caliopen_main",".","message",".","store",".","message_index","import","IndexedMessage","from","caliopen_main",".","contact",".","store",".","contact_index","import","IndexedContact","log",".","info","(","'Creating index mapping for message and contact in shard {}'",".","format","(","shard",")",")","message_mapping","=","IndexedMessage",".","build_mapping","(",")","message_mapping",".","save","(","shard",",","using","=","client",")","contact_mapping","=","IndexedContact",".","build_mapping","(",")","contact_mapping",".","save","(","shard",",","using","=","client",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/setups.py#L45-L102"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/setups.py","language":"python","identifier":"setup_system_tags","parameters":"(user)","argument_list":"","return_statement":"","docstring":"Create system tags.","docstring_summary":"Create system tags.","docstring_tokens":["Create","system","tags","."],"function":"def setup_system_tags(user):\n \"\"\"Create system tags.\"\"\"\n # TODO: translate tags'name to user's preferred language\n default_tags = Configuration('global').get('system.default_tags')\n for tag in default_tags:\n tag['type'] = 'system'\n tag['date_insert'] = datetime.datetime.now(tz=pytz.utc)\n tag['label'] = tag.get('label', tag['name'])\n from .user import Tag\n Tag.create(user, **tag)","function_tokens":["def","setup_system_tags","(","user",")",":","# TODO: translate tags'name to user's preferred language","default_tags","=","Configuration","(","'global'",")",".","get","(","'system.default_tags'",")","for","tag","in","default_tags",":","tag","[","'type'","]","=","'system'","tag","[","'date_insert'","]","=","datetime",".","datetime",".","now","(","tz","=","pytz",".","utc",")","tag","[","'label'","]","=","tag",".","get","(","'label'",",","tag","[","'name'","]",")","from",".","user","import","Tag","Tag",".","create","(","user",",","*","*","tag",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/setups.py#L105-L114"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/setups.py","language":"python","identifier":"setup_settings","parameters":"(user, settings)","argument_list":"","return_statement":"return True","docstring":"Create settings related to user.","docstring_summary":"Create settings related to user.","docstring_tokens":["Create","settings","related","to","user","."],"function":"def setup_settings(user, settings):\n \"\"\"Create settings related to user.\"\"\"\n # XXX set correct values\n\n settings = {\n 'user_id': user.user_id,\n 'default_locale': settings.default_locale,\n 'message_display_format': settings.message_display_format,\n 'contact_display_order': settings.contact_display_order,\n 'contact_display_format': settings.contact_display_format,\n 'notification_enabled': settings.notification_enabled,\n 'notification_message_preview':\n settings.notification_message_preview,\n 'notification_sound_enabled':\n settings.notification_sound_enabled,\n 'notification_delay_disappear':\n settings.notification_delay_disappear,\n }\n\n obj = ObjectSettings(user)\n obj.unmarshall_dict(settings)\n obj.marshall_db()\n obj.save_db()\n return True","function_tokens":["def","setup_settings","(","user",",","settings",")",":","# XXX set correct values","settings","=","{","'user_id'",":","user",".","user_id",",","'default_locale'",":","settings",".","default_locale",",","'message_display_format'",":","settings",".","message_display_format",",","'contact_display_order'",":","settings",".","contact_display_order",",","'contact_display_format'",":","settings",".","contact_display_format",",","'notification_enabled'",":","settings",".","notification_enabled",",","'notification_message_preview'",":","settings",".","notification_message_preview",",","'notification_sound_enabled'",":","settings",".","notification_sound_enabled",",","'notification_delay_disappear'",":","settings",".","notification_delay_disappear",",","}","obj","=","ObjectSettings","(","user",")","obj",".","unmarshall_dict","(","settings",")","obj",".","marshall_db","(",")","obj",".","save_db","(",")","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/setups.py#L117-L140"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/core\/identity.py","language":"python","identifier":"UserIdentity.get_by_identifier","parameters":"(cls, identifier, protocol, user_id)","argument_list":"","return_statement":"return identities","docstring":"return an array of one or more user_identities","docstring_summary":"return an array of one or more user_identities","docstring_tokens":["return","an","array","of","one","or","more","user_identities"],"function":"def get_by_identifier(cls, identifier, protocol, user_id):\n \"\"\"return an array of one or more user_identities\"\"\"\n if not protocol:\n ids = IdentityLookup.find(identifier=identifier)\n elif not user_id:\n ids = IdentityLookup.find(identifier=identifier,\n protocol=protocol)\n else:\n ids = IdentityLookup.find(identifier=identifier,\n protocol=protocol,\n user_id=user_id)\n identities = []\n for id in ids:\n identities.append(\n UserIdentity.get_by_user_id(id.user_id, id.identity_id))\n return identities","function_tokens":["def","get_by_identifier","(","cls",",","identifier",",","protocol",",","user_id",")",":","if","not","protocol",":","ids","=","IdentityLookup",".","find","(","identifier","=","identifier",")","elif","not","user_id",":","ids","=","IdentityLookup",".","find","(","identifier","=","identifier",",","protocol","=","protocol",")","else",":","ids","=","IdentityLookup",".","find","(","identifier","=","identifier",",","protocol","=","protocol",",","user_id","=","user_id",")","identities","=","[","]","for","id","in","ids",":","identities",".","append","(","UserIdentity",".","get_by_user_id","(","id",".","user_id",",","id",".","identity_id",")",")","return","identities"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/core\/identity.py#L21-L36"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/objects\/tag.py","language":"python","identifier":"UserTag.delete_db","parameters":"(self)","argument_list":"","return_statement":"return True","docstring":"Delete a tag in store.","docstring_summary":"Delete a tag in store.","docstring_tokens":["Delete","a","tag","in","store","."],"function":"def delete_db(self):\n \"\"\"Delete a tag in store.\"\"\"\n self._db.delete()\n return True","function_tokens":["def","delete_db","(","self",")",":","self",".","_db",".","delete","(",")","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/objects\/tag.py#L30-L33"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/helpers\/mergePatch.py","language":"python","identifier":"merge_patch","parameters":"(target, patch)","argument_list":"","return_statement":"","docstring":"rfc 7396 merge patch implementation","docstring_summary":"rfc 7396 merge patch implementation","docstring_tokens":["rfc","7396","merge","patch","implementation"],"function":"def merge_patch(target, patch):\n \"\"\"rfc 7396 merge patch implementation\"\"\"\n if type(patch) is dict:\n if type(target) is not dict:\n target = {} # Ignore the contents and set it to an empty Object\n for key, value in patch.iteritems():\n if value is None:\n if key in target:\n del target[key]\n else:\n target[key] = merge_patch(target[key], value)\n return target\n else:\n return patch","function_tokens":["def","merge_patch","(","target",",","patch",")",":","if","type","(","patch",")","is","dict",":","if","type","(","target",")","is","not","dict",":","target","=","{","}","# Ignore the contents and set it to an empty Object","for","key",",","value","in","patch",".","iteritems","(",")",":","if","value","is","None",":","if","key","in","target",":","del","target","[","key","]","else",":","target","[","key","]","=","merge_patch","(","target","[","key","]",",","value",")","return","target","else",":","return","patch"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/helpers\/mergePatch.py#L11-L24"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/helpers\/mergePatch.py","language":"python","identifier":"MergeBatch.process","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Process the merge on core object.","docstring_summary":"Process the merge on core object.","docstring_tokens":["Process","the","merge","on","core","object","."],"function":"def process(self):\n \"\"\"Process the merge on core object.\"\"\"\n log.info(\"process operations : {}\".format(self.operations))\n for typ, column, value in self.operations:\n core_attr = getattr(self.obj, column)\n if typ == 'add':\n core_attr = core_attr + value\n elif typ == 'del':\n core_attr = core_attr - value\n elif typ == 'replace':\n core_attr = value\n else:\n raise NotImplementedError('Merge operation {} not supported',\n format(typ))\n self.obj.save()","function_tokens":["def","process","(","self",")",":","log",".","info","(","\"process operations : {}\"",".","format","(","self",".","operations",")",")","for","typ",",","column",",","value","in","self",".","operations",":","core_attr","=","getattr","(","self",".","obj",",","column",")","if","typ","==","'add'",":","core_attr","=","core_attr","+","value","elif","typ","==","'del'",":","core_attr","=","core_attr","-","value","elif","typ","==","'replace'",":","core_attr","=","value","else",":","raise","NotImplementedError","(","'Merge operation {} not supported'",",","format","(","typ",")",")","self",".","obj",".","save","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/helpers\/mergePatch.py#L38-L52"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/user\/helpers\/validators.py","language":"python","identifier":"is_valid_username","parameters":"(username)","argument_list":"","return_statement":"","docstring":"conforms to doc\/RFCs\/username_specifications","docstring_summary":"conforms to doc\/RFCs\/username_specifications","docstring_tokens":["conforms","to","doc","\/","RFCs","\/","username_specifications"],"function":"def is_valid_username(username):\n \"\"\" conforms to doc\/RFCs\/username_specifications\"\"\"\n\n if len(username) < 3:\n raise SyntaxError\n\n rgx = ur\"^(([^\\p{C}\\p{M}\\p{Lm}\\p{Sk}\\p{Z}.\\u0022,@\\u0060:;<>\\[\\\\\\]]|\" \\\n ur\"[^\\p{C}\\p{M}\\p{Lm}\\p{Sk}\\p{Z}.\\u0022,@\\u0060:;<>\\[\\\\\\]]\\.)){1,40}\" \\\n ur\"[^\\p{C}\\p{M}\\p{Lm}\\p{Sk}\\p{Z}.\\u0022,@\\u0060:;<>\\[\\\\\\]]$\"\n\n r = regex.compile(rgx, flags=regex.V1+regex.UNICODE)\n\n if r.match(username) is None:\n raise SyntaxError","function_tokens":["def","is_valid_username","(","username",")",":","if","len","(","username",")","<","3",":","raise","SyntaxError","rgx","=","ur\"^(([^\\p{C}\\p{M}\\p{Lm}\\p{Sk}\\p{Z}.\\u0022,@\\u0060:;<>\\[\\\\\\]]|\"","ur\"[^\\p{C}\\p{M}\\p{Lm}\\p{Sk}\\p{Z}.\\u0022,@\\u0060:;<>\\[\\\\\\]]\\.)){1,40}\"","ur\"[^\\p{C}\\p{M}\\p{Lm}\\p{Sk}\\p{Z}.\\u0022,@\\u0060:;<>\\[\\\\\\]]$\"","r","=","regex",".","compile","(","rgx",",","flags","=","regex",".","V1","+","regex",".","UNICODE",")","if","r",".","match","(","username",")","is","None",":","raise","SyntaxError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/user\/helpers\/validators.py#L7-L20"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/device\/core.py","language":"python","identifier":"Device.create_from_parameter","parameters":"(cls, user, param, headers)","argument_list":"","return_statement":"return Device.create(user, dev, public_keys=[dev_key])","docstring":"Create a device from API parameters.","docstring_summary":"Create a device from API parameters.","docstring_tokens":["Create","a","device","from","API","parameters","."],"function":"def create_from_parameter(cls, user, param, headers):\n \"\"\"Create a device from API parameters.\"\"\"\n dev = NewDevice()\n dev.device_id = param['device_id']\n dev.user_agent = headers.get('User-Agent')\n dev.ip_creation = headers.get('X-Forwarded-For')\n dev.status = 'verified' if 'status' not in param else param['status']\n qualifier = NewDeviceQualifier(user)\n qualifier.process(dev)\n if 'name' in param:\n # Used to set the default device\n dev.name = param['name']\n else:\n dev_name = 'new device'\n if 'device_type' in dev.privacy_features:\n dev_ext = dev.privacy_features['device_type']\n dev_name = '{} {}'.format(dev_name, dev_ext)\n dev.name = dev_name\n\n dev.type = dev.privacy_features.get('device_type', 'other')\n # Device ecdsa key\n dev_key = NewPublicKey()\n dev_key.key_id = uuid.uuid4()\n dev_key.resource_id = dev.device_id\n dev_key.resource_type = 'device'\n dev_key.label = 'ecdsa key'\n dev_key.kty = 'ec'\n dev_key.use = 'sig'\n dev_key.x = int(param['ecdsa_key']['x'], 16)\n dev_key.y = int(param['ecdsa_key']['y'], 16)\n dev_key.crv = param['ecdsa_key']['curve']\n # XXX Should be better design\n alg_map = {\n 'P-256': 'ES256',\n 'P-384': 'ES384',\n 'P-521': 'ES512'\n }\n dev_key.alg = alg_map[dev_key.crv]\n return Device.create(user, dev, public_keys=[dev_key])","function_tokens":["def","create_from_parameter","(","cls",",","user",",","param",",","headers",")",":","dev","=","NewDevice","(",")","dev",".","device_id","=","param","[","'device_id'","]","dev",".","user_agent","=","headers",".","get","(","'User-Agent'",")","dev",".","ip_creation","=","headers",".","get","(","'X-Forwarded-For'",")","dev",".","status","=","'verified'","if","'status'","not","in","param","else","param","[","'status'","]","qualifier","=","NewDeviceQualifier","(","user",")","qualifier",".","process","(","dev",")","if","'name'","in","param",":","# Used to set the default device","dev",".","name","=","param","[","'name'","]","else",":","dev_name","=","'new device'","if","'device_type'","in","dev",".","privacy_features",":","dev_ext","=","dev",".","privacy_features","[","'device_type'","]","dev_name","=","'{} {}'",".","format","(","dev_name",",","dev_ext",")","dev",".","name","=","dev_name","dev",".","type","=","dev",".","privacy_features",".","get","(","'device_type'",",","'other'",")","# Device ecdsa key","dev_key","=","NewPublicKey","(",")","dev_key",".","key_id","=","uuid",".","uuid4","(",")","dev_key",".","resource_id","=","dev",".","device_id","dev_key",".","resource_type","=","'device'","dev_key",".","label","=","'ecdsa key'","dev_key",".","kty","=","'ec'","dev_key",".","use","=","'sig'","dev_key",".","x","=","int","(","param","[","'ecdsa_key'","]","[","'x'","]",",","16",")","dev_key",".","y","=","int","(","param","[","'ecdsa_key'","]","[","'y'","]",",","16",")","dev_key",".","crv","=","param","[","'ecdsa_key'","]","[","'curve'","]","# XXX Should be better design","alg_map","=","{","'P-256'",":","'ES256'",",","'P-384'",":","'ES384'",",","'P-521'",":","'ES512'","}","dev_key",".","alg","=","alg_map","[","dev_key",".","crv","]","return","Device",".","create","(","user",",","dev",",","public_keys","=","[","dev_key","]",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/device\/core.py#L50-L88"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/device\/core.py","language":"python","identifier":"Device.create","parameters":"(cls, user, device, **related)","argument_list":"","return_statement":"return core","docstring":"Create a new device for an user.","docstring_summary":"Create a new device for an user.","docstring_tokens":["Create","a","new","device","for","an","user","."],"function":"def create(cls, user, device, **related):\n \"\"\"Create a new device for an user.\"\"\"\n device.validate()\n attrs = {'device_id': device.device_id,\n 'type': device.type,\n 'name': device.name,\n 'user_agent': device.user_agent,\n 'ip_creation': device.ip_creation,\n 'privacy_features': device.privacy_features,\n 'status': device.status}\n\n core = super(Device, cls).create(user, **attrs)\n log.debug('Created device %s' % core.device_id)\n related_cores = {}\n for k, v in related.iteritems():\n if k in cls._relations:\n for obj in v:\n log.debug('Processing object %r' % obj.to_native())\n # XXX check only one is_primary per relation using it\n new_core = core._relations[k].create(user, **obj)\n related_cores.setdefault(k, []).append(new_core.to_dict())\n log.debug('Created related core %r' % new_core)\n return core","function_tokens":["def","create","(","cls",",","user",",","device",",","*","*","related",")",":","device",".","validate","(",")","attrs","=","{","'device_id'",":","device",".","device_id",",","'type'",":","device",".","type",",","'name'",":","device",".","name",",","'user_agent'",":","device",".","user_agent",",","'ip_creation'",":","device",".","ip_creation",",","'privacy_features'",":","device",".","privacy_features",",","'status'",":","device",".","status","}","core","=","super","(","Device",",","cls",")",".","create","(","user",",","*","*","attrs",")","log",".","debug","(","'Created device %s'","%","core",".","device_id",")","related_cores","=","{","}","for","k",",","v","in","related",".","iteritems","(",")",":","if","k","in","cls",".","_relations",":","for","obj","in","v",":","log",".","debug","(","'Processing object %r'","%","obj",".","to_native","(",")",")","# XXX check only one is_primary per relation using it","new_core","=","core",".","_relations","[","k","]",".","create","(","user",",","*","*","obj",")","related_cores",".","setdefault","(","k",",","[","]",")",".","append","(","new_core",".","to_dict","(",")",")","log",".","debug","(","'Created related core %r'","%","new_core",")","return","core"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/device\/core.py#L91-L113"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/device\/core.py","language":"python","identifier":"Device.check_locations","parameters":"(self, ipaddr)","argument_list":"","return_statement":"return True","docstring":"Check if the location of device is in related authorized ips.","docstring_summary":"Check if the location of device is in related authorized ips.","docstring_tokens":["Check","if","the","location","of","device","is","in","related","authorized","ips","."],"function":"def check_locations(self, ipaddr):\n \"\"\"Check if the location of device is in related authorized ips.\"\"\"\n if self.locations:\n for loc in self.locations:\n log.info(\"Testing cidr {0} with ip {1}\".\n format(loc.address, ipaddr))\n return True","function_tokens":["def","check_locations","(","self",",","ipaddr",")",":","if","self",".","locations",":","for","loc","in","self",".","locations",":","log",".","info","(","\"Testing cidr {0} with ip {1}\"",".","format","(","loc",".","address",",","ipaddr",")",")","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/device\/core.py#L115-L121"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/device\/core.py","language":"python","identifier":"Device.login","parameters":"(self, ipaddr)","argument_list":"","return_statement":"","docstring":"Login action for a device.","docstring_summary":"Login action for a device.","docstring_tokens":["Login","action","for","a","device","."],"function":"def login(self, ipaddr):\n \"\"\"Login action for a device.\"\"\"\n log.info(\"Logging device {0} for user {1}\".format(self.device_id,\n self.user_id))\n if not self.check_locations(ipaddr):\n raise Exception(\"Device IP Address not in allowed locations\")\n self._log_action(ipaddr, 'login')","function_tokens":["def","login","(","self",",","ipaddr",")",":","log",".","info","(","\"Logging device {0} for user {1}\"",".","format","(","self",".","device_id",",","self",".","user_id",")",")","if","not","self",".","check_locations","(","ipaddr",")",":","raise","Exception","(","\"Device IP Address not in allowed locations\"",")","self",".","_log_action","(","ipaddr",",","'login'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/device\/core.py#L128-L134"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/device\/core.py","language":"python","identifier":"Device.logout","parameters":"(self, ipaddr)","argument_list":"","return_statement":"","docstring":"Logout action for a device.","docstring_summary":"Logout action for a device.","docstring_tokens":["Logout","action","for","a","device","."],"function":"def logout(self, ipaddr):\n \"\"\"Logout action for a device.\"\"\"\n self._log_action(ipaddr, \"logout\")","function_tokens":["def","logout","(","self",",","ipaddr",")",":","self",".","_log_action","(","ipaddr",",","\"logout\"",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/device\/core.py#L136-L138"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/core.py","language":"python","identifier":"Contact._create_lookup","parameters":"(self, type, value)","argument_list":"","return_statement":"return lookup","docstring":"Create one contact lookup.","docstring_summary":"Create one contact lookup.","docstring_tokens":["Create","one","contact","lookup","."],"function":"def _create_lookup(self, type, value):\n \"\"\"Create one contact lookup.\"\"\"\n log.debug('Will create lookup for type {} and value {}'.\n format(type, value))\n lookup = ContactLookup.create(self.user, value=value, type=type,\n contact_id=self.contact_id)\n participant = Participant(address=value, protocol=type)\n\n return lookup","function_tokens":["def","_create_lookup","(","self",",","type",",","value",")",":","log",".","debug","(","'Will create lookup for type {} and value {}'",".","format","(","type",",","value",")",")","lookup","=","ContactLookup",".","create","(","self",".","user",",","value","=","value",",","type","=","type",",","contact_id","=","self",".","contact_id",")","participant","=","Participant","(","address","=","value",",","protocol","=","type",")","return","lookup"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/core.py#L106-L114"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/core.py","language":"python","identifier":"Contact._create_lookups","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Create lookups for a contact using its nested attributes.","docstring_summary":"Create lookups for a contact using its nested attributes.","docstring_tokens":["Create","lookups","for","a","contact","using","its","nested","attributes","."],"function":"def _create_lookups(self):\n \"\"\"Create lookups for a contact using its nested attributes.\"\"\"\n for attr_name, obj in self._lookup_values.items():\n nested = getattr(self, attr_name)\n if nested:\n for attr in nested:\n lookup_value = attr[obj['value']]\n if lookup_value:\n self._create_lookup(obj['type'], lookup_value)","function_tokens":["def","_create_lookups","(","self",")",":","for","attr_name",",","obj","in","self",".","_lookup_values",".","items","(",")",":","nested","=","getattr","(","self",",","attr_name",")","if","nested",":","for","attr","in","nested",":","lookup_value","=","attr","[","obj","[","'value'","]","]","if","lookup_value",":","self",".","_create_lookup","(","obj","[","'type'","]",",","lookup_value",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/core.py#L116-L124"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/core.py","language":"python","identifier":"Contact.public_keys","parameters":"(self)","argument_list":"","return_statement":"return self._expand_relation('public_keys')","docstring":"Return detailed public keys.","docstring_summary":"Return detailed public keys.","docstring_tokens":["Return","detailed","public","keys","."],"function":"def public_keys(self):\n \"\"\"Return detailed public keys.\"\"\"\n return self._expand_relation('public_keys')","function_tokens":["def","public_keys","(","self",")",":","return","self",".","_expand_relation","(","'public_keys'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/core.py#L234-L236"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py","language":"python","identifier":"VcardContact.__init__","parameters":"(self, vcard)","argument_list":"","return_statement":"","docstring":"Parse a vcard contact.","docstring_summary":"Parse a vcard contact.","docstring_tokens":["Parse","a","vcard","contact","."],"function":"def __init__(self, vcard):\n \"\"\"Parse a vcard contact.\"\"\"\n self._vcard = vcard\n self._parse()","function_tokens":["def","__init__","(","self",",","vcard",")",":","self",".","_vcard","=","vcard","self",".","_parse","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py#L20-L23"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py","language":"python","identifier":"VcardContact._get_not_empty","parameters":"(self, prop)","argument_list":"","return_statement":"return None","docstring":"Get non empty value (and only value) from a vcard property.","docstring_summary":"Get non empty value (and only value) from a vcard property.","docstring_tokens":["Get","non","empty","value","(","and","only","value",")","from","a","vcard","property","."],"function":"def _get_not_empty(self, prop):\n \"\"\"Get non empty value (and only value) from a vcard property.\"\"\"\n if prop in self._vcard.contents:\n attr = self._vcard.contents[prop]\n if isinstance(attr, (list, tuple)):\n return [x.value for x in attr if x.value]\n return attr.value if attr.value else None\n return None","function_tokens":["def","_get_not_empty","(","self",",","prop",")",":","if","prop","in","self",".","_vcard",".","contents",":","attr","=","self",".","_vcard",".","contents","[","prop","]","if","isinstance","(","attr",",","(","list",",","tuple",")",")",":","return","[","x",".","value","for","x","in","attr","if","x",".","value","]","return","attr",".","value","if","attr",".","value","else","None","return","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py#L25-L32"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py","language":"python","identifier":"VcardContact.__parse_emails","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Read vcard email property and build NewEmail instances.","docstring_summary":"Read vcard email property and build NewEmail instances.","docstring_tokens":["Read","vcard","email","property","and","build","NewEmail","instances","."],"function":"def __parse_emails(self):\n \"\"\"Read vcard email property and build NewEmail instances.\"\"\"\n for param in self._vcard.contents.get('email', []):\n yield self.__build_email(param)","function_tokens":["def","__parse_emails","(","self",")",":","for","param","in","self",".","_vcard",".","contents",".","get","(","'email'",",","[","]",")",":","yield","self",".","__build_email","(","param",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py#L45-L48"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py","language":"python","identifier":"VcardContact.__parse_phones","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Read vcard tel property and build NewPhone instances.","docstring_summary":"Read vcard tel property and build NewPhone instances.","docstring_tokens":["Read","vcard","tel","property","and","build","NewPhone","instances","."],"function":"def __parse_phones(self):\n \"\"\"Read vcard tel property and build NewPhone instances.\"\"\"\n for param in self._vcard.contents.get('tel', []):\n yield self.__build_phone(param)","function_tokens":["def","__parse_phones","(","self",")",":","for","param","in","self",".","_vcard",".","contents",".","get","(","'tel'",",","[","]",")",":","yield","self",".","__build_phone","(","param",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py#L82-L85"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py","language":"python","identifier":"VcardContact.__parse_addresses","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Read vcard adr property and build NewPostalAddress instances.","docstring_summary":"Read vcard adr property and build NewPostalAddress instances.","docstring_tokens":["Read","vcard","adr","property","and","build","NewPostalAddress","instances","."],"function":"def __parse_addresses(self):\n \"\"\"Read vcard adr property and build NewPostalAddress instances.\"\"\"\n for param in self._vcard.contents.get('adr', []):\n yield self.__build_address(param)","function_tokens":["def","__parse_addresses","(","self",")",":","for","param","in","self",".","_vcard",".","contents",".","get","(","'adr'",",","[","]",")",":","yield","self",".","__build_address","(","param",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py#L96-L99"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py","language":"python","identifier":"VcardContact.serialize","parameters":"(self)","argument_list":"","return_statement":"return data","docstring":"Serialize contact.","docstring_summary":"Serialize contact.","docstring_tokens":["Serialize","contact","."],"function":"def serialize(self):\n \"\"\"Serialize contact.\"\"\"\n data = self.contact.serialize()\n data.update({'_meta': self._meta})\n return data","function_tokens":["def","serialize","(","self",")",":","data","=","self",".","contact",".","serialize","(",")","data",".","update","(","{","'_meta'",":","self",".","_meta","}",")","return","data"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py#L168-L172"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py","language":"python","identifier":"VcardContact.validate","parameters":"(self)","argument_list":"","return_statement":"return self.contact.validate()","docstring":"Validate contact parsed informations.","docstring_summary":"Validate contact parsed informations.","docstring_tokens":["Validate","contact","parsed","informations","."],"function":"def validate(self):\n \"\"\"Validate contact parsed informations.\"\"\"\n return self.contact.validate()","function_tokens":["def","validate","(","self",")",":","return","self",".","contact",".","validate","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py#L174-L176"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py","language":"python","identifier":"VcardParser.__init__","parameters":"(self, f)","argument_list":"","return_statement":"","docstring":"Read a vcard file and create a generator on vcard objects.","docstring_summary":"Read a vcard file and create a generator on vcard objects.","docstring_tokens":["Read","a","vcard","file","and","create","a","generator","on","vcard","objects","."],"function":"def __init__(self, f):\n \"\"\"Read a vcard file and create a generator on vcard objects.\"\"\"\n self._vcards = vobject.readComponents(f)","function_tokens":["def","__init__","(","self",",","f",")",":","self",".","_vcards","=","vobject",".","readComponents","(","f",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py#L182-L184"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py","language":"python","identifier":"VcardParser.parse","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Generator on vcards objects read from read file.","docstring_summary":"Generator on vcards objects read from read file.","docstring_tokens":["Generator","on","vcards","objects","read","from","read","file","."],"function":"def parse(self):\n \"\"\"Generator on vcards objects read from read file.\"\"\"\n for vcard in self._vcards:\n yield VcardContact(vcard)","function_tokens":["def","parse","(","self",")",":","for","vcard","in","self",".","_vcards",":","yield","VcardContact","(","vcard",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/parsers\/vcard.py#L186-L189"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/objects\/phone.py","language":"python","identifier":"Phone.unmarshall_dict","parameters":"(self, document, **options)","argument_list":"","return_statement":"","docstring":"try to extract a normalize phone number from document","docstring_summary":"try to extract a normalize phone number from document","docstring_tokens":["try","to","extract","a","normalize","phone","number","from","document"],"function":"def unmarshall_dict(self, document, **options):\n \"\"\"try to extract a normalize phone number from document\"\"\"\n super(Phone, self).unmarshall_dict(document, **options)\n normalized = self.normalize_number(self.number)\n if normalized:\n setattr(self, 'normalized_number', normalized)","function_tokens":["def","unmarshall_dict","(","self",",","document",",","*","*","options",")",":","super","(","Phone",",","self",")",".","unmarshall_dict","(","document",",","*","*","options",")","normalized","=","self",".","normalize_number","(","self",".","number",")","if","normalized",":","setattr","(","self",",","'normalized_number'",",","normalized",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/objects\/phone.py#L46-L51"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/store\/contact_index.py","language":"python","identifier":"IndexedContact.contact_id","parameters":"(self)","argument_list":"","return_statement":"return self.meta.id","docstring":"The compound primary key for a contact is contact_id.","docstring_summary":"The compound primary key for a contact is contact_id.","docstring_tokens":["The","compound","primary","key","for","a","contact","is","contact_id","."],"function":"def contact_id(self):\n \"\"\"The compound primary key for a contact is contact_id.\"\"\"\n return self.meta.id","function_tokens":["def","contact_id","(","self",")",":","return","self",".","meta",".","id"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/store\/contact_index.py#L106-L108"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/contact\/store\/contact_index.py","language":"python","identifier":"IndexedContact.build_mapping","parameters":"(cls)","argument_list":"","return_statement":"return m","docstring":"Create elasticsearch indexed_contacts mapping object for an user.","docstring_summary":"Create elasticsearch indexed_contacts mapping object for an user.","docstring_tokens":["Create","elasticsearch","indexed_contacts","mapping","object","for","an","user","."],"function":"def build_mapping(cls):\n \"\"\"Create elasticsearch indexed_contacts mapping object for an user.\"\"\"\n m = Mapping(cls.doc_type)\n m.meta('_all', enabled=True)\n\n m.field('user_id', 'keyword')\n m.field('contact_id', 'keyword')\n\n m.field('additional_name', 'text', fields={\n \"normalized\": {\"type\": \"text\", \"analyzer\": \"text_analyzer\"}\n })\n # addresses\n addresses = Nested(doc_class=IndexedPostalAddress, include_in_all=True,\n properties={\n \"address_id\": \"keyword\",\n \"label\": \"text\",\n \"type\": \"keyword\",\n \"is_primary\": \"boolean\",\n \"street\": \"text\",\n \"city\": \"text\",\n \"postal_code\": \"keyword\",\n \"country\": \"text\",\n \"region\": \"text\"\n })\n m.field(\"addresses\", addresses)\n m.field(\"avatar\", \"keyword\")\n m.field('date_insert', 'date')\n m.field('date_update', 'date')\n m.field('deleted', 'date')\n # emails\n internet_addr = Nested(doc_class=IndexedInternetAddress,\n include_in_all=True,\n )\n internet_addr.field(\"address\", \"text\", analyzer=\"text_analyzer\",\n fields={\n \"raw\": {\"type\": \"keyword\"},\n \"parts\": {\"type\": \"text\",\n \"analyzer\": \"email_analyzer\"}\n })\n internet_addr.field(\"email_id\", Keyword())\n internet_addr.field(\"is_primary\", Boolean())\n internet_addr.field(\"label\", \"text\", analyzer=\"text_analyzer\")\n internet_addr.field(\"type\", Keyword())\n m.field(\"emails\", internet_addr)\n\n m.field('family_name', \"text\", fields={\n \"normalized\": {\"type\": \"text\", \"analyzer\": \"text_analyzer\"}\n })\n m.field('given_name', 'text', fields={\n \"normalized\": {\"type\": \"text\", \"analyzer\": \"text_analyzer\"}\n })\n m.field(\"groups\", Keyword(multi=True))\n # social ids\n social_ids = Nested(doc_class=IndexedSocialIdentity,\n include_in_all=True,\n properties={\n \"name\": \"text\",\n \"type\": \"keyword\",\n \"infos\": Nested()\n })\n m.field(\"identities\", social_ids)\n m.field(\"ims\", internet_addr)\n m.field(\"infos\", Nested())\n m.field('name_prefix', 'keyword')\n m.field('name_suffix', 'keyword')\n # organizations\n organizations = Nested(doc_class=IndexedOrganization,\n include_in_all=True)\n organizations.field(\"deleted\", Boolean())\n organizations.field(\"department\", \"text\", analyzer=\"text_analyzer\")\n organizations.field(\"is_primary\", Boolean())\n organizations.field(\"job_description\", \"text\")\n organizations.field(\"label\", \"text\", analyzer=\"text_analyzer\")\n organizations.field(\"name\", 'text', fields={\n \"normalized\": {\"type\": \"text\", \"analyzer\": \"text_analyzer\"}\n })\n organizations.field(\"organization_id\", Keyword())\n organizations.field(\"title\", Keyword())\n organizations.field(\"type\", Keyword())\n m.field(\"organizations\", organizations)\n # phones\n phones = Nested(doc_class=IndexedPhone, include_in_all=True,\n properties={\n \"is_primary\": \"boolean\",\n \"number\": \"text\",\n \"normalized_number\": \"text\",\n \"phone_id\": \"keyword\",\n \"type\": \"keyword\",\n \"uri\": \"keyword\"\n })\n\n m.field(\"phones\", phones)\n # pi\n pi = Object(doc_class=PIIndexModel, include_in_all=True,\n properties={\n \"comportment\": \"integer\",\n \"context\": \"integer\",\n \"date_update\": \"date\",\n \"technic\": \"integer\",\n \"version\": \"integer\"\n })\n m.field(\"pi\", pi)\n m.field(\"privacy_features\", Object(include_in_all=True))\n m.field(\"public_key\", Nested())\n m.field(\"social_identities\", social_ids)\n m.field(\"tags\", Keyword(multi=True))\n m.field('title', 'text', analyzer=\"text_analyzer\",\n fields={\n \"raw\": {\"type\": \"keyword\"}\n })\n\n return m","function_tokens":["def","build_mapping","(","cls",")",":","m","=","Mapping","(","cls",".","doc_type",")","m",".","meta","(","'_all'",",","enabled","=","True",")","m",".","field","(","'user_id'",",","'keyword'",")","m",".","field","(","'contact_id'",",","'keyword'",")","m",".","field","(","'additional_name'",",","'text'",",","fields","=","{","\"normalized\"",":","{","\"type\"",":","\"text\"",",","\"analyzer\"",":","\"text_analyzer\"","}","}",")","# addresses","addresses","=","Nested","(","doc_class","=","IndexedPostalAddress",",","include_in_all","=","True",",","properties","=","{","\"address_id\"",":","\"keyword\"",",","\"label\"",":","\"text\"",",","\"type\"",":","\"keyword\"",",","\"is_primary\"",":","\"boolean\"",",","\"street\"",":","\"text\"",",","\"city\"",":","\"text\"",",","\"postal_code\"",":","\"keyword\"",",","\"country\"",":","\"text\"",",","\"region\"",":","\"text\"","}",")","m",".","field","(","\"addresses\"",",","addresses",")","m",".","field","(","\"avatar\"",",","\"keyword\"",")","m",".","field","(","'date_insert'",",","'date'",")","m",".","field","(","'date_update'",",","'date'",")","m",".","field","(","'deleted'",",","'date'",")","# emails","internet_addr","=","Nested","(","doc_class","=","IndexedInternetAddress",",","include_in_all","=","True",",",")","internet_addr",".","field","(","\"address\"",",","\"text\"",",","analyzer","=","\"text_analyzer\"",",","fields","=","{","\"raw\"",":","{","\"type\"",":","\"keyword\"","}",",","\"parts\"",":","{","\"type\"",":","\"text\"",",","\"analyzer\"",":","\"email_analyzer\"","}","}",")","internet_addr",".","field","(","\"email_id\"",",","Keyword","(",")",")","internet_addr",".","field","(","\"is_primary\"",",","Boolean","(",")",")","internet_addr",".","field","(","\"label\"",",","\"text\"",",","analyzer","=","\"text_analyzer\"",")","internet_addr",".","field","(","\"type\"",",","Keyword","(",")",")","m",".","field","(","\"emails\"",",","internet_addr",")","m",".","field","(","'family_name'",",","\"text\"",",","fields","=","{","\"normalized\"",":","{","\"type\"",":","\"text\"",",","\"analyzer\"",":","\"text_analyzer\"","}","}",")","m",".","field","(","'given_name'",",","'text'",",","fields","=","{","\"normalized\"",":","{","\"type\"",":","\"text\"",",","\"analyzer\"",":","\"text_analyzer\"","}","}",")","m",".","field","(","\"groups\"",",","Keyword","(","multi","=","True",")",")","# social ids","social_ids","=","Nested","(","doc_class","=","IndexedSocialIdentity",",","include_in_all","=","True",",","properties","=","{","\"name\"",":","\"text\"",",","\"type\"",":","\"keyword\"",",","\"infos\"",":","Nested","(",")","}",")","m",".","field","(","\"identities\"",",","social_ids",")","m",".","field","(","\"ims\"",",","internet_addr",")","m",".","field","(","\"infos\"",",","Nested","(",")",")","m",".","field","(","'name_prefix'",",","'keyword'",")","m",".","field","(","'name_suffix'",",","'keyword'",")","# organizations","organizations","=","Nested","(","doc_class","=","IndexedOrganization",",","include_in_all","=","True",")","organizations",".","field","(","\"deleted\"",",","Boolean","(",")",")","organizations",".","field","(","\"department\"",",","\"text\"",",","analyzer","=","\"text_analyzer\"",")","organizations",".","field","(","\"is_primary\"",",","Boolean","(",")",")","organizations",".","field","(","\"job_description\"",",","\"text\"",")","organizations",".","field","(","\"label\"",",","\"text\"",",","analyzer","=","\"text_analyzer\"",")","organizations",".","field","(","\"name\"",",","'text'",",","fields","=","{","\"normalized\"",":","{","\"type\"",":","\"text\"",",","\"analyzer\"",":","\"text_analyzer\"","}","}",")","organizations",".","field","(","\"organization_id\"",",","Keyword","(",")",")","organizations",".","field","(","\"title\"",",","Keyword","(",")",")","organizations",".","field","(","\"type\"",",","Keyword","(",")",")","m",".","field","(","\"organizations\"",",","organizations",")","# phones","phones","=","Nested","(","doc_class","=","IndexedPhone",",","include_in_all","=","True",",","properties","=","{","\"is_primary\"",":","\"boolean\"",",","\"number\"",":","\"text\"",",","\"normalized_number\"",":","\"text\"",",","\"phone_id\"",":","\"keyword\"",",","\"type\"",":","\"keyword\"",",","\"uri\"",":","\"keyword\"","}",")","m",".","field","(","\"phones\"",",","phones",")","# pi","pi","=","Object","(","doc_class","=","PIIndexModel",",","include_in_all","=","True",",","properties","=","{","\"comportment\"",":","\"integer\"",",","\"context\"",":","\"integer\"",",","\"date_update\"",":","\"date\"",",","\"technic\"",":","\"integer\"",",","\"version\"",":","\"integer\"","}",")","m",".","field","(","\"pi\"",",","pi",")","m",".","field","(","\"privacy_features\"",",","Object","(","include_in_all","=","True",")",")","m",".","field","(","\"public_key\"",",","Nested","(",")",")","m",".","field","(","\"social_identities\"",",","social_ids",")","m",".","field","(","\"tags\"",",","Keyword","(","multi","=","True",")",")","m",".","field","(","'title'",",","'text'",",","analyzer","=","\"text_analyzer\"",",","fields","=","{","\"raw\"",":","{","\"type\"",":","\"keyword\"","}","}",")","return","m"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/contact\/store\/contact_index.py#L111-L222"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/participant\/core\/participant.py","language":"python","identifier":"hash_participants_uri","parameters":"(participants)","argument_list":"","return_statement":"return {'uris': URIs, 'hash': hash}","docstring":"Create hash from a collection of Participant\n\n :param participants: a collection of Participant\n :return: sorted collection of participants' URI + hash of this collection\n\n hash is computed from a set of URIs which are strings modeled as\n 'participant.protocol:participant.address'","docstring_summary":"Create hash from a collection of Participant","docstring_tokens":["Create","hash","from","a","collection","of","Participant"],"function":"def hash_participants_uri(participants):\n \"\"\"\n Create hash from a collection of Participant\n\n :param participants: a collection of Participant\n :return: sorted collection of participants' URI + hash of this collection\n\n hash is computed from a set of URIs which are strings modeled as\n 'participant.protocol:participant.address'\n \"\"\"\n URIs = set()\n for participant in participants:\n if not participant.address or not participant.protocol:\n raise Exception(\"missing mandatory property in participant\")\n uri = participant.protocol + \":\" + participant.address.lower()\n URIs.add(uri)\n\n URIs = list(URIs)\n URIs.sort()\n hash = hashlib.sha256(''.join(URIs)).hexdigest()\n return {'uris': URIs, 'hash': hash}","function_tokens":["def","hash_participants_uri","(","participants",")",":","URIs","=","set","(",")","for","participant","in","participants",":","if","not","participant",".","address","or","not","participant",".","protocol",":","raise","Exception","(","\"missing mandatory property in participant\"",")","uri","=","participant",".","protocol","+","\":\"","+","participant",".","address",".","lower","(",")","URIs",".","add","(","uri",")","URIs","=","list","(","URIs",")","URIs",".","sort","(",")","hash","=","hashlib",".","sha256","(","''",".","join","(","URIs",")",")",".","hexdigest","(",")","return","{","'uris'",":","URIs",",","'hash'",":","hash","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/participant\/core\/participant.py#L27-L47"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/participant\/core\/participant.py","language":"python","identifier":"participants_from_uris","parameters":"(user, uris, uris_hash)","argument_list":"","return_statement":"return {'components': participants, 'hash': participants_hash}","docstring":"- resolve uris to contact to build participants' set\n - compute participants_hash\n - create two ways links :\n uris<->uris_hash\n uris<->participants_hash\n\n :param user:\n :param uris: a set() of uris formatted like 'scheme:path'\n :param uris_hash: the hash or uris' components\n :type uris: set\n :type uris_hash: string\n :return: participant","docstring_summary":"- resolve uris to contact to build participants' set\n - compute participants_hash\n - create two ways links :\n uris<->uris_hash\n uris<->participants_hash","docstring_tokens":["-","resolve","uris","to","contact","to","build","participants","set","-","compute","participants_hash","-","create","two","ways","links",":","uris<","-",">","uris_hash","uris<","-",">","participants_hash"],"function":"def participants_from_uris(user, uris, uris_hash):\n \"\"\"\n - resolve uris to contact to build participants' set\n - compute participants_hash\n - create two ways links :\n uris<->uris_hash\n uris<->participants_hash\n\n :param user:\n :param uris: a set() of uris formatted like 'scheme:path'\n :param uris_hash: the hash or uris' components\n :type uris: set\n :type uris_hash: string\n :return: participant\n \"\"\"\n from caliopen_main.contact.core import ContactLookup\n\n participants = set()\n for uri in uris:\n try:\n contact = ContactLookup.get(user, uri.split(\":\", 1)[1])\n if contact:\n participants.add(\"contact:\" + contact.contact_id)\n else:\n participants.add(uri)\n except NotFound:\n participants.add(uri)\n\n participants = list(participants)\n participants.sort()\n participants_hash = hashlib.sha256(''.join(participants)).hexdigest()\n\n date = datetime.utcnow()\n\n # store uris_hash -> participants_hash\n ParticipantHash.create(user_id=user.user_id,\n kind=\"uris\",\n key=uris_hash,\n value=participants_hash,\n components=uris,\n date_insert=date)\n # store participants_hash -> uris_hash\n ParticipantHash.create(user_id=user.user_id,\n kind=\"participants\",\n key=participants_hash,\n value=uris_hash,\n components=participants,\n date_insert=date)\n for uri in uris:\n # uri->uris_hash\n HashLookup.create(user_id=user.user_id,\n uri=uri,\n hash=uris_hash,\n hash_components=uris,\n date_insert=date)\n\n return {'components': participants, 'hash': participants_hash}","function_tokens":["def","participants_from_uris","(","user",",","uris",",","uris_hash",")",":","from","caliopen_main",".","contact",".","core","import","ContactLookup","participants","=","set","(",")","for","uri","in","uris",":","try",":","contact","=","ContactLookup",".","get","(","user",",","uri",".","split","(","\":\"",",","1",")","[","1","]",")","if","contact",":","participants",".","add","(","\"contact:\"","+","contact",".","contact_id",")","else",":","participants",".","add","(","uri",")","except","NotFound",":","participants",".","add","(","uri",")","participants","=","list","(","participants",")","participants",".","sort","(",")","participants_hash","=","hashlib",".","sha256","(","''",".","join","(","participants",")",")",".","hexdigest","(",")","date","=","datetime",".","utcnow","(",")","# store uris_hash -> participants_hash","ParticipantHash",".","create","(","user_id","=","user",".","user_id",",","kind","=","\"uris\"",",","key","=","uris_hash",",","value","=","participants_hash",",","components","=","uris",",","date_insert","=","date",")","# store participants_hash -> uris_hash","ParticipantHash",".","create","(","user_id","=","user",".","user_id",",","kind","=","\"participants\"",",","key","=","participants_hash",",","value","=","uris_hash",",","components","=","participants",",","date_insert","=","date",")","for","uri","in","uris",":","# uri->uris_hash","HashLookup",".","create","(","user_id","=","user",".","user_id",",","uri","=","uri",",","hash","=","uris_hash",",","hash_components","=","uris",",","date_insert","=","date",")","return","{","'components'",":","participants",",","'hash'",":","participants_hash","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/participant\/core\/participant.py#L50-L106"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/discussion\/core\/discussion.py","language":"python","identifier":"Discussion.upsert_lookups_for_participants","parameters":"(self, participants)","argument_list":"","return_statement":"return self","docstring":"Ensure that participants lookup and hash lookup tables are filled\n for these participants\n\n :param user:\n :param participants: a collection of parameters\/Participant\n :type uris: set\n :return: Discussion","docstring_summary":"Ensure that participants lookup and hash lookup tables are filled\n for these participants","docstring_tokens":["Ensure","that","participants","lookup","and","hash","lookup","tables","are","filled","for","these","participants"],"function":"def upsert_lookups_for_participants(self, participants):\n \"\"\"\n Ensure that participants lookup and hash lookup tables are filled\n for these participants\n\n :param user:\n :param participants: a collection of parameters\/Participant\n :type uris: set\n :return: Discussion\n \"\"\"\n if not participants:\n raise Exception(\"missing mandatory property to create lookup entry\")\n\n uris = hash_participants_uri(participants)\n hash_lookup = ParticipantHash.find(user_id=self.user.user_id,\n kind=\"uris\",\n key=uris['hash'])\n if len(hash_lookup) > 0:\n self.participants = hash_lookup[0].components\n self.participants_hash = hash_lookup[0].value\n else:\n parts = participants_from_uris(self.user, uris['uris'],\n uris['hash'])\n self.participants = parts['components']\n self.participants_hash = parts['hash']\n\n return self","function_tokens":["def","upsert_lookups_for_participants","(","self",",","participants",")",":","if","not","participants",":","raise","Exception","(","\"missing mandatory property to create lookup entry\"",")","uris","=","hash_participants_uri","(","participants",")","hash_lookup","=","ParticipantHash",".","find","(","user_id","=","self",".","user",".","user_id",",","kind","=","\"uris\"",",","key","=","uris","[","'hash'","]",")","if","len","(","hash_lookup",")",">","0",":","self",".","participants","=","hash_lookup","[","0","]",".","components","self",".","participants_hash","=","hash_lookup","[","0","]",".","value","else",":","parts","=","participants_from_uris","(","self",".","user",",","uris","[","'uris'","]",",","uris","[","'hash'","]",")","self",".","participants","=","parts","[","'components'","]","self",".","participants_hash","=","parts","[","'hash'","]","return","self"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/discussion\/core\/discussion.py#L19-L45"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/discussion\/objects\/discussion.py","language":"python","identifier":"Discussion.upsert_lookups_for_participants","parameters":"(self, user, participants)","argument_list":"","return_statement":"return self","docstring":"Ensure that participants lookup and hash lookup tables are filled\n for these participants\n\n :param user:\n :param participants: a collection of parameters\/Participant\n :type uris: set\n :return: Discussion","docstring_summary":"Ensure that participants lookup and hash lookup tables are filled\n for these participants","docstring_tokens":["Ensure","that","participants","lookup","and","hash","lookup","tables","are","filled","for","these","participants"],"function":"def upsert_lookups_for_participants(self, user, participants):\n \"\"\"\n Ensure that participants lookup and hash lookup tables are filled\n for these participants\n\n :param user:\n :param participants: a collection of parameters\/Participant\n :type uris: set\n :return: Discussion\n \"\"\"\n if not participants:\n raise Exception(\"missing mandatory property to create lookup entry\")\n\n uris = hash_participants_uri(participants)\n self.uris = uris['uris']\n self.uris_hash = uris['hash']\n hash_lookup = ParticipantHash.find(user_id=user.user_id, kind=\"uris\",\n key=uris['hash'])\n if len(hash_lookup) > 0:\n self.participants = hash_lookup[0].components\n self.participants_hash = hash_lookup[0].value\n else:\n parts = participants_from_uris(user, uris['uris'],\n uris['hash'])\n self.participants = parts['components']\n self.participants_hash = parts['hash']\n\n return self","function_tokens":["def","upsert_lookups_for_participants","(","self",",","user",",","participants",")",":","if","not","participants",":","raise","Exception","(","\"missing mandatory property to create lookup entry\"",")","uris","=","hash_participants_uri","(","participants",")","self",".","uris","=","uris","[","'uris'","]","self",".","uris_hash","=","uris","[","'hash'","]","hash_lookup","=","ParticipantHash",".","find","(","user_id","=","user",".","user_id",",","kind","=","\"uris\"",",","key","=","uris","[","'hash'","]",")","if","len","(","hash_lookup",")",">","0",":","self",".","participants","=","hash_lookup","[","0","]",".","components","self",".","participants_hash","=","hash_lookup","[","0","]",".","value","else",":","parts","=","participants_from_uris","(","user",",","uris","[","'uris'","]",",","uris","[","'hash'","]",")","self",".","participants","=","parts","[","'components'","]","self",".","participants_hash","=","parts","[","'hash'","]","return","self"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/discussion\/objects\/discussion.py#L20-L47"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py","language":"python","identifier":"DiscussionIndexManager._prepare_search","parameters":"(self)","argument_list":"","return_statement":"return search","docstring":"Prepare a dsl.Search object on current index.","docstring_summary":"Prepare a dsl.Search object on current index.","docstring_tokens":["Prepare","a","dsl",".","Search","object","on","current","index","."],"function":"def _prepare_search(self):\n \"\"\"Prepare a dsl.Search object on current index.\"\"\"\n search = IndexedMessage.search(using=self.proxy,\n index=self.index)\n search = search.filter('term', user_id=self.user_id)\n return search","function_tokens":["def","_prepare_search","(","self",")",":","search","=","IndexedMessage",".","search","(","using","=","self",".","proxy",",","index","=","self",".","index",")","search","=","search",".","filter","(","'term'",",","user_id","=","self",".","user_id",")","return","search"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py#L40-L45"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py","language":"python","identifier":"DiscussionIndexManager.__search_ids","parameters":"(self, limit, offset, min_pi, max_pi, min_il, max_il)","argument_list":"","return_statement":"return {}, 0","docstring":"Search discussions ids as a bucket aggregation.","docstring_summary":"Search discussions ids as a bucket aggregation.","docstring_tokens":["Search","discussions","ids","as","a","bucket","aggregation","."],"function":"def __search_ids(self, limit, offset, min_pi, max_pi, min_il, max_il):\n \"\"\"Search discussions ids as a bucket aggregation.\"\"\"\n # TODO :\u00a0search on participants_hash instead\n search = self._prepare_search(). \\\n filter(\"range\", importance_level={'gte': min_il, 'lte': max_il})\n # Do bucket term aggregation, sorted by last_message date\n size = offset + (limit * 2)\n agg = A('terms', field='discussion_id',\n order={'last_message': 'desc'}, size=size, shard_size=size)\n search.aggs.bucket('discussions', agg) \\\n .metric('last_message', 'max', field='date_sort') \\\n .bucket(\"unread\", \"filter\", term={\"is_unread\": True})\n\n result = search.source(exclude=[\"*\"]).execute()\n if hasattr(result, 'aggregations'):\n # Something found\n buckets = result.aggregations.discussions.buckets\n # XXX Ugly but don't find a way to paginate on bucket aggregation\n buckets = buckets[offset:offset + limit]\n total = result.aggregations.discussions.sum_other_doc_count\n # remove last_message for now as it doesn't have relevant attrs\n for discussion in buckets:\n del discussion[\"last_message\"]\n return buckets, total\n log.debug('No result found on index {}'.format(self.index))\n return {}, 0","function_tokens":["def","__search_ids","(","self",",","limit",",","offset",",","min_pi",",","max_pi",",","min_il",",","max_il",")",":","# TODO :\u00a0search on participants_hash instead","search","=","self",".","_prepare_search","(",")",".","filter","(","\"range\"",",","importance_level","=","{","'gte'",":","min_il",",","'lte'",":","max_il","}",")","# Do bucket term aggregation, sorted by last_message date","size","=","offset","+","(","limit","*","2",")","agg","=","A","(","'terms'",",","field","=","'discussion_id'",",","order","=","{","'last_message'",":","'desc'","}",",","size","=","size",",","shard_size","=","size",")","search",".","aggs",".","bucket","(","'discussions'",",","agg",")",".","metric","(","'last_message'",",","'max'",",","field","=","'date_sort'",")",".","bucket","(","\"unread\"",",","\"filter\"",",","term","=","{","\"is_unread\"",":","True","}",")","result","=","search",".","source","(","exclude","=","[","\"*\"","]",")",".","execute","(",")","if","hasattr","(","result",",","'aggregations'",")",":","# Something found","buckets","=","result",".","aggregations",".","discussions",".","buckets","# XXX Ugly but don't find a way to paginate on bucket aggregation","buckets","=","buckets","[","offset",":","offset","+","limit","]","total","=","result",".","aggregations",".","discussions",".","sum_other_doc_count","# remove last_message for now as it doesn't have relevant attrs","for","discussion","in","buckets",":","del","discussion","[","\"last_message\"","]","return","buckets",",","total","log",".","debug","(","'No result found on index {}'",".","format","(","self",".","index",")",")","return","{","}",",","0"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py#L47-L72"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py","language":"python","identifier":"DiscussionIndexManager.get_last_message","parameters":"(self, discussion_id, min_il, max_il, include_draft)","argument_list":"","return_statement":"return result.hits[0]","docstring":"Get last message of a given discussion.","docstring_summary":"Get last message of a given discussion.","docstring_tokens":["Get","last","message","of","a","given","discussion","."],"function":"def get_last_message(self, discussion_id, min_il, max_il, include_draft):\n \"\"\"Get last message of a given discussion.\"\"\"\n search = self._prepare_search() \\\n .filter(\"match\", discussion_id=discussion_id) \\\n .filter(\"range\", importance_level={'gte': min_il, 'lte': max_il})\n\n if not include_draft:\n search = search.filter(\"match\", is_draft=False)\n\n result = search.sort('-date_sort')[0:1].execute()\n if not result.hits:\n # XXX what to do better if not found ?\n return {}\n return result.hits[0]","function_tokens":["def","get_last_message","(","self",",","discussion_id",",","min_il",",","max_il",",","include_draft",")",":","search","=","self",".","_prepare_search","(",")",".","filter","(","\"match\"",",","discussion_id","=","discussion_id",")",".","filter","(","\"range\"",",","importance_level","=","{","'gte'",":","min_il",",","'lte'",":","max_il","}",")","if","not","include_draft",":","search","=","search",".","filter","(","\"match\"",",","is_draft","=","False",")","result","=","search",".","sort","(","'-date_sort'",")","[","0",":","1","]",".","execute","(",")","if","not","result",".","hits",":","# XXX what to do better if not found ?","return","{","}","return","result",".","hits","[","0","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py#L74-L87"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py","language":"python","identifier":"DiscussionIndexManager.list_discussions","parameters":"(self, limit=10, offset=0, min_pi=0, max_pi=0,\n min_il=-10, max_il=10)","argument_list":"","return_statement":"return discussions, total + len(discussions)","docstring":"Build a list of limited number of discussions.","docstring_summary":"Build a list of limited number of discussions.","docstring_tokens":["Build","a","list","of","limited","number","of","discussions","."],"function":"def list_discussions(self, limit=10, offset=0, min_pi=0, max_pi=0,\n min_il=-10, max_il=10):\n \"\"\"Build a list of limited number of discussions.\"\"\"\n buckets, total = self.__search_ids(limit, offset, min_pi, max_pi,\n min_il,\n max_il)\n discussions = []\n for bucket in buckets:\n # TODO : les buckets seront des hash_participants, donc il faut cr\u00e9er la liste des discussion_id avant et it\u00e9rer l\u00e0-dessus\n message = self.get_last_message(bucket['key'],\n min_il, max_il,\n True)\n discussion = DiscussionIndex(bucket['key'])\n discussion.total_count = bucket['doc_count']\n discussion.unread_count = bucket['unread']['doc_count']\n discussion.last_message = message\n # XXX build others values from index\n discussions.append(discussion)\n # XXX total do not work completly, hack a bit\n return discussions, total + len(discussions)","function_tokens":["def","list_discussions","(","self",",","limit","=","10",",","offset","=","0",",","min_pi","=","0",",","max_pi","=","0",",","min_il","=","-","10",",","max_il","=","10",")",":","buckets",",","total","=","self",".","__search_ids","(","limit",",","offset",",","min_pi",",","max_pi",",","min_il",",","max_il",")","discussions","=","[","]","for","bucket","in","buckets",":","# TODO : les buckets seront des hash_participants, donc il faut cr\u00e9er la liste des discussion_id avant et it\u00e9rer l\u00e0-dessus","message","=","self",".","get_last_message","(","bucket","[","'key'","]",",","min_il",",","max_il",",","True",")","discussion","=","DiscussionIndex","(","bucket","[","'key'","]",")","discussion",".","total_count","=","bucket","[","'doc_count'","]","discussion",".","unread_count","=","bucket","[","'unread'","]","[","'doc_count'","]","discussion",".","last_message","=","message","# XXX build others values from index","discussions",".","append","(","discussion",")","# XXX total do not work completly, hack a bit","return","discussions",",","total","+","len","(","discussions",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py#L89-L108"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py","language":"python","identifier":"DiscussionIndexManager.message_belongs_to","parameters":"(self, discussion_id, message_id)","argument_list":"","return_statement":"return str(msg.discussion_id) == str(discussion_id)","docstring":"Search if a message belongs to a discussion","docstring_summary":"Search if a message belongs to a discussion","docstring_tokens":["Search","if","a","message","belongs","to","a","discussion"],"function":"def message_belongs_to(self, discussion_id, message_id):\n \"\"\"Search if a message belongs to a discussion\"\"\"\n\n msg = IndexedMessage.get(message_id, using=self.proxy, index=self.index)\n return str(msg.discussion_id) == str(discussion_id)","function_tokens":["def","message_belongs_to","(","self",",","discussion_id",",","message_id",")",":","msg","=","IndexedMessage",".","get","(","message_id",",","using","=","self",".","proxy",",","index","=","self",".","index",")","return","str","(","msg",".","discussion_id",")","==","str","(","discussion_id",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py#L110-L114"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py","language":"python","identifier":"DiscussionIndexManager.get_by_id","parameters":"(self, discussion_id, min_il=0, max_il=100)","argument_list":"","return_statement":"return discussion","docstring":"Return a single discussion by discussion_id","docstring_summary":"Return a single discussion by discussion_id","docstring_tokens":["Return","a","single","discussion","by","discussion_id"],"function":"def get_by_id(self, discussion_id, min_il=0, max_il=100):\n \"\"\"Return a single discussion by discussion_id\"\"\"\n\n # TODO : search by multiple discussion_id because they are hashes now\n search = self._prepare_search() \\\n .filter(\"match\", discussion_id=discussion_id)\n search.aggs.bucket('discussions', A('terms', field='discussion_id')) \\\n .bucket(\"unread\", \"filter\", term={\"is_unread\": True})\n result = search.execute()\n if not result.hits or len(result.hits) < 1:\n return None\n\n message = self.get_last_message(discussion_id, min_il, max_il, True)\n discussion = DiscussionIndex(discussion_id)\n discussion.total_count = result.hits.total\n discussion.last_message = message\n discussion.unread_count = result.aggregations.discussions.buckets[\n 0].unread.doc_count\n return discussion","function_tokens":["def","get_by_id","(","self",",","discussion_id",",","min_il","=","0",",","max_il","=","100",")",":","# TODO : search by multiple discussion_id because they are hashes now","search","=","self",".","_prepare_search","(",")",".","filter","(","\"match\"",",","discussion_id","=","discussion_id",")","search",".","aggs",".","bucket","(","'discussions'",",","A","(","'terms'",",","field","=","'discussion_id'",")",")",".","bucket","(","\"unread\"",",","\"filter\"",",","term","=","{","\"is_unread\"",":","True","}",")","result","=","search",".","execute","(",")","if","not","result",".","hits","or","len","(","result",".","hits",")","<","1",":","return","None","message","=","self",".","get_last_message","(","discussion_id",",","min_il",",","max_il",",","True",")","discussion","=","DiscussionIndex","(","discussion_id",")","discussion",".","total_count","=","result",".","hits",".","total","discussion",".","last_message","=","message","discussion",".","unread_count","=","result",".","aggregations",".","discussions",".","buckets","[","0","]",".","unread",".","doc_count","return","discussion"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py#L116-L134"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py","language":"python","identifier":"DiscussionIndexManager.get_by_uris","parameters":"(self, uris_hashes, min_il=0, max_il=100)","argument_list":"","return_statement":"return result","docstring":":param uris_hashes: an array of uris hashes\n :param min_il:\n :param max_il:\n :return:","docstring_summary":"","docstring_tokens":[],"function":"def get_by_uris(self, uris_hashes, min_il=0, max_il=100):\n \"\"\"\n\n :param uris_hashes: an array of uris hashes\n :param min_il:\n :param max_il:\n :return:\n \"\"\"\n search = self._prepare_search(). \\\n filter(\"terms\", discussion_id=uris_hashes). \\\n filter(\"range\", importance_level={'gte': min_il, 'lte': max_il})\n\n agg = A('terms', field='discussion_id',\n order={'last_message': 'desc'})\n search.aggs.bucket('discussions', agg). \\\n metric('last_message', 'max', field='date_sort'). \\\n bucket(\"unread\", \"filter\", term={\"is_unread\": True})\n\n result = search.execute()\n if not result.hits or len(result.hits) < 1:\n return None\n\n return result","function_tokens":["def","get_by_uris","(","self",",","uris_hashes",",","min_il","=","0",",","max_il","=","100",")",":","search","=","self",".","_prepare_search","(",")",".","filter","(","\"terms\"",",","discussion_id","=","uris_hashes",")",".","filter","(","\"range\"",",","importance_level","=","{","'gte'",":","min_il",",","'lte'",":","max_il","}",")","agg","=","A","(","'terms'",",","field","=","'discussion_id'",",","order","=","{","'last_message'",":","'desc'","}",")","search",".","aggs",".","bucket","(","'discussions'",",","agg",")",".","metric","(","'last_message'",",","'max'",",","field","=","'date_sort'",")",".","bucket","(","\"unread\"",",","\"filter\"",",","term","=","{","\"is_unread\"",":","True","}",")","result","=","search",".","execute","(",")","if","not","result",".","hits","or","len","(","result",".","hits",")","<","1",":","return","None","return","result"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/discussion\/store\/discussion_index.py#L136-L158"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"walk_with_boundary","parameters":"(message, boundary)","argument_list":"","return_statement":"","docstring":"Recurse in boundaries.","docstring_summary":"Recurse in boundaries.","docstring_tokens":["Recurse","in","boundaries","."],"function":"def walk_with_boundary(message, boundary):\n \"\"\"Recurse in boundaries.\"\"\"\n message.add_header(\"Mime-Boundary\", boundary)\n yield message\n if message.is_multipart():\n subboundary = message.get_boundary(\"\")\n for subpart in message.get_payload():\n for subsubpart in walk_with_boundary(subpart, subboundary):\n yield subsubpart","function_tokens":["def","walk_with_boundary","(","message",",","boundary",")",":","message",".","add_header","(","\"Mime-Boundary\"",",","boundary",")","yield","message","if","message",".","is_multipart","(",")",":","subboundary","=","message",".","get_boundary","(","\"\"",")","for","subpart","in","message",".","get_payload","(",")",":","for","subsubpart","in","walk_with_boundary","(","subpart",",","subboundary",")",":","yield","subsubpart"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L363-L371"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailAttachment.__init__","parameters":"(self, part)","argument_list":"","return_statement":"","docstring":"Extract attachment attributes from a mail part.","docstring_summary":"Extract attachment attributes from a mail part.","docstring_tokens":["Extract","attachment","attributes","from","a","mail","part","."],"function":"def __init__(self, part):\n \"\"\"Extract attachment attributes from a mail part.\"\"\"\n self.content_type = part.get_content_type()\n self.filename = part.get_filename()\n if self.filename:\n try:\n self.filename = self.filename.decode('utf-8')\n except UnicodeError:\n log.warn('Invalid filename encoding')\n content_disposition = part.get(\"Content-Disposition\")\n if content_disposition:\n dispositions = content_disposition.strip().split(\";\")\n self.is_inline = bool(dispositions[0].lower() == \"inline\")\n else:\n self.is_inline = True\n data = part.get_payload()\n self.can_index = False\n if any(x in part.get_content_type() for x in TEXT_CONTENT_TYPE):\n self.can_index = True\n charsets = part.get_charsets()\n if len(charsets) > 1:\n raise Exception('Too many charset %r for %s' %\n (charsets, part.get_payload()))\n self.charset = charsets[0]\n if 'Content-Transfer-Encoding' in part.keys():\n if part.get('Content-Transfer-Encoding') == 'base64':\n data = base64.b64decode(data)\n if self.charset:\n data = data.decode(self.charset, 'replace'). \\\n encode('utf-8')\n boundary = part.get(\"Mime-Boundary\", failobj=\"\")\n if boundary is not \"\":\n self.mime_boundary = boundary\n else:\n self.mime_boundary = \"\"\n self.data = data\n self.size = len(data) if data else 0","function_tokens":["def","__init__","(","self",",","part",")",":","self",".","content_type","=","part",".","get_content_type","(",")","self",".","filename","=","part",".","get_filename","(",")","if","self",".","filename",":","try",":","self",".","filename","=","self",".","filename",".","decode","(","'utf-8'",")","except","UnicodeError",":","log",".","warn","(","'Invalid filename encoding'",")","content_disposition","=","part",".","get","(","\"Content-Disposition\"",")","if","content_disposition",":","dispositions","=","content_disposition",".","strip","(",")",".","split","(","\";\"",")","self",".","is_inline","=","bool","(","dispositions","[","0","]",".","lower","(",")","==","\"inline\"",")","else",":","self",".","is_inline","=","True","data","=","part",".","get_payload","(",")","self",".","can_index","=","False","if","any","(","x","in","part",".","get_content_type","(",")","for","x","in","TEXT_CONTENT_TYPE",")",":","self",".","can_index","=","True","charsets","=","part",".","get_charsets","(",")","if","len","(","charsets",")",">","1",":","raise","Exception","(","'Too many charset %r for %s'","%","(","charsets",",","part",".","get_payload","(",")",")",")","self",".","charset","=","charsets","[","0","]","if","'Content-Transfer-Encoding'","in","part",".","keys","(",")",":","if","part",".","get","(","'Content-Transfer-Encoding'",")","==","'base64'",":","data","=","base64",".","b64decode","(","data",")","if","self",".","charset",":","data","=","data",".","decode","(","self",".","charset",",","'replace'",")",".","encode","(","'utf-8'",")","boundary","=","part",".","get","(","\"Mime-Boundary\"",",","failobj","=","\"\"",")","if","boundary","is","not","\"\"",":","self",".","mime_boundary","=","boundary","else",":","self",".","mime_boundary","=","\"\"","self",".","data","=","data","self",".","size","=","len","(","data",")","if","data","else","0"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L45-L81"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailAttachment.is_attachment","parameters":"(cls, part)","argument_list":"","return_statement":"return False","docstring":"Check if a part conform to Caliopen's attachment definition.\n\n A part is an \"attachment\" if it verifies ANY of this conditions :\n - it has a Content-Disposition header with param \"attachment\"\n - the main part of the Content-Type header\n is within \"attachment_types\" list below\n - the part is not a PGP\/Mime encryption envelope\n\n see https:\/\/www.iana.org\/assignments\/media-types\/media-types.xhtml\n\n :param part: an email\/message's part as return by the walk() func.\n :return: true or false","docstring_summary":"Check if a part conform to Caliopen's attachment definition.","docstring_tokens":["Check","if","a","part","conform","to","Caliopen","s","attachment","definition","."],"function":"def is_attachment(cls, part):\n \"\"\"Check if a part conform to Caliopen's attachment definition.\n\n A part is an \"attachment\" if it verifies ANY of this conditions :\n - it has a Content-Disposition header with param \"attachment\"\n - the main part of the Content-Type header\n is within \"attachment_types\" list below\n - the part is not a PGP\/Mime encryption envelope\n\n see https:\/\/www.iana.org\/assignments\/media-types\/media-types.xhtml\n\n :param part: an email\/message's part as return by the walk() func.\n :return: true or false\n \"\"\"\n content_disposition = part.get(\"Content-Disposition\")\n if content_disposition:\n dispositions = content_disposition.strip().split(\";\")\n if bool(dispositions[0].lower() == \"attachment\") or \\\n bool(dispositions[0].lower() == \"inline\"):\n return True\n\n attachment_types = (\n \"application\", \"image\", \"video\", \"audio\", \"message\", \"font\")\n if part.get_content_maintype() in attachment_types:\n return True\n return False","function_tokens":["def","is_attachment","(","cls",",","part",")",":","content_disposition","=","part",".","get","(","\"Content-Disposition\"",")","if","content_disposition",":","dispositions","=","content_disposition",".","strip","(",")",".","split","(","\";\"",")","if","bool","(","dispositions","[","0","]",".","lower","(",")","==","\"attachment\"",")","or","bool","(","dispositions","[","0","]",".","lower","(",")","==","\"inline\"",")",":","return","True","attachment_types","=","(","\"application\"",",","\"image\"",",","\"video\"",",","\"audio\"",",","\"message\"",",","\"font\"",")","if","part",".","get_content_maintype","(",")","in","attachment_types",":","return","True","return","False"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L84-L109"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailParticipant.__init__","parameters":"(self, type, addr)","argument_list":"","return_statement":"","docstring":"Parse an email address and create a participant.","docstring_summary":"Parse an email address and create a participant.","docstring_tokens":["Parse","an","email","address","and","create","a","participant","."],"function":"def __init__(self, type, addr):\n \"\"\"Parse an email address and create a participant.\"\"\"\n self.type = type\n parts = clean_email_address(addr)\n self.address = parts[0]\n self.label = parts[1]","function_tokens":["def","__init__","(","self",",","type",",","addr",")",":","self",".","type","=","type","parts","=","clean_email_address","(","addr",")","self",".","address","=","parts","[","0","]","self",".","label","=","parts","[","1","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L117-L122"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.__init__","parameters":"(self, raw_data)","argument_list":"","return_statement":"","docstring":"Parse an RFC2822,5322 mail message.","docstring_summary":"Parse an RFC2822,5322 mail message.","docstring_tokens":["Parse","an","RFC2822","5322","mail","message","."],"function":"def __init__(self, raw_data):\n \"\"\"Parse an RFC2822,5322 mail message.\"\"\"\n self.raw = raw_data\n self._extra_parameters = {}\n try:\n self.mail = Message(raw_data)\n except Exception as exc:\n log.error('Parse message failed %s' % exc)\n raise exc\n if self.mail.defects:\n # XXX what to do ?\n log.warn('Defects on parsed mail %r' % self.mail.defects)\n self.warning = self.mail.defects\n self.get_bodies()","function_tokens":["def","__init__","(","self",",","raw_data",")",":","self",".","raw","=","raw_data","self",".","_extra_parameters","=","{","}","try",":","self",".","mail","=","Message","(","raw_data",")","except","Exception","as","exc",":","log",".","error","(","'Parse message failed %s'","%","exc",")","raise","exc","if","self",".","mail",".","defects",":","# XXX what to do ?","log",".","warn","(","'Defects on parsed mail %r'","%","self",".","mail",".","defects",")","self",".","warning","=","self",".","mail",".","defects","self",".","get_bodies","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L141-L154"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.get_bodies","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Extract body alternatives, if any.","docstring_summary":"Extract body alternatives, if any.","docstring_tokens":["Extract","body","alternatives","if","any","."],"function":"def get_bodies(self):\n \"\"\"Extract body alternatives, if any.\"\"\"\n body_html = \"\"\n body_plain = \"\"\n\n if self.mail.get(\"Content-Type\", None):\n if self.mail.is_multipart():\n if self.mail.get_content_subtype() == 'encrypted':\n parts = self.mail.get_payload()\n if len(parts) == 2:\n self.body_plain = parts[1].get_payload()\n return\n else:\n log.warn('Encrypted message with invalid parts count')\n for top_level_part in self.mail.get_payload():\n if top_level_part.get_content_maintype() == \"multipart\":\n for alternative in top_level_part.get_payload():\n charset = alternative.get_param(\"charset\")\n if isinstance(charset, tuple):\n charset = unicode(charset[2],\n charset[0] or \"us-ascii\")\n if alternative.get_content_type() == \"text\/plain\":\n body_plain = alternative.get_payload(\n decode=True)\n self.body_plain = to_utf8(body_plain, charset)\n elif alternative.get_content_type() == \"text\/html\":\n body_html = alternative. \\\n get_payload(decode=True)\n self.body_html = to_utf8(body_html, charset)\n break\n else:\n charset = top_level_part.get_param(\"charset\")\n if isinstance(charset, tuple):\n charset = unicode(charset[2],\n charset[0] or \"us-ascii\")\n if top_level_part.get_content_type() == \"text\/plain\":\n body_plain = top_level_part. \\\n get_payload(decode=True)\n self.body_plain = to_utf8(body_plain, charset)\n elif top_level_part.get_content_type() == \"text\/html\":\n body_html = top_level_part.get_payload(decode=True)\n self.body_html = to_utf8(body_html, charset)\n else:\n charset = self.mail.get_param(\"charset\")\n if isinstance(charset, tuple):\n charset = unicode(charset[2], charset[0] or \"us-ascii\")\n if self.mail.get_content_type() == \"text\/html\":\n body_html = self.mail.get_payload(decode=True)\n self.body_html = to_utf8(body_html, charset)\n else:\n body_plain = self.mail.get_payload(decode=True)\n self.body_plain = to_utf8(body_plain, charset)\n else:\n self.body_plain = self.mail.get_payload(decode=True)","function_tokens":["def","get_bodies","(","self",")",":","body_html","=","\"\"","body_plain","=","\"\"","if","self",".","mail",".","get","(","\"Content-Type\"",",","None",")",":","if","self",".","mail",".","is_multipart","(",")",":","if","self",".","mail",".","get_content_subtype","(",")","==","'encrypted'",":","parts","=","self",".","mail",".","get_payload","(",")","if","len","(","parts",")","==","2",":","self",".","body_plain","=","parts","[","1","]",".","get_payload","(",")","return","else",":","log",".","warn","(","'Encrypted message with invalid parts count'",")","for","top_level_part","in","self",".","mail",".","get_payload","(",")",":","if","top_level_part",".","get_content_maintype","(",")","==","\"multipart\"",":","for","alternative","in","top_level_part",".","get_payload","(",")",":","charset","=","alternative",".","get_param","(","\"charset\"",")","if","isinstance","(","charset",",","tuple",")",":","charset","=","unicode","(","charset","[","2","]",",","charset","[","0","]","or","\"us-ascii\"",")","if","alternative",".","get_content_type","(",")","==","\"text\/plain\"",":","body_plain","=","alternative",".","get_payload","(","decode","=","True",")","self",".","body_plain","=","to_utf8","(","body_plain",",","charset",")","elif","alternative",".","get_content_type","(",")","==","\"text\/html\"",":","body_html","=","alternative",".","get_payload","(","decode","=","True",")","self",".","body_html","=","to_utf8","(","body_html",",","charset",")","break","else",":","charset","=","top_level_part",".","get_param","(","\"charset\"",")","if","isinstance","(","charset",",","tuple",")",":","charset","=","unicode","(","charset","[","2","]",",","charset","[","0","]","or","\"us-ascii\"",")","if","top_level_part",".","get_content_type","(",")","==","\"text\/plain\"",":","body_plain","=","top_level_part",".","get_payload","(","decode","=","True",")","self",".","body_plain","=","to_utf8","(","body_plain",",","charset",")","elif","top_level_part",".","get_content_type","(",")","==","\"text\/html\"",":","body_html","=","top_level_part",".","get_payload","(","decode","=","True",")","self",".","body_html","=","to_utf8","(","body_html",",","charset",")","else",":","charset","=","self",".","mail",".","get_param","(","\"charset\"",")","if","isinstance","(","charset",",","tuple",")",":","charset","=","unicode","(","charset","[","2","]",",","charset","[","0","]","or","\"us-ascii\"",")","if","self",".","mail",".","get_content_type","(",")","==","\"text\/html\"",":","body_html","=","self",".","mail",".","get_payload","(","decode","=","True",")","self",".","body_html","=","to_utf8","(","body_html",",","charset",")","else",":","body_plain","=","self",".","mail",".","get_payload","(","decode","=","True",")","self",".","body_plain","=","to_utf8","(","body_plain",",","charset",")","else",":","self",".","body_plain","=","self",".","mail",".","get_payload","(","decode","=","True",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L156-L209"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.subject","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Mail subject.","docstring_summary":"Mail subject.","docstring_tokens":["Mail","subject","."],"function":"def subject(self):\n \"\"\"Mail subject.\"\"\"\n s = decode_header(self.mail.get('Subject'))\n charset = s[0][1]\n if charset is not None:\n return s[0][0].decode(charset, \"replace\"). \\\n encode(\"utf-8\", \"replace\")\n else:\n try:\n return s[0][0].decode('utf-8', errors='ignore')\n except UnicodeError:\n log.warn('Invalid subject encoding')\n return s[0][0]","function_tokens":["def","subject","(","self",")",":","s","=","decode_header","(","self",".","mail",".","get","(","'Subject'",")",")","charset","=","s","[","0","]","[","1","]","if","charset","is","not","None",":","return","s","[","0","]","[","0","]",".","decode","(","charset",",","\"replace\"",")",".","encode","(","\"utf-8\"",",","\"replace\"",")","else",":","try",":","return","s","[","0","]","[","0","]",".","decode","(","'utf-8'",",","errors","=","'ignore'",")","except","UnicodeError",":","log",".","warn","(","'Invalid subject encoding'",")","return","s","[","0","]","[","0","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L212-L224"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.size","parameters":"(self)","argument_list":"","return_statement":"return len(self.mail.as_string())","docstring":"Get mail size in bytes.","docstring_summary":"Get mail size in bytes.","docstring_tokens":["Get","mail","size","in","bytes","."],"function":"def size(self):\n \"\"\"Get mail size in bytes.\"\"\"\n return len(self.mail.as_string())","function_tokens":["def","size","(","self",")",":","return","len","(","self",".","mail",".","as_string","(",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L227-L229"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.external_references","parameters":"(self)","argument_list":"","return_statement":"return {\n 'message_id': mid,\n 'parent_id': pid,\n 'ancestors_ids': ref_ids}","docstring":"Return mail references to be used as external references.\n\n making use of RFC5322 headers :\n message-id\n in-reply-to\n references\n headers' strings are pruned to extract email addresses only.","docstring_summary":"Return mail references to be used as external references.","docstring_tokens":["Return","mail","references","to","be","used","as","external","references","."],"function":"def external_references(self):\n \"\"\"Return mail references to be used as external references.\n\n making use of RFC5322 headers :\n message-id\n in-reply-to\n references\n headers' strings are pruned to extract email addresses only.\n \"\"\"\n ext_id = self.mail.get('Message-Id')\n parent_id = self.mail.get('In-Reply-To')\n ref = self.mail.get_all(\"References\")\n ref_addr = getaddresses(ref) if ref else None\n ref_ids = [address[1] for address in ref_addr] if ref_addr else []\n mid = clean_email_address(ext_id)[1] if ext_id else None\n if not mid:\n log.error('Unable to find correct message_id {}'.format(ext_id))\n mid = ext_id\n pid = clean_email_address(parent_id)[1] if parent_id else None\n if not pid:\n pid = parent_id\n return {\n 'message_id': mid,\n 'parent_id': pid,\n 'ancestors_ids': ref_ids}","function_tokens":["def","external_references","(","self",")",":","ext_id","=","self",".","mail",".","get","(","'Message-Id'",")","parent_id","=","self",".","mail",".","get","(","'In-Reply-To'",")","ref","=","self",".","mail",".","get_all","(","\"References\"",")","ref_addr","=","getaddresses","(","ref",")","if","ref","else","None","ref_ids","=","[","address","[","1","]","for","address","in","ref_addr","]","if","ref_addr","else","[","]","mid","=","clean_email_address","(","ext_id",")","[","1","]","if","ext_id","else","None","if","not","mid",":","log",".","error","(","'Unable to find correct message_id {}'",".","format","(","ext_id",")",")","mid","=","ext_id","pid","=","clean_email_address","(","parent_id",")","[","1","]","if","parent_id","else","None","if","not","pid",":","pid","=","parent_id","return","{","'message_id'",":","mid",",","'parent_id'",":","pid",",","'ancestors_ids'",":","ref_ids","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L232-L256"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.date","parameters":"(self)","argument_list":"","return_statement":"return datetime.datetime.now(tz=pytz.utc)","docstring":"Get UTC date from a mail message.","docstring_summary":"Get UTC date from a mail message.","docstring_tokens":["Get","UTC","date","from","a","mail","message","."],"function":"def date(self):\n \"\"\"Get UTC date from a mail message.\"\"\"\n mail_date = self.mail.get('Date')\n if mail_date:\n try:\n tmp_date = parsedate_tz(mail_date)\n return datetime.datetime.fromtimestamp(mktime_tz(tmp_date))\n except TypeError:\n log.error('Invalid date in mail {}'.format(mail_date))\n log.debug('No date on mail using now (UTC)')\n return datetime.datetime.now(tz=pytz.utc)","function_tokens":["def","date","(","self",")",":","mail_date","=","self",".","mail",".","get","(","'Date'",")","if","mail_date",":","try",":","tmp_date","=","parsedate_tz","(","mail_date",")","return","datetime",".","datetime",".","fromtimestamp","(","mktime_tz","(","tmp_date",")",")","except","TypeError",":","log",".","error","(","'Invalid date in mail {}'",".","format","(","mail_date",")",")","log",".","debug","(","'No date on mail using now (UTC)'",")","return","datetime",".","datetime",".","now","(","tz","=","pytz",".","utc",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L259-L269"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.participants","parameters":"(self)","argument_list":"","return_statement":"return participants","docstring":"Mail participants.","docstring_summary":"Mail participants.","docstring_tokens":["Mail","participants","."],"function":"def participants(self):\n \"\"\"Mail participants.\"\"\"\n participants = []\n for header in self.recipient_headers:\n addrs = []\n participant_type = header.capitalize()\n if self.mail.get(header):\n parts = self.mail.get(header).split('>,')\n if not parts:\n pass\n if parts and parts[0] == 'undisclosed-recipients:;':\n pass\n filtered = [x for x in parts if '@' in x]\n addrs.extend(filtered)\n for addr in addrs:\n participant = MailParticipant(participant_type, addr.lower())\n if participant.address == '' and participant.label == '':\n log.warn('Invalid email address {}'.format(addr))\n else:\n participants.append(participant)\n return participants","function_tokens":["def","participants","(","self",")",":","participants","=","[","]","for","header","in","self",".","recipient_headers",":","addrs","=","[","]","participant_type","=","header",".","capitalize","(",")","if","self",".","mail",".","get","(","header",")",":","parts","=","self",".","mail",".","get","(","header",")",".","split","(","'>,'",")","if","not","parts",":","pass","if","parts","and","parts","[","0","]","==","'undisclosed-recipients:;'",":","pass","filtered","=","[","x","for","x","in","parts","if","'@'","in","x","]","addrs",".","extend","(","filtered",")","for","addr","in","addrs",":","participant","=","MailParticipant","(","participant_type",",","addr",".","lower","(",")",")","if","participant",".","address","==","''","and","participant",".","label","==","''",":","log",".","warn","(","'Invalid email address {}'",".","format","(","addr",")",")","else",":","participants",".","append","(","participant",")","return","participants"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L272-L292"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.attachments","parameters":"(self)","argument_list":"","return_statement":"return attchs","docstring":"Extract parts which we consider as attachments.","docstring_summary":"Extract parts which we consider as attachments.","docstring_tokens":["Extract","parts","which","we","consider","as","attachments","."],"function":"def attachments(self):\n \"\"\"Extract parts which we consider as attachments.\"\"\"\n if not self.mail.is_multipart():\n return []\n attchs = []\n for p in walk_with_boundary(self.mail, \"\"):\n if not p.is_multipart():\n if p.get_content_subtype() == 'pgp-encrypted':\n # Special consideration. Do not present it as an attachment\n # but set _extra_parameters accordingly\n self._extra_parameters.update({'encrypted': 'pgp'})\n continue\n if MailAttachment.is_attachment(p):\n attchs.append(MailAttachment(p))\n return attchs","function_tokens":["def","attachments","(","self",")",":","if","not","self",".","mail",".","is_multipart","(",")",":","return","[","]","attchs","=","[","]","for","p","in","walk_with_boundary","(","self",".","mail",",","\"\"",")",":","if","not","p",".","is_multipart","(",")",":","if","p",".","get_content_subtype","(",")","==","'pgp-encrypted'",":","# Special consideration. Do not present it as an attachment","# but set _extra_parameters accordingly","self",".","_extra_parameters",".","update","(","{","'encrypted'",":","'pgp'","}",")","continue","if","MailAttachment",".","is_attachment","(","p",")",":","attchs",".","append","(","MailAttachment","(","p",")",")","return","attchs"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L295-L309"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.extra_parameters","parameters":"(self)","argument_list":"","return_statement":"return self._extra_parameters","docstring":"Mail message extra parameters.","docstring_summary":"Mail message extra parameters.","docstring_tokens":["Mail","message","extra","parameters","."],"function":"def extra_parameters(self):\n \"\"\"Mail message extra parameters.\"\"\"\n lists = self.mail.get_all(\"List-ID\")\n lists_addr = getaddresses(lists) if lists else None\n lists_ids = [address[1] for address in lists_addr] \\\n if lists_addr else []\n self._extra_parameters.update({'lists': lists_ids})\n return self._extra_parameters","function_tokens":["def","extra_parameters","(","self",")",":","lists","=","self",".","mail",".","get_all","(","\"List-ID\"",")","lists_addr","=","getaddresses","(","lists",")","if","lists","else","None","lists_ids","=","[","address","[","1","]","for","address","in","lists_addr","]","if","lists_addr","else","[","]","self",".","_extra_parameters",".","update","(","{","'lists'",":","lists_ids","}",")","return","self",".","_extra_parameters"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L312-L319"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.headers","parameters":"(self)","argument_list":"","return_statement":"return headers","docstring":"Extract all headers into list.\n\n Duplicate on headers exists, group them by name\n with a related list of values","docstring_summary":"Extract all headers into list.","docstring_tokens":["Extract","all","headers","into","list","."],"function":"def headers(self):\n \"\"\"Extract all headers into list.\n\n Duplicate on headers exists, group them by name\n with a related list of values\n \"\"\"\n\n def keyfunc(item):\n return item[0]\n\n # Group multiple value for same headers into a dict of list\n headers = {}\n data = sorted(self.mail.items(), key=keyfunc)\n for k, g in groupby(data, key=keyfunc):\n headers[k] = [x[1] for x in g]\n return headers","function_tokens":["def","headers","(","self",")",":","def","keyfunc","(","item",")",":","return","item","[","0","]","# Group multiple value for same headers into a dict of list","headers","=","{","}","data","=","sorted","(","self",".","mail",".","items","(",")",",","key","=","keyfunc",")","for","k",",","g","in","groupby","(","data",",","key","=","keyfunc",")",":","headers","[","k","]","=","[","x","[","1","]","for","x","in","g","]","return","headers"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L324-L339"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py","language":"python","identifier":"MailMessage.external_flags","parameters":"(self)","argument_list":"","return_statement":"return tags","docstring":"Get headers added by our fetcher that represent flags or labels\n set by external provider,\n returned as list of tags","docstring_summary":"Get headers added by our fetcher that represent flags or labels\n set by external provider,\n returned as list of tags","docstring_tokens":["Get","headers","added","by","our","fetcher","that","represent","flags","or","labels","set","by","external","provider","returned","as","list","of","tags"],"function":"def external_flags(self):\n \"\"\"\n Get headers added by our fetcher that represent flags or labels\n set by external provider,\n returned as list of tags\n \"\"\"\n tags = []\n for h in ['X-Fetched-Imap-Flags', 'X-Fetched-X-GM-LABELS']:\n enc_flags = self.mail.get(h)\n if enc_flags:\n flags_str = base64.decodestring(enc_flags)\n for flag in string.split(flags_str, '\\r\\n'):\n if flag not in EXCLUDED_EXT_FLAGS:\n tag = Tag()\n tag.name = flag\n tag.label = flag\n tag.type = 'imported'\n tags.append(tag)\n return tags","function_tokens":["def","external_flags","(","self",")",":","tags","=","[","]","for","h","in","[","'X-Fetched-Imap-Flags'",",","'X-Fetched-X-GM-LABELS'","]",":","enc_flags","=","self",".","mail",".","get","(","h",")","if","enc_flags",":","flags_str","=","base64",".","decodestring","(","enc_flags",")","for","flag","in","string",".","split","(","flags_str",",","'\\r\\n'",")",":","if","flag","not","in","EXCLUDED_EXT_FLAGS",":","tag","=","Tag","(",")","tag",".","name","=","flag","tag",".","label","=","flag","tag",".","type","=","'imported'","tags",".","append","(","tag",")","return","tags"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mail.py#L342-L360"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py","language":"python","identifier":"TwitterDM.subject","parameters":"(self)","argument_list":"","return_statement":"return ''","docstring":"tweets don't have subject\n should we return an excerpt ?","docstring_summary":"tweets don't have subject\n should we return an excerpt ?","docstring_tokens":["tweets","don","t","have","subject","should","we","return","an","excerpt","?"],"function":"def subject(self):\n \"\"\"\n tweets don't have subject\n should we return an excerpt ?\n \"\"\"\n return ''","function_tokens":["def","subject","(","self",")",":","return","''"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py#L49-L54"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py","language":"python","identifier":"TwitterDM.size","parameters":"(self)","argument_list":"","return_statement":"return len(self.dm.as_string())","docstring":"Get json tweet object size in bytes.","docstring_summary":"Get json tweet object size in bytes.","docstring_tokens":["Get","json","tweet","object","size","in","bytes","."],"function":"def size(self):\n \"\"\"Get json tweet object size in bytes.\"\"\"\n return len(self.dm.as_string())","function_tokens":["def","size","(","self",")",":","return","len","(","self",".","dm",".","as_string","(",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py#L57-L59"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py","language":"python","identifier":"TwitterDM.participants","parameters":"(self)","argument_list":"","return_statement":"return [TwitterParticipant(\"To\", clean_twitter_address(self.recipient_name)),\n TwitterParticipant(\"From\", clean_twitter_address(self.sender_name))]","docstring":"one sender only for now","docstring_summary":"one sender only for now","docstring_tokens":["one","sender","only","for","now"],"function":"def participants(self):\n \"one sender only for now\"\n return [TwitterParticipant(\"To\", clean_twitter_address(self.recipient_name)),\n TwitterParticipant(\"From\", clean_twitter_address(self.sender_name))]","function_tokens":["def","participants","(","self",")",":","return","[","TwitterParticipant","(","\"To\"",",","clean_twitter_address","(","self",".","recipient_name",")",")",",","TwitterParticipant","(","\"From\"",",","clean_twitter_address","(","self",".","sender_name",")",")","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py#L67-L70"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py","language":"python","identifier":"TwitterDM.attachments","parameters":"(self)","argument_list":"","return_statement":"return []","docstring":"TODO","docstring_summary":"TODO","docstring_tokens":["TODO"],"function":"def attachments(self):\n \"\"\"TODO\"\"\"\n return []","function_tokens":["def","attachments","(","self",")",":","return","[","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py#L77-L79"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py","language":"python","identifier":"TwitterDM.extra_parameters","parameters":"(self)","argument_list":"","return_statement":"return {}","docstring":"TODO","docstring_summary":"TODO","docstring_tokens":["TODO"],"function":"def extra_parameters(self):\n \"\"\"TODO\"\"\"\n return {}","function_tokens":["def","extra_parameters","(","self",")",":","return","{","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py#L82-L84"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py","language":"python","identifier":"TwitterParticipant.__init__","parameters":"(self, type, screen_name)","argument_list":"","return_statement":"","docstring":"Parse a twitter address and create a participant.","docstring_summary":"Parse a twitter address and create a participant.","docstring_tokens":["Parse","a","twitter","address","and","create","a","participant","."],"function":"def __init__(self, type, screen_name):\n \"\"\"Parse a twitter address and create a participant.\"\"\"\n self.type = type\n self.address = clean_twitter_address(screen_name)\n self.label = screen_name","function_tokens":["def","__init__","(","self",",","type",",","screen_name",")",":","self",".","type","=","type","self",".","address","=","clean_twitter_address","(","screen_name",")","self",".","label","=","screen_name"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/twitter.py#L94-L98"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py","language":"python","identifier":"MastodonStatus.subject","parameters":"(self)","argument_list":"","return_statement":"return ''","docstring":"toots don't have subject\n should we return an excerpt ?","docstring_summary":"toots don't have subject\n should we return an excerpt ?","docstring_tokens":["toots","don","t","have","subject","should","we","return","an","excerpt","?"],"function":"def subject(self):\n \"\"\"\n toots don't have subject\n should we return an excerpt ?\n \"\"\"\n return ''","function_tokens":["def","subject","(","self",")",":","return","''"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py#L52-L57"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py","language":"python","identifier":"MastodonStatus.size","parameters":"(self)","argument_list":"","return_statement":"return len(self.dm.as_string())","docstring":"Get json toot object size in bytes.","docstring_summary":"Get json toot object size in bytes.","docstring_tokens":["Get","json","toot","object","size","in","bytes","."],"function":"def size(self):\n \"\"\"Get json toot object size in bytes.\"\"\"\n return len(self.dm.as_string())","function_tokens":["def","size","(","self",")",":","return","len","(","self",".","dm",".","as_string","(",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py#L60-L62"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py","language":"python","identifier":"MastodonStatus.participants","parameters":"(self)","argument_list":"","return_statement":"return p","docstring":"one sender only for now","docstring_summary":"one sender only for now","docstring_tokens":["one","sender","only","for","now"],"function":"def participants(self):\n \"one sender only for now\"\n p = [self.sender]\n p.extend(self.recipients)\n return p","function_tokens":["def","participants","(","self",")",":","p","=","[","self",".","sender","]","p",".","extend","(","self",".","recipients",")","return","p"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py#L69-L73"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py","language":"python","identifier":"MastodonStatus.attachments","parameters":"(self)","argument_list":"","return_statement":"return []","docstring":"TODO","docstring_summary":"TODO","docstring_tokens":["TODO"],"function":"def attachments(self):\n \"\"\"TODO\"\"\"\n return []","function_tokens":["def","attachments","(","self",")",":","return","[","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py#L81-L83"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py","language":"python","identifier":"MastodonStatus.extra_parameters","parameters":"(self)","argument_list":"","return_statement":"return {}","docstring":"TODO","docstring_summary":"TODO","docstring_tokens":["TODO"],"function":"def extra_parameters(self):\n \"\"\"TODO\"\"\"\n return {}","function_tokens":["def","extra_parameters","(","self",")",":","return","{","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py#L86-L88"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py","language":"python","identifier":"MastodonParticipant.__init__","parameters":"(self, type, url)","argument_list":"","return_statement":"","docstring":"Parse a mastodon address and create a participant.","docstring_summary":"Parse a mastodon address and create a participant.","docstring_tokens":["Parse","a","mastodon","address","and","create","a","participant","."],"function":"def __init__(self, type, url):\n \"\"\"Parse a mastodon address and create a participant.\"\"\"\n domain, username = parse_mastodon_url(url)\n self.address = username + '@' + domain\n self.label = username\n self.type = type","function_tokens":["def","__init__","(","self",",","type",",","url",")",":","domain",",","username","=","parse_mastodon_url","(","url",")","self",".","address","=","username","+","'@'","+","domain","self",".","label","=","username","self",".","type","=","type"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parsers\/mastodon.py#L98-L103"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/core\/raw.py","language":"python","identifier":"RawMessage.create","parameters":"(cls, raw)","argument_list":"","return_statement":"return super(RawMessage, cls).create(raw_msg_id=key,\n raw_data=raw,\n raw_size=size)","docstring":"Create raw message.","docstring_summary":"Create raw message.","docstring_tokens":["Create","raw","message","."],"function":"def create(cls, raw):\n \"\"\"Create raw message.\"\"\"\n key = uuid.uuid4()\n size = len(raw)\n return super(RawMessage, cls).create(raw_msg_id=key,\n raw_data=raw,\n raw_size=size)","function_tokens":["def","create","(","cls",",","raw",")",":","key","=","uuid",".","uuid4","(",")","size","=","len","(","raw",")","return","super","(","RawMessage",",","cls",")",".","create","(","raw_msg_id","=","key",",","raw_data","=","raw",",","raw_size","=","size",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/core\/raw.py#L39-L45"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/core\/raw.py","language":"python","identifier":"RawMessage.get","parameters":"(cls, raw_msg_id)","argument_list":"","return_statement":"return raw_msg","docstring":"Get raw message from db or ObjectStorage service\n\n :param raw_msg_id:\n :return: a RawMessage or NotFound exception","docstring_summary":"Get raw message from db or ObjectStorage service","docstring_tokens":["Get","raw","message","from","db","or","ObjectStorage","service"],"function":"def get(cls, raw_msg_id):\n \"\"\"\n Get raw message from db or ObjectStorage service\n\n :param raw_msg_id:\n :return: a RawMessage or NotFound exception\n \"\"\"\n try:\n raw_msg = super(RawMessage, cls).get(raw_msg_id)\n except Exception as exc:\n log.warn(exc)\n raise NotFound\n\n if len(raw_msg.raw_data) == 0 and raw_msg.uri != '':\n # means raw message data have been stored in object store\n # need to retrieve raw_data from it\n url = urlparse.urlsplit(raw_msg.uri)\n path = url.path.strip(\"\/\")\n if url.scheme == 's3':\n minioConf = Configuration(\"global\").get(\"object_store\")\n minioClient = Minio(minioConf[\"endpoint\"],\n access_key=minioConf[\"access_key\"],\n secret_key=minioConf[\"secret_key\"],\n secure=False,\n region=minioConf[\"location\"])\n try:\n resp = minioClient.get_object(url.netloc, path)\n except Exception as exc:\n log.warn(exc)\n raise NotFound\n # resp is a urllib3.response.HTTPResponse class\n try:\n raw_msg.raw_data = resp.data\n except Exception as exc:\n log.warn(exc)\n raise NotFound\n else:\n log.warn(\"raw message uri scheme not implemented\")\n raise NotFound\n\n return raw_msg","function_tokens":["def","get","(","cls",",","raw_msg_id",")",":","try",":","raw_msg","=","super","(","RawMessage",",","cls",")",".","get","(","raw_msg_id",")","except","Exception","as","exc",":","log",".","warn","(","exc",")","raise","NotFound","if","len","(","raw_msg",".","raw_data",")","==","0","and","raw_msg",".","uri","!=","''",":","# means raw message data have been stored in object store","# need to retrieve raw_data from it","url","=","urlparse",".","urlsplit","(","raw_msg",".","uri",")","path","=","url",".","path",".","strip","(","\"\/\"",")","if","url",".","scheme","==","'s3'",":","minioConf","=","Configuration","(","\"global\"",")",".","get","(","\"object_store\"",")","minioClient","=","Minio","(","minioConf","[","\"endpoint\"","]",",","access_key","=","minioConf","[","\"access_key\"","]",",","secret_key","=","minioConf","[","\"secret_key\"","]",",","secure","=","False",",","region","=","minioConf","[","\"location\"","]",")","try",":","resp","=","minioClient",".","get_object","(","url",".","netloc",",","path",")","except","Exception","as","exc",":","log",".","warn","(","exc",")","raise","NotFound","# resp is a urllib3.response.HTTPResponse class","try",":","raw_msg",".","raw_data","=","resp",".","data","except","Exception","as","exc",":","log",".","warn","(","exc",")","raise","NotFound","else",":","log",".","warn","(","\"raw message uri scheme not implemented\"",")","raise","NotFound","return","raw_msg"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/core\/raw.py#L48-L88"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/core\/raw.py","language":"python","identifier":"RawMessage.get_for_user","parameters":"(cls, user_id, raw_msg_id)","argument_list":"","return_statement":"","docstring":"Get raw message by raw_msg_id, if message belongs to user.\n\n :param: user_id is a string\n :param: raw_msg_id is a string\n :return: a RawMessage or None","docstring_summary":"Get raw message by raw_msg_id, if message belongs to user.","docstring_tokens":["Get","raw","message","by","raw_msg_id","if","message","belongs","to","user","."],"function":"def get_for_user(cls, user_id, raw_msg_id):\n \"\"\"\n Get raw message by raw_msg_id, if message belongs to user.\n\n :param: user_id is a string\n :param: raw_msg_id is a string\n :return: a RawMessage or None\n \"\"\"\n if not UserRawLookup.belongs_to_user(user_id, raw_msg_id):\n return None\n try:\n return cls.get(raw_msg_id)\n except NotFound:\n return None","function_tokens":["def","get_for_user","(","cls",",","user_id",",","raw_msg_id",")",":","if","not","UserRawLookup",".","belongs_to_user","(","user_id",",","raw_msg_id",")",":","return","None","try",":","return","cls",".","get","(","raw_msg_id",")","except","NotFound",":","return","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/core\/raw.py#L91-L104"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/core\/raw.py","language":"python","identifier":"RawMessage.parse","parameters":"(self)","argument_list":"","return_statement":"return MailMessage(self)","docstring":"Parse raw message to get a formatted object.","docstring_summary":"Parse raw message to get a formatted object.","docstring_tokens":["Parse","raw","message","to","get","a","formatted","object","."],"function":"def parse(self):\n \"\"\"Parse raw message to get a formatted object.\"\"\"\n return MailMessage(self)","function_tokens":["def","parse","(","self",")",":","return","MailMessage","(","self",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/core\/raw.py#L106-L108"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py","language":"python","identifier":"Message.raw","parameters":"(self)","argument_list":"","return_statement":"return msg.raw_data","docstring":"Return raw text from pristine raw message.","docstring_summary":"Return raw text from pristine raw message.","docstring_tokens":["Return","raw","text","from","pristine","raw","message","."],"function":"def raw(self):\n \"\"\"Return raw text from pristine raw message.\"\"\"\n msg = RawMessage.get_for_user(self.user_id, self.raw_msg_id)\n return msg.raw_data","function_tokens":["def","raw","(","self",")",":","msg","=","RawMessage",".","get_for_user","(","self",".","user_id",",","self",".","raw_msg_id",")","return","msg",".","raw_data"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py#L80-L83"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py","language":"python","identifier":"Message.raw_json","parameters":"(self)","argument_list":"","return_statement":"return json.loads(msg.json_rep)","docstring":"Return json representation of pristine raw message.","docstring_summary":"Return json representation of pristine raw message.","docstring_tokens":["Return","json","representation","of","pristine","raw","message","."],"function":"def raw_json(self):\n \"\"\"Return json representation of pristine raw message.\"\"\"\n msg = RawMessage.get_for_user(self.user_id, self.raw_msg_id)\n return json.loads(msg.json_rep)","function_tokens":["def","raw_json","(","self",")",":","msg","=","RawMessage",".","get_for_user","(","self",".","user_id",",","self",".","raw_msg_id",")","return","json",".","loads","(","msg",".","json_rep",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py#L86-L89"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py","language":"python","identifier":"Message.user_identity","parameters":"(self)","argument_list":"","return_statement":"return self.user_identities[0] if self.user_identities else None","docstring":"return first user_identity","docstring_summary":"return first user_identity","docstring_tokens":["return","first","user_identity"],"function":"def user_identity(self):\n \"\"\"\n return first user_identity\n \"\"\"\n return self.user_identities[0] if self.user_identities else None","function_tokens":["def","user_identity","(","self",")",":","return","self",".","user_identities","[","0","]","if","self",".","user_identities","else","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py#L98-L102"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py","language":"python","identifier":"Message.create_draft","parameters":"(cls, user, **params)","argument_list":"","return_statement":"return message","docstring":"Create and save a new message (draft) for an user.\n\n :params: a NewMessage dict","docstring_summary":"Create and save a new message (draft) for an user.","docstring_tokens":["Create","and","save","a","new","message","(","draft",")","for","an","user","."],"function":"def create_draft(cls, user, **params):\n \"\"\"\n Create and save a new message (draft) for an user.\n\n :params: a NewMessage dict\n \"\"\"\n # silently remove unexpected props within patch if not in strict mode\n strict_patch = Configuration('global').get('apiV1.strict_patch', False)\n if not strict_patch:\n allowed_properties = [\n \"body\",\n \"message_id\",\n \"parent_id\",\n \"participants\",\n \"subject\",\n \"user_identities\",\n \"privacy_features\",\n ]\n for key, value in params.items():\n if key not in allowed_properties:\n del (params[key])\n try:\n draft_param = Draft(params, strict=strict_patch)\n if draft_param.message_id:\n draft_param.validate_uuid(user.user_id)\n else:\n draft_param.message_id = uuid.uuid4()\n discussion_id = draft_param.validate_consistency(user, True)\n except Exception as exc:\n log.warn(\"create_draft error %r\" % exc)\n raise exc\n\n message = Message(user)\n message.unmarshall_json_dict(draft_param.to_primitive())\n message.user_id = UUID(user.user_id)\n message.is_draft = True\n message.is_received = False\n message.discussion_id = discussion_id\n\n if not message.protocol:\n log.warn(\"failed to pick a protocol\")\n raise Exception(\"`message protocol is missing\")\n\n # forbid multiple protocol\n for participant in message.participants:\n if participant.protocol != message.protocol:\n log.warning(\"Different protocols detected {0} and {1}\".\n format(participant.protocol, message.protocol))\n\n message.date = message.date_sort = message.date_insert = \\\n datetime.datetime.now(tz=pytz.utc)\n\n try:\n message.marshall_db()\n message.save_db()\n except Exception as exc:\n log.warn(exc)\n raise exc\n try:\n message.marshall_index()\n message.save_index(wait_for=True)\n except Exception as exc:\n log.warn(exc)\n raise exc\n return message","function_tokens":["def","create_draft","(","cls",",","user",",","*","*","params",")",":","# silently remove unexpected props within patch if not in strict mode","strict_patch","=","Configuration","(","'global'",")",".","get","(","'apiV1.strict_patch'",",","False",")","if","not","strict_patch",":","allowed_properties","=","[","\"body\"",",","\"message_id\"",",","\"parent_id\"",",","\"participants\"",",","\"subject\"",",","\"user_identities\"",",","\"privacy_features\"",",","]","for","key",",","value","in","params",".","items","(",")",":","if","key","not","in","allowed_properties",":","del","(","params","[","key","]",")","try",":","draft_param","=","Draft","(","params",",","strict","=","strict_patch",")","if","draft_param",".","message_id",":","draft_param",".","validate_uuid","(","user",".","user_id",")","else",":","draft_param",".","message_id","=","uuid",".","uuid4","(",")","discussion_id","=","draft_param",".","validate_consistency","(","user",",","True",")","except","Exception","as","exc",":","log",".","warn","(","\"create_draft error %r\"","%","exc",")","raise","exc","message","=","Message","(","user",")","message",".","unmarshall_json_dict","(","draft_param",".","to_primitive","(",")",")","message",".","user_id","=","UUID","(","user",".","user_id",")","message",".","is_draft","=","True","message",".","is_received","=","False","message",".","discussion_id","=","discussion_id","if","not","message",".","protocol",":","log",".","warn","(","\"failed to pick a protocol\"",")","raise","Exception","(","\"`message protocol is missing\"",")","# forbid multiple protocol","for","participant","in","message",".","participants",":","if","participant",".","protocol","!=","message",".","protocol",":","log",".","warning","(","\"Different protocols detected {0} and {1}\"",".","format","(","participant",".","protocol",",","message",".","protocol",")",")","message",".","date","=","message",".","date_sort","=","message",".","date_insert","=","datetime",".","datetime",".","now","(","tz","=","pytz",".","utc",")","try",":","message",".","marshall_db","(",")","message",".","save_db","(",")","except","Exception","as","exc",":","log",".","warn","(","exc",")","raise","exc","try",":","message",".","marshall_index","(",")","message",".","save_index","(","wait_for","=","True",")","except","Exception","as","exc",":","log",".","warn","(","exc",")","raise","exc","return","message"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py#L105-L169"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py","language":"python","identifier":"Message.patch_draft","parameters":"(self, user, patch, **options)","argument_list":"","return_statement":"","docstring":"Operation specific to draft, before applying generic patch.","docstring_summary":"Operation specific to draft, before applying generic patch.","docstring_tokens":["Operation","specific","to","draft","before","applying","generic","patch","."],"function":"def patch_draft(self, user, patch, **options):\n \"\"\"Operation specific to draft, before applying generic patch.\"\"\"\n try:\n params = dict(patch)\n except Exception as exc:\n log.info(exc)\n raise err.PatchError(message=exc.message)\n # silently remove unexpected props within patch if not in strict mode\n strict_patch = Configuration('global').get('apiV1.strict_patch', False)\n if not strict_patch:\n allowed_properties = [\n \"body\",\n \"current_state\",\n \"user_identities\",\n \"message_id\",\n \"parent_id\",\n \"participants\",\n \"subject\",\n \"privacy_features\",\n ]\n for key, value in params.items():\n if key not in allowed_properties:\n del (params[key])\n\n for key, value in params[\"current_state\"].items():\n if key not in allowed_properties:\n del (params[\"current_state\"][key])\n\n try:\n self.get_db()\n self.unmarshall_db()\n except Exception as exc:\n log.info(\"patch_draft() failed to get msg from db: {}\".format(\n exc))\n raise exc\n\n if not self.is_draft:\n raise err.PatchUnprocessable(message=\"this message is not a draft\")\n try:\n current_state = params.pop(\"current_state\")\n draft_param = Draft(params, strict=strict_patch)\n except Exception as exc:\n log.info(exc)\n raise err.PatchError(message=exc.message)\n\n # add missing params to be able to check consistency\n self_dict = self.marshall_dict()\n if \"message_id\" not in params and self.message_id:\n draft_param.message_id = UUIDType().to_native(self.message_id)\n\n if \"parent_id\" not in params and self.parent_id:\n draft_param.parent_id = UUIDType().to_native(self.parent_id)\n\n if \"subject\" not in params:\n draft_param.subject = self.subject\n\n if \"participants\" not in params and self.participants:\n for participant in self_dict['participants']:\n indexed = IndexedParticipant(participant)\n draft_param.participants.append(indexed)\n\n\n if \"user_identities\" not in params and self.user_identities:\n draft_param.user_identities = self_dict[\"user_identities\"]\n\n # make sure the participant is present\n # and is consistent with selected user's identity\n try:\n new_discussion_id = draft_param.validate_consistency(user, False)\n except Exception as exc:\n log.info(\"consistency validation failed with err : {}\".format(exc))\n raise err.PatchError(message=exc.message)\n\n validated_draft = draft_param.serialize()\n validated_params = copy.deepcopy(params)\n\n if \"participants\" in params:\n validated_params[\"participants\"] = validated_draft[\"participants\"]\n if new_discussion_id != self.discussion_id:\n # discussion_id has changed, update draft's discussion_id\n current_state[\"discussion_id\"] = self.discussion_id\n validated_params[\"discussion_id\"] = new_discussion_id\n\n # remove empty ids from current state if any\n if \"parent_id\" in current_state and current_state[\"parent_id\"] == \"\":\n del (current_state[\"parent_id\"])\n\n # handle body key mapping to body_plain or body_html\n # TODO: handle plain\/html flag to map to right field\n if \"body\" in validated_params:\n validated_params[\"body_plain\"] = validated_params[\"body\"]\n del (validated_params[\"body\"])\n if \"body\" in current_state:\n current_state[\"body_plain\"] = current_state[\"body\"]\n del (current_state[\"body\"])\n\n # date should reflect last edit time\n current_state[\"date\"] = self.date\n current_state[\"date_sort\"] = self.date_sort\n validated_params[\"date\"] = validated_params[\"date_sort\"] = \\\n datetime.datetime.now(tz=pytz.utc)\n\n validated_params[\"current_state\"] = current_state\n\n if \"participants\" in current_state and self.participants:\n # replace participants' label and contact_ids\n # because frontend has up-to-date data for these properties\n # which are probably not the one stored in db\n db_parts = {}\n for p in self_dict['participants']:\n db_parts[p['protocol'] + p['type'] + p['address']] = p\n for i, p in enumerate(current_state['participants']):\n current_state['participants'][i] = db_parts[p['protocol'] + p['type'] + p['address']]\n\n try:\n self.apply_patch(validated_params, **options)\n except Exception as exc:\n log.info(\"apply_patch() failed with error : {}\".format(exc))\n raise exc","function_tokens":["def","patch_draft","(","self",",","user",",","patch",",","*","*","options",")",":","try",":","params","=","dict","(","patch",")","except","Exception","as","exc",":","log",".","info","(","exc",")","raise","err",".","PatchError","(","message","=","exc",".","message",")","# silently remove unexpected props within patch if not in strict mode","strict_patch","=","Configuration","(","'global'",")",".","get","(","'apiV1.strict_patch'",",","False",")","if","not","strict_patch",":","allowed_properties","=","[","\"body\"",",","\"current_state\"",",","\"user_identities\"",",","\"message_id\"",",","\"parent_id\"",",","\"participants\"",",","\"subject\"",",","\"privacy_features\"",",","]","for","key",",","value","in","params",".","items","(",")",":","if","key","not","in","allowed_properties",":","del","(","params","[","key","]",")","for","key",",","value","in","params","[","\"current_state\"","]",".","items","(",")",":","if","key","not","in","allowed_properties",":","del","(","params","[","\"current_state\"","]","[","key","]",")","try",":","self",".","get_db","(",")","self",".","unmarshall_db","(",")","except","Exception","as","exc",":","log",".","info","(","\"patch_draft() failed to get msg from db: {}\"",".","format","(","exc",")",")","raise","exc","if","not","self",".","is_draft",":","raise","err",".","PatchUnprocessable","(","message","=","\"this message is not a draft\"",")","try",":","current_state","=","params",".","pop","(","\"current_state\"",")","draft_param","=","Draft","(","params",",","strict","=","strict_patch",")","except","Exception","as","exc",":","log",".","info","(","exc",")","raise","err",".","PatchError","(","message","=","exc",".","message",")","# add missing params to be able to check consistency","self_dict","=","self",".","marshall_dict","(",")","if","\"message_id\"","not","in","params","and","self",".","message_id",":","draft_param",".","message_id","=","UUIDType","(",")",".","to_native","(","self",".","message_id",")","if","\"parent_id\"","not","in","params","and","self",".","parent_id",":","draft_param",".","parent_id","=","UUIDType","(",")",".","to_native","(","self",".","parent_id",")","if","\"subject\"","not","in","params",":","draft_param",".","subject","=","self",".","subject","if","\"participants\"","not","in","params","and","self",".","participants",":","for","participant","in","self_dict","[","'participants'","]",":","indexed","=","IndexedParticipant","(","participant",")","draft_param",".","participants",".","append","(","indexed",")","if","\"user_identities\"","not","in","params","and","self",".","user_identities",":","draft_param",".","user_identities","=","self_dict","[","\"user_identities\"","]","# make sure the participant is present","# and is consistent with selected user's identity","try",":","new_discussion_id","=","draft_param",".","validate_consistency","(","user",",","False",")","except","Exception","as","exc",":","log",".","info","(","\"consistency validation failed with err : {}\"",".","format","(","exc",")",")","raise","err",".","PatchError","(","message","=","exc",".","message",")","validated_draft","=","draft_param",".","serialize","(",")","validated_params","=","copy",".","deepcopy","(","params",")","if","\"participants\"","in","params",":","validated_params","[","\"participants\"","]","=","validated_draft","[","\"participants\"","]","if","new_discussion_id","!=","self",".","discussion_id",":","# discussion_id has changed, update draft's discussion_id","current_state","[","\"discussion_id\"","]","=","self",".","discussion_id","validated_params","[","\"discussion_id\"","]","=","new_discussion_id","# remove empty ids from current state if any","if","\"parent_id\"","in","current_state","and","current_state","[","\"parent_id\"","]","==","\"\"",":","del","(","current_state","[","\"parent_id\"","]",")","# handle body key mapping to body_plain or body_html","# TODO: handle plain\/html flag to map to right field","if","\"body\"","in","validated_params",":","validated_params","[","\"body_plain\"","]","=","validated_params","[","\"body\"","]","del","(","validated_params","[","\"body\"","]",")","if","\"body\"","in","current_state",":","current_state","[","\"body_plain\"","]","=","current_state","[","\"body\"","]","del","(","current_state","[","\"body\"","]",")","# date should reflect last edit time","current_state","[","\"date\"","]","=","self",".","date","current_state","[","\"date_sort\"","]","=","self",".","date_sort","validated_params","[","\"date\"","]","=","validated_params","[","\"date_sort\"","]","=","datetime",".","datetime",".","now","(","tz","=","pytz",".","utc",")","validated_params","[","\"current_state\"","]","=","current_state","if","\"participants\"","in","current_state","and","self",".","participants",":","# replace participants' label and contact_ids","# because frontend has up-to-date data for these properties","# which are probably not the one stored in db","db_parts","=","{","}","for","p","in","self_dict","[","'participants'","]",":","db_parts","[","p","[","'protocol'","]","+","p","[","'type'","]","+","p","[","'address'","]","]","=","p","for","i",",","p","in","enumerate","(","current_state","[","'participants'","]",")",":","current_state","[","'participants'","]","[","i","]","=","db_parts","[","p","[","'protocol'","]","+","p","[","'type'","]","+","p","[","'address'","]","]","try",":","self",".","apply_patch","(","validated_params",",","*","*","options",")","except","Exception","as","exc",":","log",".","info","(","\"apply_patch() failed with error : {}\"",".","format","(","exc",")",")","raise","exc"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/objects\/message.py#L171-L289"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parameters\/draft.py","language":"python","identifier":"Draft.validate_consistency","parameters":"(self, user, is_new)","argument_list":"","return_statement":"return self.discussion_id","docstring":"Function used by create_draft and patch_draft\n to unsure provided params are consistent with draft's context\n\n :param user : the user object\n :param is_new : if true indicates that we want to validate a new draft,\n otherwise it is an update of existing one\n\n If needed, draft is modified to conform.","docstring_summary":"Function used by create_draft and patch_draft\n to unsure provided params are consistent with draft's context","docstring_tokens":["Function","used","by","create_draft","and","patch_draft","to","unsure","provided","params","are","consistent","with","draft","s","context"],"function":"def validate_consistency(self, user, is_new):\n \"\"\"\n Function used by create_draft and patch_draft\n to unsure provided params are consistent with draft's context\n\n :param user : the user object\n :param is_new : if true indicates that we want to validate a new draft,\n otherwise it is an update of existing one\n\n If needed, draft is modified to conform.\n \"\"\"\n try:\n self.validate()\n\n except Exception as exc:\n log.exception(\"draft validation failed with error {}\".format(exc))\n raise exc\n # copy body to body_plain TODO : manage plain or html switch user pref\n if hasattr(self, \"body\") and self.body is not None:\n self.body_plain = self.body\n else:\n self.body = self.body_plain = \"\"\n\n # fill field consistently\n # based on current user's selected identity\n from_participant = self._add_from_participant(user)\n\n if hasattr(self, 'parent_id') \\\n and self.parent_id is not None \\\n and self.parent_id != \"\" \\\n and is_new:\n # it is a reply, enforce participants\n # and other mandatory properties\n try:\n parent_msg = ModelMessage.get(user_id=user.user_id,\n message_id=self.parent_id)\n except NotFound:\n raise PatchError(message=\"parent message not found\")\n self._build_participants_for_reply(parent_msg, from_participant)\n self.discussion_id = self.hash_participants\n self._update_external_references(user)\n self._build_subject_for_reply(parent_msg)\n elif self.discussion_id != self.hash_participants:\n # participants_hash has changed, update lookups\n self.discussion_id = self.hash_participants\n\n return self.discussion_id","function_tokens":["def","validate_consistency","(","self",",","user",",","is_new",")",":","try",":","self",".","validate","(",")","except","Exception","as","exc",":","log",".","exception","(","\"draft validation failed with error {}\"",".","format","(","exc",")",")","raise","exc","# copy body to body_plain TODO : manage plain or html switch user pref","if","hasattr","(","self",",","\"body\"",")","and","self",".","body","is","not","None",":","self",".","body_plain","=","self",".","body","else",":","self",".","body","=","self",".","body_plain","=","\"\"","# fill field consistently","# based on current user's selected identity","from_participant","=","self",".","_add_from_participant","(","user",")","if","hasattr","(","self",",","'parent_id'",")","and","self",".","parent_id","is","not","None","and","self",".","parent_id","!=","\"\"","and","is_new",":","# it is a reply, enforce participants","# and other mandatory properties","try",":","parent_msg","=","ModelMessage",".","get","(","user_id","=","user",".","user_id",",","message_id","=","self",".","parent_id",")","except","NotFound",":","raise","PatchError","(","message","=","\"parent message not found\"",")","self",".","_build_participants_for_reply","(","parent_msg",",","from_participant",")","self",".","discussion_id","=","self",".","hash_participants","self",".","_update_external_references","(","user",")","self",".","_build_subject_for_reply","(","parent_msg",")","elif","self",".","discussion_id","!=","self",".","hash_participants",":","# participants_hash has changed, update lookups","self",".","discussion_id","=","self",".","hash_participants","return","self",".","discussion_id"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parameters\/draft.py#L36-L82"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parameters\/draft.py","language":"python","identifier":"Draft._build_participants_for_reply","parameters":"(self, parent_msg, sender)","argument_list":"","return_statement":"","docstring":"Build participants list from message in-reply to.\n\n - former 'From' recipients are replaced by 'To' recipients\n - provided identity is used to fill the new 'From' participant\n - new sender is removed from former recipients\n\n :param sender: participant previously computed by _add_from_participant","docstring_summary":"Build participants list from message in-reply to.","docstring_tokens":["Build","participants","list","from","message","in","-","reply","to","."],"function":"def _build_participants_for_reply(self, parent_msg, sender):\n \"\"\"\n Build participants list from message in-reply to.\n\n - former 'From' recipients are replaced by 'To' recipients\n - provided identity is used to fill the new 'From' participant\n - new sender is removed from former recipients\n\n :param sender: participant previously computed by _add_from_participant\n \"\"\"\n if not self.parent_id:\n return\n # TODO : manage reply to discussion-list\n # TODO :\u00a0and to messages that have a `reply-to` header\n self.participants = []\n sender['address'] = sender['address'].lower()\n for i, participant in enumerate(parent_msg.participants):\n participant['address'] = participant['address'].lower()\n if not re.match(sender['address'], participant['address'],\n re.IGNORECASE):\n if re.match(\"from\", participant['type'], re.IGNORECASE):\n participant[\"type\"] = \"To\"\n self.participants.append(participant)\n elif not re.match(\"list-id\", participant['type'],\n re.IGNORECASE):\n self.participants.append(participant)\n elif not re.match(\"from\", participant['type'], re.IGNORECASE):\n self.participants.append(participant)\n\n # add sender\n self.participants.append(sender)","function_tokens":["def","_build_participants_for_reply","(","self",",","parent_msg",",","sender",")",":","if","not","self",".","parent_id",":","return","# TODO : manage reply to discussion-list","# TODO :\u00a0and to messages that have a `reply-to` header","self",".","participants","=","[","]","sender","[","'address'","]","=","sender","[","'address'","]",".","lower","(",")","for","i",",","participant","in","enumerate","(","parent_msg",".","participants",")",":","participant","[","'address'","]","=","participant","[","'address'","]",".","lower","(",")","if","not","re",".","match","(","sender","[","'address'","]",",","participant","[","'address'","]",",","re",".","IGNORECASE",")",":","if","re",".","match","(","\"from\"",",","participant","[","'type'","]",",","re",".","IGNORECASE",")",":","participant","[","\"type\"","]","=","\"To\"","self",".","participants",".","append","(","participant",")","elif","not","re",".","match","(","\"list-id\"",",","participant","[","'type'","]",",","re",".","IGNORECASE",")",":","self",".","participants",".","append","(","participant",")","elif","not","re",".","match","(","\"from\"",",","participant","[","'type'","]",",","re",".","IGNORECASE",")",":","self",".","participants",".","append","(","participant",")","# add sender","self",".","participants",".","append","(","sender",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parameters\/draft.py#L126-L156"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parameters\/draft.py","language":"python","identifier":"Draft._build_subject_for_reply","parameters":"(self, parent_msg)","argument_list":"","return_statement":"","docstring":":param user:\n :return:","docstring_summary":"","docstring_tokens":[],"function":"def _build_subject_for_reply(self, parent_msg):\n \"\"\"\n\n :param user:\n :return:\n \"\"\"\n # check subject consistency\n # (https:\/\/www.wikiwand.com\/en\/List_of_email_subject_abbreviations)\n # for now, we use standard prefix \u00abRe: \u00bb (RFC5322#section-3.6.5)\n p = re.compile(\n '([\\[\\(] *)?(RE?S?|FYI|RIF|I|FS|VB|RV|ENC|ODP|PD|YNT|ILT|SV|VS|VL|AW|WG|\u0391\u03a0|\u03a3\u03a7\u0395\u03a4|\u03a0\u03a1\u0398|\u05ea\u05d2\u05d5\u05d1\u05d4|\u05d4\u05d5\u05e2\u05d1\u05e8|\u4e3b\u9898|\u8f6c\u53d1|FWD?) *([-:;)\\]][ :;\\])-]*|$)|\\]+ *$',\n re.IGNORECASE)\n # if hasattr(self, 'subject') and self.subject is not None:\n # if p.sub('', self.subject).strip() != p.sub('',\n # parent_msg.subject).strip():\n # raise PatchConflict(message=\"subject has been changed\")\n # else:\n # # no subject property provided :\n # # add subject from context with only one \"Re: \" prefix\n self.subject = \"Re: \" + p.sub('', parent_msg.subject, -1)","function_tokens":["def","_build_subject_for_reply","(","self",",","parent_msg",")",":","# check subject consistency","# (https:\/\/www.wikiwand.com\/en\/List_of_email_subject_abbreviations)","# for now, we use standard prefix \u00abRe: \u00bb (RFC5322#section-3.6.5)","p","=","re",".","compile","(","'([\\[\\(] *)?(RE?S?|FYI|RIF|I|FS|VB|RV|ENC|ODP|PD|YNT|ILT|SV|VS|VL|AW|WG|\u0391\u03a0|\u03a3\u03a7\u0395\u03a4|\u03a0\u03a1\u0398|\u05ea\u05d2\u05d5\u05d1\u05d4|\u05d4\u05d5\u05e2\u05d1\u05e8|\u4e3b\u9898|\u8f6c\u53d1|FWD?) *([-:;)\\]][ :;\\])-]*|$)|\\]+ *$',","","re",".","IGNORECASE",")","# if hasattr(self, 'subject') and self.subject is not None:","# if p.sub('', self.subject).strip() != p.sub('',","# parent_msg.subject).strip():","# raise PatchConflict(message=\"subject has been changed\")","# else:","# # no subject property provided :","# # add subject from context with only one \"Re: \" prefix","self",".","subject","=","\"Re: \"","+","p",".","sub","(","''",",","parent_msg",".","subject",",","-","1",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parameters\/draft.py#L158-L177"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/parameters\/draft.py","language":"python","identifier":"Draft._update_external_references","parameters":"(self, user)","argument_list":"","return_statement":"","docstring":"copy externals references from current draft's ancestor\n and change parent_id to reflect new message's hierarchy\n :return:","docstring_summary":"copy externals references from current draft's ancestor\n and change parent_id to reflect new message's hierarchy\n :return:","docstring_tokens":["copy","externals","references","from","current","draft","s","ancestor","and","change","parent_id","to","reflect","new","message","s","hierarchy",":","return",":"],"function":"def _update_external_references(self, user):\n \"\"\"\n copy externals references from current draft's ancestor\n and change parent_id to reflect new message's hierarchy\n :return:\n \"\"\"\n from caliopen_main.message.objects.message import Message\n parent_msg = Message(user, message_id=self.parent_id)\n parent_msg.get_db()\n parent_msg.unmarshall_db()\n if parent_msg:\n self.external_references = ExternalReferences(\n vars(parent_msg.external_references))\n self.external_references.ancestors_ids.append(\n parent_msg.external_references.message_id)\n self.external_references.parent_id = parent_msg.external_references.message_id\n self.external_references.message_id = \"\"","function_tokens":["def","_update_external_references","(","self",",","user",")",":","from","caliopen_main",".","message",".","objects",".","message","import","Message","parent_msg","=","Message","(","user",",","message_id","=","self",".","parent_id",")","parent_msg",".","get_db","(",")","parent_msg",".","unmarshall_db","(",")","if","parent_msg",":","self",".","external_references","=","ExternalReferences","(","vars","(","parent_msg",".","external_references",")",")","self",".","external_references",".","ancestors_ids",".","append","(","parent_msg",".","external_references",".","message_id",")","self",".","external_references",".","parent_id","=","parent_msg",".","external_references",".","message_id","self",".","external_references",".","message_id","=","\"\""],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/parameters\/draft.py#L179-L195"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/store\/message_index.py","language":"python","identifier":"IndexedMessage.message_id","parameters":"(self)","argument_list":"","return_statement":"return self.meta.id","docstring":"The compound primary key for a message is message_id.","docstring_summary":"The compound primary key for a message is message_id.","docstring_tokens":["The","compound","primary","key","for","a","message","is","message_id","."],"function":"def message_id(self):\n \"\"\"The compound primary key for a message is message_id.\"\"\"\n return self.meta.id","function_tokens":["def","message_id","(","self",")",":","return","self",".","meta",".","id"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/store\/message_index.py#L48-L50"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/main\/py.main\/caliopen_main\/message\/store\/message_index.py","language":"python","identifier":"IndexedMessage.build_mapping","parameters":"(cls)","argument_list":"","return_statement":"return m","docstring":"Generate the mapping definition for indexed messages","docstring_summary":"Generate the mapping definition for indexed messages","docstring_tokens":["Generate","the","mapping","definition","for","indexed","messages"],"function":"def build_mapping(cls):\n \"\"\"Generate the mapping definition for indexed messages\"\"\"\n m = Mapping(cls.doc_type)\n m.meta('_all', enabled=True)\n m.field('user_id', 'keyword')\n # attachments\n m.field('attachments', Nested(doc_class=IndexedMessageAttachment,\n include_in_all=True,\n properties={\n \"content_type\": Keyword(),\n \"file_name\": Keyword(),\n \"is_inline\": Boolean(),\n \"size\": Integer(),\n \"temp_id\": Keyword(),\n \"url\": Keyword(),\n \"mime_boundary\": Keyword()\n })\n )\n m.field('body_html', 'text', fields={\n \"normalized\": {\"type\": \"text\", \"analyzer\": \"text_analyzer\"}\n })\n m.field('body_plain', 'text', fields={\n \"normalized\": {\"type\": \"text\", \"analyzer\": \"text_analyzer\"}\n })\n m.field('date', 'date')\n m.field('date_delete', 'date')\n m.field('date_insert', 'date')\n m.field('date_sort', 'date')\n m.field('discussion_id', 'keyword')\n # external references\n m.field('external_references',\n Nested(doc_class=IndexedExternalReferences,\n include_in_all=True,\n properties={\n \"ancestors_ids\": Keyword(),\n \"message_id\": Keyword(),\n \"parent_id\": Keyword()\n })\n )\n m.field('importance_level', 'short')\n m.field('is_answered', 'boolean')\n m.field('is_draft', 'boolean')\n m.field('is_unread', 'boolean')\n m.field('is_received', 'boolean')\n m.field('message_id', 'keyword')\n m.field('parent_id', 'keyword')\n # participants\n participants = Nested(doc_class=IndexedParticipant,\n include_in_all=True)\n participants.field(\"address\", \"text\", analyzer=\"text_analyzer\",\n fields={\n \"raw\": {\"type\": \"keyword\"},\n \"parts\": {\"type\": \"text\",\n \"analyzer\": \"email_analyzer\"}\n })\n participants.field(\"contact_ids\", Keyword(multi=True))\n participants.field(\"label\", \"text\", analyzer=\"text_analyzer\")\n participants.field(\"protocol\", Keyword())\n participants.field(\"type\", Keyword())\n m.field('participants', participants)\n # PI\n pi = Object(doc_class=PIIndexModel, include_in_all=True,\n properties={\n \"technic\": \"integer\",\n \"comportment\": \"integer\",\n \"context\": \"integer\",\n \"version\": \"integer\",\n \"date_update\": \"date\"\n })\n m.field(\"pi\", pi)\n m.field('privacy_features', Object(include_in_all=True))\n m.field('raw_msg_id', \"keyword\")\n m.field('subject', 'text', fields={\n \"normalized\": {\"type\": \"text\", \"analyzer\": \"text_analyzer\"}\n })\n m.field('tags', Keyword(multi=True))\n\n m.field('subject', 'text')\n m.field('tags', Keyword(multi=True))\n m.field('protocol', 'keyword')\n m.field('user_identities', Keyword(multi=True))\n\n return m","function_tokens":["def","build_mapping","(","cls",")",":","m","=","Mapping","(","cls",".","doc_type",")","m",".","meta","(","'_all'",",","enabled","=","True",")","m",".","field","(","'user_id'",",","'keyword'",")","# attachments","m",".","field","(","'attachments'",",","Nested","(","doc_class","=","IndexedMessageAttachment",",","include_in_all","=","True",",","properties","=","{","\"content_type\"",":","Keyword","(",")",",","\"file_name\"",":","Keyword","(",")",",","\"is_inline\"",":","Boolean","(",")",",","\"size\"",":","Integer","(",")",",","\"temp_id\"",":","Keyword","(",")",",","\"url\"",":","Keyword","(",")",",","\"mime_boundary\"",":","Keyword","(",")","}",")",")","m",".","field","(","'body_html'",",","'text'",",","fields","=","{","\"normalized\"",":","{","\"type\"",":","\"text\"",",","\"analyzer\"",":","\"text_analyzer\"","}","}",")","m",".","field","(","'body_plain'",",","'text'",",","fields","=","{","\"normalized\"",":","{","\"type\"",":","\"text\"",",","\"analyzer\"",":","\"text_analyzer\"","}","}",")","m",".","field","(","'date'",",","'date'",")","m",".","field","(","'date_delete'",",","'date'",")","m",".","field","(","'date_insert'",",","'date'",")","m",".","field","(","'date_sort'",",","'date'",")","m",".","field","(","'discussion_id'",",","'keyword'",")","# external references","m",".","field","(","'external_references'",",","Nested","(","doc_class","=","IndexedExternalReferences",",","include_in_all","=","True",",","properties","=","{","\"ancestors_ids\"",":","Keyword","(",")",",","\"message_id\"",":","Keyword","(",")",",","\"parent_id\"",":","Keyword","(",")","}",")",")","m",".","field","(","'importance_level'",",","'short'",")","m",".","field","(","'is_answered'",",","'boolean'",")","m",".","field","(","'is_draft'",",","'boolean'",")","m",".","field","(","'is_unread'",",","'boolean'",")","m",".","field","(","'is_received'",",","'boolean'",")","m",".","field","(","'message_id'",",","'keyword'",")","m",".","field","(","'parent_id'",",","'keyword'",")","# participants","participants","=","Nested","(","doc_class","=","IndexedParticipant",",","include_in_all","=","True",")","participants",".","field","(","\"address\"",",","\"text\"",",","analyzer","=","\"text_analyzer\"",",","fields","=","{","\"raw\"",":","{","\"type\"",":","\"keyword\"","}",",","\"parts\"",":","{","\"type\"",":","\"text\"",",","\"analyzer\"",":","\"email_analyzer\"","}","}",")","participants",".","field","(","\"contact_ids\"",",","Keyword","(","multi","=","True",")",")","participants",".","field","(","\"label\"",",","\"text\"",",","analyzer","=","\"text_analyzer\"",")","participants",".","field","(","\"protocol\"",",","Keyword","(",")",")","participants",".","field","(","\"type\"",",","Keyword","(",")",")","m",".","field","(","'participants'",",","participants",")","# PI","pi","=","Object","(","doc_class","=","PIIndexModel",",","include_in_all","=","True",",","properties","=","{","\"technic\"",":","\"integer\"",",","\"comportment\"",":","\"integer\"",",","\"context\"",":","\"integer\"",",","\"version\"",":","\"integer\"",",","\"date_update\"",":","\"date\"","}",")","m",".","field","(","\"pi\"",",","pi",")","m",".","field","(","'privacy_features'",",","Object","(","include_in_all","=","True",")",")","m",".","field","(","'raw_msg_id'",",","\"keyword\"",")","m",".","field","(","'subject'",",","'text'",",","fields","=","{","\"normalized\"",":","{","\"type\"",":","\"text\"",",","\"analyzer\"",":","\"text_analyzer\"","}","}",")","m",".","field","(","'tags'",",","Keyword","(","multi","=","True",")",")","m",".","field","(","'subject'",",","'text'",")","m",".","field","(","'tags'",",","Keyword","(","multi","=","True",")",")","m",".","field","(","'protocol'",",","'keyword'",")","m",".","field","(","'user_identities'",",","Keyword","(","multi","=","True",")",")","return","m"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/main\/py.main\/caliopen_main\/message\/store\/message_index.py#L53-L135"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.ML\/caliopen_climl\/cli.py","language":"python","identifier":"cli","parameters":"(ctx, config)","argument_list":"","return_statement":"","docstring":"Entry point.","docstring_summary":"Entry point.","docstring_tokens":["Entry","point","."],"function":"def cli(ctx, config):\n \"\"\"Entry point.\"\"\"\n ctx.obj = Config(config).conf","function_tokens":["def","cli","(","ctx",",","config",")",":","ctx",".","obj","=","Config","(","config",")",".","conf"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.ML\/caliopen_climl\/cli.py#L21-L23"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.ML\/caliopen_climl\/cli.py","language":"python","identifier":"train","parameters":"(config, model, index, output)","argument_list":"","return_statement":"","docstring":"Train a model command.","docstring_summary":"Train a model command.","docstring_tokens":["Train","a","model","command","."],"function":"def train(config, model, index, output):\n \"\"\"Train a model command.\"\"\"\n click.echo('Will train model {0} with index {1}'.\n format(model, index))\n if model == 'tagger':\n provider = ESDataManager(config)\n provider.prepare(provider.get_query(),\n index=None,\n doc_type='indexed_message')\n manager = ModelManager(provider)\n result_file = manager.get_new_model(output)\n save_file(config, result_file, model)\n else:\n click.echo('Unknow model {0}'.format(model))","function_tokens":["def","train","(","config",",","model",",","index",",","output",")",":","click",".","echo","(","'Will train model {0} with index {1}'",".","format","(","model",",","index",")",")","if","model","==","'tagger'",":","provider","=","ESDataManager","(","config",")","provider",".","prepare","(","provider",".","get_query","(",")",",","index","=","None",",","doc_type","=","'indexed_message'",")","manager","=","ModelManager","(","provider",")","result_file","=","manager",".","get_new_model","(","output",")","save_file","(","config",",","result_file",",","model",")","else",":","click",".","echo","(","'Unknow model {0}'",".","format","(","model",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.ML\/caliopen_climl\/cli.py#L31-L44"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.doc\/caliopen_api_doc\/config.py","language":"python","identifier":"includeme","parameters":"(config)","argument_list":"","return_statement":"","docstring":"Configure API to serve static documentation files.","docstring_summary":"Configure API to serve static documentation files.","docstring_tokens":["Configure","API","to","serve","static","documentation","files","."],"function":"def includeme(config):\n \"\"\"Configure API to serve static documentation files.\"\"\"\n log.info('Loading api doc module')\n settings = config.registry.settings\n swagger_dir = settings.get('pyramid_swagger.schema_directory')\n if not swagger_dir:\n log.warn('No configured swagger schema directory found')\n else:\n log.info('Will load swagger.json from {}'.format(swagger_dir))\n config.add_static_view('doc\/api', swagger_dir,\n cache_max_age=3600)\n # the api swagger-ui is within folder \/devtools\/swagger-ui\n config.add_static_view('api-ui', 'caliopen_api_doc:swagger-ui\/',\n cache_max_age=3600)\n # the Single Source of Truth\n config.add_static_view('defs', 'caliopen_api_doc:..\/..\/defs\/',\n cache_max_age=3600)","function_tokens":["def","includeme","(","config",")",":","log",".","info","(","'Loading api doc module'",")","settings","=","config",".","registry",".","settings","swagger_dir","=","settings",".","get","(","'pyramid_swagger.schema_directory'",")","if","not","swagger_dir",":","log",".","warn","(","'No configured swagger schema directory found'",")","else",":","log",".","info","(","'Will load swagger.json from {}'",".","format","(","swagger_dir",")",")","config",".","add_static_view","(","'doc\/api'",",","swagger_dir",",","cache_max_age","=","3600",")","# the api swagger-ui is within folder \/devtools\/swagger-ui","config",".","add_static_view","(","'api-ui'",",","'caliopen_api_doc:swagger-ui\/'",",","cache_max_age","=","3600",")","# the Single Source of Truth","config",".","add_static_view","(","'defs'",",","'caliopen_api_doc:..\/..\/defs\/'",",","cache_max_age","=","3600",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.doc\/caliopen_api_doc\/config.py#L9-L25"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.migrate\/caliopen_migrate\/shards.py","language":"python","identifier":"delete_all_shards","parameters":"(dry_run=True)","argument_list":"","return_statement":"","docstring":"Delete all index shards.","docstring_summary":"Delete all index shards.","docstring_tokens":["Delete","all","index","shards","."],"function":"def delete_all_shards(dry_run=True):\n \"\"\"Delete all index shards.\"\"\"\n client = get_index_connection()\n shards = Configuration('global').get('elasticsearch.shards')\n\n for shard in shards:\n log.info('Processing shard {}'.format(shard))\n if not shard.startswith('caliopen-'):\n log.warn('Invalid shard name, pass')\n continue\n if not client.indices.exists(shard):\n log.warn('Shard does not exist')\n continue\n if dry_run:\n log.info('Delete shard but dry run do not touch')\n else:\n client.indices.delete(shard)\n log.info('Index {} deleted'.format(shard))","function_tokens":["def","delete_all_shards","(","dry_run","=","True",")",":","client","=","get_index_connection","(",")","shards","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.shards'",")","for","shard","in","shards",":","log",".","info","(","'Processing shard {}'",".","format","(","shard",")",")","if","not","shard",".","startswith","(","'caliopen-'",")",":","log",".","warn","(","'Invalid shard name, pass'",")","continue","if","not","client",".","indices",".","exists","(","shard",")",":","log",".","warn","(","'Shard does not exist'",")","continue","if","dry_run",":","log",".","info","(","'Delete shard but dry run do not touch'",")","else",":","client",".","indices",".","delete","(","shard",")","log",".","info","(","'Index {} deleted'",".","format","(","shard",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.migrate\/caliopen_migrate\/shards.py#L11-L28"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.migrate\/caliopen_migrate\/shards.py","language":"python","identifier":"create_all_shards","parameters":"(dry_run=True)","argument_list":"","return_statement":"","docstring":"Create all needed index shards.","docstring_summary":"Create all needed index shards.","docstring_tokens":["Create","all","needed","index","shards","."],"function":"def create_all_shards(dry_run=True):\n \"\"\"Create all needed index shards.\"\"\"\n client = get_index_connection()\n shards = Configuration('global').get('elasticsearch.shards')\n\n for shard_id in shards:\n if not client.indices.exists(shard_id):\n log.info('Creating shard {}'.format(shard_id))\n if not dry_run:\n setup_shard_index(shard_id)","function_tokens":["def","create_all_shards","(","dry_run","=","True",")",":","client","=","get_index_connection","(",")","shards","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.shards'",")","for","shard_id","in","shards",":","if","not","client",".","indices",".","exists","(","shard_id",")",":","log",".","info","(","'Creating shard {}'",".","format","(","shard_id",")",")","if","not","dry_run",":","setup_shard_index","(","shard_id",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.migrate\/caliopen_migrate\/shards.py#L31-L40"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.migrate\/caliopen_migrate\/shards.py","language":"python","identifier":"recreate_user_alias","parameters":"(client, user, dry_run=True)","argument_list":"","return_statement":"return True","docstring":"Create an index alias mapping user_id -> shard_id.","docstring_summary":"Create an index alias mapping user_id -> shard_id.","docstring_tokens":["Create","an","index","alias","mapping","user_id","-",">","shard_id","."],"function":"def recreate_user_alias(client, user, dry_run=True):\n \"\"\"Create an index alias mapping user_id -> shard_id.\"\"\"\n if not user.shard_id:\n log.error('No shard for user {}'.format(user.user_id))\n return False\n shards = Configuration('global').get('elasticsearch.shards')\n alias_exists = False\n if client.indices.exists_alias(name=user.user_id):\n alias = client.indices.get_alias(name=user.user_id)\n for index, alias_infos in alias.items():\n if index not in shards:\n if not dry_run:\n client.indices.delete_alias(index=index, name=user.user_id)\n else:\n log.info('Alias exist {} with index {}, should delete'.\n format(user.user_id, index))\n else:\n log.info('Alias on shard exist, skipping')\n alias_exists = True\n if alias_exists:\n return True\n if not dry_run:\n body = {'filter': {'term': {'user_id': user.user_id}}}\n try:\n client.indices.put_alias(index=user.shard_id,\n name=user.user_id,\n body=body)\n except Exception as exc:\n log.exception('Error during alias creation for user {} : {}'.\n format(user.user_id, exc))\n return False\n else:\n log.info('Should create alias {}'.format(user.user_id))\n return True","function_tokens":["def","recreate_user_alias","(","client",",","user",",","dry_run","=","True",")",":","if","not","user",".","shard_id",":","log",".","error","(","'No shard for user {}'",".","format","(","user",".","user_id",")",")","return","False","shards","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.shards'",")","alias_exists","=","False","if","client",".","indices",".","exists_alias","(","name","=","user",".","user_id",")",":","alias","=","client",".","indices",".","get_alias","(","name","=","user",".","user_id",")","for","index",",","alias_infos","in","alias",".","items","(",")",":","if","index","not","in","shards",":","if","not","dry_run",":","client",".","indices",".","delete_alias","(","index","=","index",",","name","=","user",".","user_id",")","else",":","log",".","info","(","'Alias exist {} with index {}, should delete'",".","format","(","user",".","user_id",",","index",")",")","else",":","log",".","info","(","'Alias on shard exist, skipping'",")","alias_exists","=","True","if","alias_exists",":","return","True","if","not","dry_run",":","body","=","{","'filter'",":","{","'term'",":","{","'user_id'",":","user",".","user_id","}","}","}","try",":","client",".","indices",".","put_alias","(","index","=","user",".","shard_id",",","name","=","user",".","user_id",",","body","=","body",")","except","Exception","as","exc",":","log",".","exception","(","'Error during alias creation for user {} : {}'",".","format","(","user",".","user_id",",","exc",")",")","return","False","else",":","log",".","info","(","'Should create alias {}'",".","format","(","user",".","user_id",")",")","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.migrate\/caliopen_migrate\/shards.py#L43-L76"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.migrate\/caliopen_migrate\/shards.py","language":"python","identifier":"recreate_all_user_aliases","parameters":"(dry_run=True)","argument_list":"","return_statement":"","docstring":"Recreate alias for all users.","docstring_summary":"Recreate alias for all users.","docstring_tokens":["Recreate","alias","for","all","users","."],"function":"def recreate_all_user_aliases(dry_run=True):\n \"\"\"Recreate alias for all users.\"\"\"\n client = get_index_connection()\n for user in User._model_class.all():\n recreate_user_alias(client, user, dry_run)","function_tokens":["def","recreate_all_user_aliases","(","dry_run","=","True",")",":","client","=","get_index_connection","(",")","for","user","in","User",".","_model_class",".","all","(",")",":","recreate_user_alias","(","client",",","user",",","dry_run",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.migrate\/caliopen_migrate\/shards.py#L79-L83"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/reserved_names.py","language":"python","identifier":"import_reserved_names","parameters":"(input_file, ** kwargs)","argument_list":"","return_statement":"","docstring":"Import emails for an user.","docstring_summary":"Import emails for an user.","docstring_tokens":["Import","emails","for","an","user","."],"function":"def import_reserved_names(input_file, ** kwargs):\n \"\"\"Import emails for an user.\"\"\"\n from caliopen_main.user.core import ReservedName\n\n cpt = 0\n with open(input_file) as f:\n for name in f.read().decode('utf8').split('\\n'):\n if not name.startswith('#'):\n ReservedName.create(name=name)\n cpt += 1\n log.info('Created {} reserved names'.format(cpt))","function_tokens":["def","import_reserved_names","(","input_file",",","*","*","kwargs",")",":","from","caliopen_main",".","user",".","core","import","ReservedName","cpt","=","0","with","open","(","input_file",")","as","f",":","for","name","in","f",".","read","(",")",".","decode","(","'utf8'",")",".","split","(","'\\n'",")",":","if","not","name",".","startswith","(","'#'",")",":","ReservedName",".","create","(","name","=","name",")","cpt","+=","1","log",".","info","(","'Created {} reserved names'",".","format","(","cpt",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/reserved_names.py#L10-L20"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/compute.py","language":"python","identifier":"basic_compute","parameters":"(username, job, ** kwargs)","argument_list":"","return_statement":"","docstring":"Import emails for an user.","docstring_summary":"Import emails for an user.","docstring_tokens":["Import","emails","for","an","user","."],"function":"def basic_compute(username, job, ** kwargs):\n \"\"\"Import emails for an user.\"\"\"\n from caliopen_main.user.core import User\n from caliopen_main.contact.objects import Contact\n from caliopen_pi.qualifiers import ContactMessageQualifier\n\n user = User.by_name(username)\n qualifier = ContactMessageQualifier(user)\n contacts = Contact.list_db(user.user_id)\n\n if job == 'contact_privacy':\n for contact in contacts:\n log.info('Processing contact {0}'.format(contact.contact_id))\n qualifier.process(contact)","function_tokens":["def","basic_compute","(","username",",","job",",","*","*","kwargs",")",":","from","caliopen_main",".","user",".","core","import","User","from","caliopen_main",".","contact",".","objects","import","Contact","from","caliopen_pi",".","qualifiers","import","ContactMessageQualifier","user","=","User",".","by_name","(","username",")","qualifier","=","ContactMessageQualifier","(","user",")","contacts","=","Contact",".","list_db","(","user",".","user_id",")","if","job","==","'contact_privacy'",":","for","contact","in","contacts",":","log",".","info","(","'Processing contact {0}'",".","format","(","contact",".","contact_id",")",")","qualifier",".","process","(","contact",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/compute.py#L10-L23"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/resync_index.py","language":"python","identifier":"clean_index_user","parameters":"(client, user)","argument_list":"","return_statement":"return r1['deleted'], r2['deleted']","docstring":"Delete old data belong to an user from index.","docstring_summary":"Delete old data belong to an user from index.","docstring_tokens":["Delete","old","data","belong","to","an","user","from","index","."],"function":"def clean_index_user(client, user):\n \"\"\"Delete old data belong to an user from index.\"\"\"\n query = {'query': {'term': {'user_id': user.user_id}}}\n r1 = client.delete_by_query(index=user.shard_id,\n doc_type='indexed_message',\n body=query)\n r2 = client.delete_by_query(index=user.shard_id,\n doc_type='indexed_contact',\n body=query)\n return r1['deleted'], r2['deleted']","function_tokens":["def","clean_index_user","(","client",",","user",")",":","query","=","{","'query'",":","{","'term'",":","{","'user_id'",":","user",".","user_id","}","}","}","r1","=","client",".","delete_by_query","(","index","=","user",".","shard_id",",","doc_type","=","'indexed_message'",",","body","=","query",")","r2","=","client",".","delete_by_query","(","index","=","user",".","shard_id",",","doc_type","=","'indexed_contact'",",","body","=","query",")","return","r1","[","'deleted'","]",",","r2","[","'deleted'","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/resync_index.py#L18-L27"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/resync_index.py","language":"python","identifier":"resync_index","parameters":"(**kwargs)","argument_list":"","return_statement":"","docstring":"Resync an index for an user.","docstring_summary":"Resync an index for an user.","docstring_tokens":["Resync","an","index","for","an","user","."],"function":"def resync_index(**kwargs):\n \"\"\"Resync an index for an user.\"\"\"\n from caliopen_main.user.core import User, allocate_user_shard\n from caliopen_main.user.core.setups import setup_index\n from caliopen_main.contact.store import Contact\n from caliopen_main.contact.objects import Contact as ContactObject\n from caliopen_main.message.store import Message\n from caliopen_main.message.objects import Message as MessageObject\n\n if 'user_name' in kwargs and kwargs['user_name']:\n user = User.by_name(kwargs['user_name'])\n elif 'user_id' in kwargs and kwargs['user_id']:\n user = User.get(kwargs['user_id'])\n else:\n print('Need user_name or user_id parameter')\n sys.exit(1)\n\n es_url = Configuration('global').get('elasticsearch.url')\n es_client = Elasticsearch(es_url)\n\n if 'delete' in kwargs and kwargs['delete']:\n del_msg, del_con = clean_index_user(es_client, user)\n log.info('Delete of {0} old contacts and {1} old messages'.\n format(del_con, del_msg))\n\n user_id = uuid.UUID(user.user_id)\n shard_id = allocate_user_shard(user_id)\n if user.shard_id != shard_id:\n log.warn('Reallocate user index shard from {} to {}'.\n format(user.shard_id, shard_id))\n # XXX fixme. attribute should be set without using model\n user.model.shard_id = shard_id\n user.save()\n\n setup_index(user)\n\n cpt_contact = 0\n contacts = Contact.filter(user_id=user.user_id)\n for contact in contacts:\n log.debug('Reindex contact %r' % contact.contact_id)\n obj = ContactObject(user, contact_id=contact.contact_id)\n obj.get_db()\n obj.unmarshall_db()\n obj.create_index()\n cpt_contact += 1\n\n cpt_message = 0\n messages = Message.filter(user_id=user.user_id).timeout(None). \\\n allow_filtering()\n for message in messages:\n log.debug('Reindex message %r' % message.message_id)\n obj = MessageObject(user, message_id=message.message_id)\n obj.get_db()\n obj.unmarshall_db()\n obj.create_index()\n cpt_message += 1\n log.info('Sync of {0} contacts, {1} messages'.\n format(cpt_contact, cpt_message))\n log.info('Create index alias %r' % user.user_id)\n try:\n es_client.indices.put_alias(index=shard_id, name=user.user_id)\n except Exception as exc:\n log.exception('Error during alias creation : {}'.format(exc))\n raise exc","function_tokens":["def","resync_index","(","*","*","kwargs",")",":","from","caliopen_main",".","user",".","core","import","User",",","allocate_user_shard","from","caliopen_main",".","user",".","core",".","setups","import","setup_index","from","caliopen_main",".","contact",".","store","import","Contact","from","caliopen_main",".","contact",".","objects","import","Contact","as","ContactObject","from","caliopen_main",".","message",".","store","import","Message","from","caliopen_main",".","message",".","objects","import","Message","as","MessageObject","if","'user_name'","in","kwargs","and","kwargs","[","'user_name'","]",":","user","=","User",".","by_name","(","kwargs","[","'user_name'","]",")","elif","'user_id'","in","kwargs","and","kwargs","[","'user_id'","]",":","user","=","User",".","get","(","kwargs","[","'user_id'","]",")","else",":","print","(","'Need user_name or user_id parameter'",")","sys",".","exit","(","1",")","es_url","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.url'",")","es_client","=","Elasticsearch","(","es_url",")","if","'delete'","in","kwargs","and","kwargs","[","'delete'","]",":","del_msg",",","del_con","=","clean_index_user","(","es_client",",","user",")","log",".","info","(","'Delete of {0} old contacts and {1} old messages'",".","format","(","del_con",",","del_msg",")",")","user_id","=","uuid",".","UUID","(","user",".","user_id",")","shard_id","=","allocate_user_shard","(","user_id",")","if","user",".","shard_id","!=","shard_id",":","log",".","warn","(","'Reallocate user index shard from {} to {}'",".","format","(","user",".","shard_id",",","shard_id",")",")","# XXX fixme. attribute should be set without using model","user",".","model",".","shard_id","=","shard_id","user",".","save","(",")","setup_index","(","user",")","cpt_contact","=","0","contacts","=","Contact",".","filter","(","user_id","=","user",".","user_id",")","for","contact","in","contacts",":","log",".","debug","(","'Reindex contact %r'","%","contact",".","contact_id",")","obj","=","ContactObject","(","user",",","contact_id","=","contact",".","contact_id",")","obj",".","get_db","(",")","obj",".","unmarshall_db","(",")","obj",".","create_index","(",")","cpt_contact","+=","1","cpt_message","=","0","messages","=","Message",".","filter","(","user_id","=","user",".","user_id",")",".","timeout","(","None",")",".","allow_filtering","(",")","for","message","in","messages",":","log",".","debug","(","'Reindex message %r'","%","message",".","message_id",")","obj","=","MessageObject","(","user",",","message_id","=","message",".","message_id",")","obj",".","get_db","(",")","obj",".","unmarshall_db","(",")","obj",".","create_index","(",")","cpt_message","+=","1","log",".","info","(","'Sync of {0} contacts, {1} messages'",".","format","(","cpt_contact",",","cpt_message",")",")","log",".","info","(","'Create index alias %r'","%","user",".","user_id",")","try",":","es_client",".","indices",".","put_alias","(","index","=","shard_id",",","name","=","user",".","user_id",")","except","Exception","as","exc",":","log",".","exception","(","'Error during alias creation : {}'",".","format","(","exc",")",")","raise","exc"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/resync_index.py#L30-L93"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/setup_storage.py","language":"python","identifier":"setup_storage","parameters":"(settings=None)","argument_list":"","return_statement":"","docstring":"Create cassandra models.","docstring_summary":"Create cassandra models.","docstring_tokens":["Create","cassandra","models","."],"function":"def setup_storage(settings=None):\n \"\"\"Create cassandra models.\"\"\"\n from caliopen_storage.core import core_registry\n # Make discovery happen\n from caliopen_main.user.core import User\n from caliopen_main.user.core import (UserIdentity,\n IdentityLookup,\n IdentityTypeLookup)\n from caliopen_main.contact.objects.contact import Contact\n from caliopen_main.message.objects.message import Message\n from caliopen_main.common.objects.tag import ResourceTag\n from caliopen_main.device.core import Device\n from caliopen_main.notification.core import Notification, NotificationTtl\n from caliopen_main.protocol.core import Provider\n\n from cassandra.cqlengine.management import sync_table, \\\n create_keyspace_simple\n keyspace = Configuration('global').get('cassandra.keyspace')\n if not keyspace:\n raise Exception('Configuration missing for cassandra keyspace')\n # XXX tofix : define strategy and replication_factor in configuration\n create_keyspace_simple(keyspace, 1)\n for name, kls in core_registry.items():\n log.info('Creating cassandra model %s' % name)\n if hasattr(kls._model_class, 'pk'):\n # XXX find a better way to detect model from udt\n sync_table(kls._model_class)","function_tokens":["def","setup_storage","(","settings","=","None",")",":","from","caliopen_storage",".","core","import","core_registry","# Make discovery happen","from","caliopen_main",".","user",".","core","import","User","from","caliopen_main",".","user",".","core","import","(","UserIdentity",",","IdentityLookup",",","IdentityTypeLookup",")","from","caliopen_main",".","contact",".","objects",".","contact","import","Contact","from","caliopen_main",".","message",".","objects",".","message","import","Message","from","caliopen_main",".","common",".","objects",".","tag","import","ResourceTag","from","caliopen_main",".","device",".","core","import","Device","from","caliopen_main",".","notification",".","core","import","Notification",",","NotificationTtl","from","caliopen_main",".","protocol",".","core","import","Provider","from","cassandra",".","cqlengine",".","management","import","sync_table",",","create_keyspace_simple","keyspace","=","Configuration","(","'global'",")",".","get","(","'cassandra.keyspace'",")","if","not","keyspace",":","raise","Exception","(","'Configuration missing for cassandra keyspace'",")","# XXX tofix : define strategy and replication_factor in configuration","create_keyspace_simple","(","keyspace",",","1",")","for","name",",","kls","in","core_registry",".","items","(",")",":","log",".","info","(","'Creating cassandra model %s'","%","name",")","if","hasattr","(","kls",".","_model_class",",","'pk'",")",":","# XXX find a better way to detect model from udt","sync_table","(","kls",".","_model_class",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/setup_storage.py#L9-L35"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/import_email.py","language":"python","identifier":"import_email","parameters":"(email, import_path, format, contact_probability,\n **kwargs)","argument_list":"","return_statement":"","docstring":"Import emails for an user.","docstring_summary":"Import emails for an user.","docstring_tokens":["Import","emails","for","an","user","."],"function":"def import_email(email, import_path, format, contact_probability,\n **kwargs):\n \"\"\"Import emails for an user.\"\"\"\n from caliopen_main.user.core import User\n from caliopen_main.contact.core import Contact, ContactLookup\n from caliopen_main.message.parsers.mail import MailMessage\n from caliopen_main.contact.parameters import NewContact, NewEmail\n from caliopen_nats.delivery import UserMailDelivery\n from caliopen_main.message.core import RawMessage\n from caliopen_storage.config import Configuration\n\n max_size = int(Configuration(\"global\").get(\"object_store.db_size_limit\"))\n\n if 'to' in kwargs and kwargs['to']:\n dest_email = kwargs['to']\n else:\n dest_email = email\n\n if format == 'maildir':\n if dest_email != email:\n raise Exception('Cannot change To email using maildir format')\n emails = Maildir(import_path, factory=message_from_file)\n mode = 'maildir'\n else:\n if os.path.isdir(import_path):\n mode = 'mbox_directory'\n emails = {}\n files = [f for f in os.listdir(import_path) if\n os.path.isfile(os.path.join(import_path, f))]\n for f in files:\n try:\n log.debug('Importing mail from file {}'.format(f))\n with open('%s\/%s' % (import_path, f)) as fh:\n data = fh.read()\n data = re.sub('^To: (.*)', 'To: %s' % dest_email,\n data, flags=re.MULTILINE)\n emails[f] = message_from_string(data)\n except Exception as exc:\n log.error('Error importing email {}'.format(exc))\n else:\n mode = 'mbox'\n emails = mbox(import_path)\n\n user = User.by_local_identifier(dest_email, 'email')\n\n log.info(\"Processing mode %s\" % mode)\n\n for key, data in emails.iteritems():\n # Prevent creating message too large to fit in db.\n # (should use inject cmd for large messages)\n size = len(data.as_string())\n if size > max_size:\n log.warn(\"Message too large to fit into db. \\\n Please, use 'inject' cmd for importing large emails.\")\n continue\n\n raw = RawMessage.create(data.as_string())\n log.debug('Created raw message {}'.format(raw.raw_msg_id))\n message = MailMessage(data.as_string())\n dice = random()\n if dice <= contact_probability:\n for participant in message.participants:\n try:\n ContactLookup.get(user, participant.address)\n except NotFound:\n log.info('Creating contact %s' % participant.address)\n name, domain = participant.address.split('@')\n contact_param = NewContact()\n contact_param.family_name = name\n if participant.address:\n e_mail = NewEmail()\n e_mail.address = participant.address\n contact_param.emails = [e_mail]\n Contact.create(user, contact_param)\n else:\n log.info('No contact associated to raw {} '.format(raw.raw_msg_id))\n\n processor = UserMailDelivery(user,\n user.local_identities[\n 0]) # assume one local identity\n try:\n obj_message = processor.process_raw(raw.raw_msg_id)\n except Exception as exc:\n if isinstance(exc, DuplicateMessage):\n log.info('duplicate message {}, not imported'.format(\n raw.raw_msg_id))\n else:\n log.exception(exc)\n else:\n log.info('Created message {}'.format(obj_message.message_id))","function_tokens":["def","import_email","(","email",",","import_path",",","format",",","contact_probability",",","*","*","kwargs",")",":","from","caliopen_main",".","user",".","core","import","User","from","caliopen_main",".","contact",".","core","import","Contact",",","ContactLookup","from","caliopen_main",".","message",".","parsers",".","mail","import","MailMessage","from","caliopen_main",".","contact",".","parameters","import","NewContact",",","NewEmail","from","caliopen_nats",".","delivery","import","UserMailDelivery","from","caliopen_main",".","message",".","core","import","RawMessage","from","caliopen_storage",".","config","import","Configuration","max_size","=","int","(","Configuration","(","\"global\"",")",".","get","(","\"object_store.db_size_limit\"",")",")","if","'to'","in","kwargs","and","kwargs","[","'to'","]",":","dest_email","=","kwargs","[","'to'","]","else",":","dest_email","=","email","if","format","==","'maildir'",":","if","dest_email","!=","email",":","raise","Exception","(","'Cannot change To email using maildir format'",")","emails","=","Maildir","(","import_path",",","factory","=","message_from_file",")","mode","=","'maildir'","else",":","if","os",".","path",".","isdir","(","import_path",")",":","mode","=","'mbox_directory'","emails","=","{","}","files","=","[","f","for","f","in","os",".","listdir","(","import_path",")","if","os",".","path",".","isfile","(","os",".","path",".","join","(","import_path",",","f",")",")","]","for","f","in","files",":","try",":","log",".","debug","(","'Importing mail from file {}'",".","format","(","f",")",")","with","open","(","'%s\/%s'","%","(","import_path",",","f",")",")","as","fh",":","data","=","fh",".","read","(",")","data","=","re",".","sub","(","'^To: (.*)'",",","'To: %s'","%","dest_email",",","data",",","flags","=","re",".","MULTILINE",")","emails","[","f","]","=","message_from_string","(","data",")","except","Exception","as","exc",":","log",".","error","(","'Error importing email {}'",".","format","(","exc",")",")","else",":","mode","=","'mbox'","emails","=","mbox","(","import_path",")","user","=","User",".","by_local_identifier","(","dest_email",",","'email'",")","log",".","info","(","\"Processing mode %s\"","%","mode",")","for","key",",","data","in","emails",".","iteritems","(",")",":","# Prevent creating message too large to fit in db.","# (should use inject cmd for large messages)","size","=","len","(","data",".","as_string","(",")",")","if","size",">","max_size",":","log",".","warn","(","\"Message too large to fit into db. \\\n Please, use 'inject' cmd for importing large emails.\"",")","continue","raw","=","RawMessage",".","create","(","data",".","as_string","(",")",")","log",".","debug","(","'Created raw message {}'",".","format","(","raw",".","raw_msg_id",")",")","message","=","MailMessage","(","data",".","as_string","(",")",")","dice","=","random","(",")","if","dice","<=","contact_probability",":","for","participant","in","message",".","participants",":","try",":","ContactLookup",".","get","(","user",",","participant",".","address",")","except","NotFound",":","log",".","info","(","'Creating contact %s'","%","participant",".","address",")","name",",","domain","=","participant",".","address",".","split","(","'@'",")","contact_param","=","NewContact","(",")","contact_param",".","family_name","=","name","if","participant",".","address",":","e_mail","=","NewEmail","(",")","e_mail",".","address","=","participant",".","address","contact_param",".","emails","=","[","e_mail","]","Contact",".","create","(","user",",","contact_param",")","else",":","log",".","info","(","'No contact associated to raw {} '",".","format","(","raw",".","raw_msg_id",")",")","processor","=","UserMailDelivery","(","user",",","user",".","local_identities","[","0","]",")","# assume one local identity","try",":","obj_message","=","processor",".","process_raw","(","raw",".","raw_msg_id",")","except","Exception","as","exc",":","if","isinstance","(","exc",",","DuplicateMessage",")",":","log",".","info","(","'duplicate message {}, not imported'",".","format","(","raw",".","raw_msg_id",")",")","else",":","log",".","exception","(","exc",")","else",":","log",".","info","(","'Created message {}'",".","format","(","obj_message",".","message_id",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/import_email.py#L23-L112"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/setup.py","language":"python","identifier":"setup","parameters":"()","argument_list":"","return_statement":"","docstring":"Setup backend, storage and configuration.","docstring_summary":"Setup backend, storage and configuration.","docstring_tokens":["Setup","backend","storage","and","configuration","."],"function":"def setup():\n \"\"\"Setup backend, storage and configuration.\"\"\"\n log.info('Setup storage')\n setup_storage()\n log.info('Setup notification ttls')\n setup_notifications_ttls()","function_tokens":["def","setup","(",")",":","log",".","info","(","'Setup storage'",")","setup_storage","(",")","log",".","info","(","'Setup notification ttls'",")","setup_notifications_ttls","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/setup.py#L11-L16"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/create_user.py","language":"python","identifier":"create_user","parameters":"(**kwargs)","argument_list":"","return_statement":"","docstring":"Create user in Caliopen instance.","docstring_summary":"Create user in Caliopen instance.","docstring_tokens":["Create","user","in","Caliopen","instance","."],"function":"def create_user(**kwargs):\n \"\"\"Create user in Caliopen instance.\"\"\"\n from caliopen_main.user.core import User\n from caliopen_main.user.parameters import NewUser\n from caliopen_main.contact.parameters import NewContact\n from caliopen_main.contact.parameters import NewEmail\n\n # Fill core registry\n from caliopen_main.message.objects.message import Message\n\n param = NewUser()\n param.name = kwargs['email']\n if '@' in param.name:\n username, domain = param.name.split('@')\n param.name = username\n # Monkey patch configuration local_domain with provided value\n conf = Configuration('global').configuration\n conf['default_domain'] = domain\n param.password = kwargs['password']\n param.recovery_email = u'{}@recovery-caliopen.local'.format(param.name)\n\n contact = NewContact()\n contact.given_name = kwargs.get('given_name')\n contact.family_name = kwargs.get('family_name')\n email = NewEmail()\n email.address = param.recovery_email\n contact.emails = [email]\n param.contact = contact\n user = User.create(param)\n log.info('User %s (%s) created' % (user.user_id, user.name))","function_tokens":["def","create_user","(","*","*","kwargs",")",":","from","caliopen_main",".","user",".","core","import","User","from","caliopen_main",".","user",".","parameters","import","NewUser","from","caliopen_main",".","contact",".","parameters","import","NewContact","from","caliopen_main",".","contact",".","parameters","import","NewEmail","# Fill core registry","from","caliopen_main",".","message",".","objects",".","message","import","Message","param","=","NewUser","(",")","param",".","name","=","kwargs","[","'email'","]","if","'@'","in","param",".","name",":","username",",","domain","=","param",".","name",".","split","(","'@'",")","param",".","name","=","username","# Monkey patch configuration local_domain with provided value","conf","=","Configuration","(","'global'",")",".","configuration","conf","[","'default_domain'","]","=","domain","param",".","password","=","kwargs","[","'password'","]","param",".","recovery_email","=","u'{}@recovery-caliopen.local'",".","format","(","param",".","name",")","contact","=","NewContact","(",")","contact",".","given_name","=","kwargs",".","get","(","'given_name'",")","contact",".","family_name","=","kwargs",".","get","(","'family_name'",")","email","=","NewEmail","(",")","email",".","address","=","param",".","recovery_email","contact",".","emails","=","[","email","]","param",".","contact","=","contact","user","=","User",".","create","(","param",")","log",".","info","(","'User %s (%s) created'","%","(","user",".","user_id",",","user",".","name",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/create_user.py#L11-L40"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/dump_indexes_mappings.py","language":"python","identifier":"dump_index_mapping","parameters":"(kls, output_file)","argument_list":"","return_statement":"","docstring":"Output the json definition class.","docstring_summary":"Output the json definition class.","docstring_tokens":["Output","the","json","definition","class","."],"function":"def dump_index_mapping(kls, output_file):\n \"\"\"Output the json definition class.\"\"\"\n\n m = kls.build_mapping().to_dict()\n with open(output_file, 'w') as f:\n f.write(json.dumps(m, cls=JSONEncoder,\n indent=4, sort_keys=True))","function_tokens":["def","dump_index_mapping","(","kls",",","output_file",")",":","m","=","kls",".","build_mapping","(",")",".","to_dict","(",")","with","open","(","output_file",",","'w'",")","as","f",":","f",".","write","(","json",".","dumps","(","m",",","cls","=","JSONEncoder",",","indent","=","4",",","sort_keys","=","True",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/dump_indexes_mappings.py#L25-L31"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/inject_email.py","language":"python","identifier":"inject_email","parameters":"(recipient, email, **kwargs)","argument_list":"","return_statement":"","docstring":"Inject an email for an user.","docstring_summary":"Inject an email for an user.","docstring_tokens":["Inject","an","email","for","an","user","."],"function":"def inject_email(recipient, email, **kwargs):\n \"\"\"Inject an email for an user.\"\"\"\n\n with open(email) as f:\n conn = smtplib.SMTP('localhost', 2525)\n try:\n conn.sendmail(\"inject_email@py.cli.caliopen\", [recipient],\n str(f.read()))\n except Exception as exc:\n log.exception(exc)\n conn.quit()","function_tokens":["def","inject_email","(","recipient",",","email",",","*","*","kwargs",")",":","with","open","(","email",")","as","f",":","conn","=","smtplib",".","SMTP","(","'localhost'",",","2525",")","try",":","conn",".","sendmail","(","\"inject_email@py.cli.caliopen\"",",","[","recipient","]",",","str","(","f",".","read","(",")",")",")","except","Exception","as","exc",":","log",".","exception","(","exc",")","conn",".","quit","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/inject_email.py#L17-L27"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/resync_shard_index.py","language":"python","identifier":"resync_user","parameters":"(user)","argument_list":"","return_statement":"","docstring":"Resync data for an user into its index shard.","docstring_summary":"Resync data for an user into its index shard.","docstring_tokens":["Resync","data","for","an","user","into","its","index","shard","."],"function":"def resync_user(user):\n \"\"\"Resync data for an user into its index shard.\"\"\"\n from caliopen_main.contact.store import Contact\n from caliopen_main.contact.objects import Contact as ContactObject\n from caliopen_main.message.store import Message\n from caliopen_main.message.objects import Message as MessageObject\n\n log.info('Sync user {0} into shard {1}'.format(user.user_id,\n user.shard_id))\n\n client = Elasticsearch(Configuration('global').get('elasticsearch.url'))\n body = {'filter': {'term': {'user_id': user.user_id}}}\n # if not client.indices.exists_alias(user.user_id):\n # log.info('Creating alias {} for index {}'.format(user.user_id, user.shard_id))\n client.indices.put_alias(user.shard_id, user.user_id, body=body)\n\n contacts = Contact.filter(user_id=user.user_id).timeout(None)\n for contact in contacts:\n log.debug('Reindex contact %r' % contact.contact_id)\n obj = ContactObject(user, contact_id=contact.contact_id)\n obj.get_db()\n obj.unmarshall_db()\n obj.create_index()\n\n messages = Message.filter(user_id=user.user_id). \\\n allow_filtering().timeout(None)\n for message in messages:\n log.debug('Reindex message %r' % message.message_id)\n obj = MessageObject(user, message_id=message.message_id)\n obj.get_db()\n obj.unmarshall_db()\n obj.create_index()","function_tokens":["def","resync_user","(","user",")",":","from","caliopen_main",".","contact",".","store","import","Contact","from","caliopen_main",".","contact",".","objects","import","Contact","as","ContactObject","from","caliopen_main",".","message",".","store","import","Message","from","caliopen_main",".","message",".","objects","import","Message","as","MessageObject","log",".","info","(","'Sync user {0} into shard {1}'",".","format","(","user",".","user_id",",","user",".","shard_id",")",")","client","=","Elasticsearch","(","Configuration","(","'global'",")",".","get","(","'elasticsearch.url'",")",")","body","=","{","'filter'",":","{","'term'",":","{","'user_id'",":","user",".","user_id","}","}","}","# if not client.indices.exists_alias(user.user_id):","# log.info('Creating alias {} for index {}'.format(user.user_id, user.shard_id))","client",".","indices",".","put_alias","(","user",".","shard_id",",","user",".","user_id",",","body","=","body",")","contacts","=","Contact",".","filter","(","user_id","=","user",".","user_id",")",".","timeout","(","None",")","for","contact","in","contacts",":","log",".","debug","(","'Reindex contact %r'","%","contact",".","contact_id",")","obj","=","ContactObject","(","user",",","contact_id","=","contact",".","contact_id",")","obj",".","get_db","(",")","obj",".","unmarshall_db","(",")","obj",".","create_index","(",")","messages","=","Message",".","filter","(","user_id","=","user",".","user_id",")",".","allow_filtering","(",")",".","timeout","(","None",")","for","message","in","messages",":","log",".","debug","(","'Reindex message %r'","%","message",".","message_id",")","obj","=","MessageObject","(","user",",","message_id","=","message",".","message_id",")","obj",".","get_db","(",")","obj",".","unmarshall_db","(",")","obj",".","create_index","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/resync_shard_index.py#L19-L50"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/resync_shard_index.py","language":"python","identifier":"resync_shard_index","parameters":"(**kwargs)","argument_list":"","return_statement":"","docstring":"Resync all index of a shard.","docstring_summary":"Resync all index of a shard.","docstring_tokens":["Resync","all","index","of","a","shard","."],"function":"def resync_shard_index(**kwargs):\n \"\"\"Resync all index of a shard.\"\"\"\n from caliopen_main.user.core import User\n from caliopen_main.user.core.setups import setup_shard_index\n\n shard_id = kwargs['shard_id']\n old_shard_id = kwargs.get('old_shard_id')\n if not old_shard_id:\n old_shard_id = shard_id\n shards = Configuration('global').get('elasticsearch.shards')\n if shard_id not in shards:\n log.error('Invalid shard {0}'.format(shard_id))\n sys.exit(1)\n\n # Recreate index and mappings\n setup_shard_index(shard_id)\n\n users = User._model_class.all()\n cpt = 0\n for user in users:\n if user.shard_id not in (old_shard_id, shard_id):\n continue\n\n if user.shard_id != shard_id:\n user.shard_id = shard_id\n user.save()\n resync_user(user)\n cpt += 1\n log.info('Sync {0} users into shards'.format(cpt))","function_tokens":["def","resync_shard_index","(","*","*","kwargs",")",":","from","caliopen_main",".","user",".","core","import","User","from","caliopen_main",".","user",".","core",".","setups","import","setup_shard_index","shard_id","=","kwargs","[","'shard_id'","]","old_shard_id","=","kwargs",".","get","(","'old_shard_id'",")","if","not","old_shard_id",":","old_shard_id","=","shard_id","shards","=","Configuration","(","'global'",")",".","get","(","'elasticsearch.shards'",")","if","shard_id","not","in","shards",":","log",".","error","(","'Invalid shard {0}'",".","format","(","shard_id",")",")","sys",".","exit","(","1",")","# Recreate index and mappings","setup_shard_index","(","shard_id",")","users","=","User",".","_model_class",".","all","(",")","cpt","=","0","for","user","in","users",":","if","user",".","shard_id","not","in","(","old_shard_id",",","shard_id",")",":","continue","if","user",".","shard_id","!=","shard_id",":","user",".","shard_id","=","shard_id","user",".","save","(",")","resync_user","(","user",")","cpt","+=","1","log",".","info","(","'Sync {0} users into shards'",".","format","(","cpt",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/resync_shard_index.py#L53-L81"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/dump_model.py","language":"python","identifier":"dump_model_class","parameters":"(kls, output_file)","argument_list":"","return_statement":"","docstring":"Dump a model class into output file.","docstring_summary":"Dump a model class into output file.","docstring_tokens":["Dump","a","model","class","into","output","file","."],"function":"def dump_model_class(kls, output_file):\n \"\"\"Dump a model class into output file.\"\"\"\n records = kls._model_class.objects.all()\n data = []\n for rec in records:\n d = {}\n for k in rec._columns.keys():\n attr = getattr(rec, k)\n if hasattr(attr, 'to_python'):\n d[k] = attr.to_python()\n else:\n d[k] = attr\n data.append(d)\n with open(output_file, 'w') as f:\n f.write(json.dumps(data, cls=JSONEncoder,\n indent=4, sort_keys=True))","function_tokens":["def","dump_model_class","(","kls",",","output_file",")",":","records","=","kls",".","_model_class",".","objects",".","all","(",")","data","=","[","]","for","rec","in","records",":","d","=","{","}","for","k","in","rec",".","_columns",".","keys","(",")",":","attr","=","getattr","(","rec",",","k",")","if","hasattr","(","attr",",","'to_python'",")",":","d","[","k","]","=","attr",".","to_python","(",")","else",":","d","[","k","]","=","attr","data",".","append","(","d",")","with","open","(","output_file",",","'w'",")","as","f",":","f",".","write","(","json",".","dumps","(","data",",","cls","=","JSONEncoder",",","indent","=","4",",","sort_keys","=","True",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/dump_model.py#L23-L38"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/setup_notifications_ttls.py","language":"python","identifier":"setup_notifications_ttls","parameters":"()","argument_list":"","return_statement":"","docstring":"Fill up table `notification_ttl` with default ttls in seconds","docstring_summary":"Fill up table `notification_ttl` with default ttls in seconds","docstring_tokens":["Fill","up","table","notification_ttl","with","default","ttls","in","seconds"],"function":"def setup_notifications_ttls():\n \"\"\"Fill up table `notification_ttl` with default ttls in seconds\"\"\"\n\n from caliopen_main.notification.core import NotificationTtl\n\n default_ttls = {\n \"short-lived\": 60, # a minute\n \"mid-lived\": 3600, # an hour\n \"long-lived\": 43200, # 12 hours\n \"short-term\": 86400, # a day\n \"mid-term\": 172800, # 2 days\n \"long-term\": 1728000, # 10 days\n \"forever\": 0\n }\n\n for k, v in default_ttls.items():\n NotificationTtl.create(ttl_code=k, ttl_duration=v)\n\n log.info('{} default ttls have been set'.format(len(default_ttls)))","function_tokens":["def","setup_notifications_ttls","(",")",":","from","caliopen_main",".","notification",".","core","import","NotificationTtl","default_ttls","=","{","\"short-lived\"",":","60",",","# a minute","\"mid-lived\"",":","3600",",","# an hour","\"long-lived\"",":","43200",",","# 12 hours","\"short-term\"",":","86400",",","# a day","\"mid-term\"",":","172800",",","# 2 days","\"long-term\"",":","1728000",",","# 10 days","\"forever\"",":","0","}","for","k",",","v","in","default_ttls",".","items","(",")",":","NotificationTtl",".","create","(","ttl_code","=","k",",","ttl_duration","=","v",")","log",".","info","(","'{} default ttls have been set'",".","format","(","len","(","default_ttls",")",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/tools\/py.CLI\/caliopen_cli\/commands\/setup_notifications_ttls.py#L9-L27"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.tag\/caliopen_tag\/taggers\/tagger.py","language":"python","identifier":"MessageTagger.process","parameters":"(self, msg)","argument_list":"","return_statement":"return result","docstring":"Qualification for a message.\n\n It will first remove any \\n because predict processes one line only.\n Then it will tokenize the message with the same tokenizer as the one\n used for the training data.\n Afterwards, it will predict tag and return tag + prediction.\n Finally, it will remove the __label__ prefix to predicted tags.","docstring_summary":"Qualification for a message.","docstring_tokens":["Qualification","for","a","message","."],"function":"def process(self, msg):\n \"\"\"Qualification for a message.\n\n It will first remove any \\n because predict processes one line only.\n Then it will tokenize the message with the same tokenizer as the one\n used for the training data.\n Afterwards, it will predict tag and return tag + prediction.\n Finally, it will remove the __label__ prefix to predicted tags.\n \"\"\"\n text = pre_process(msg.body_plain, html=True)\n # TODO: Add language support + check if msg.body_plain is html ?\n\n predictions = self.model.predict(\n text,\n k=self.k,\n threshold=self.threshold\n )\n nb_result = len(predictions[0])\n result = [\n (predictions[0][i][9:], predictions[1][i])\n for i in range(nb_result)\n ]\n return result","function_tokens":["def","process","(","self",",","msg",")",":","text","=","pre_process","(","msg",".","body_plain",",","html","=","True",")","# TODO: Add language support + check if msg.body_plain is html ?","predictions","=","self",".","model",".","predict","(","text",",","k","=","self",".","k",",","threshold","=","self",".","threshold",")","nb_result","=","len","(","predictions","[","0","]",")","result","=","[","(","predictions","[","0","]","[","i","]","[","9",":","]",",","predictions","[","1","]","[","i","]",")","for","i","in","range","(","nb_result",")","]","return","result"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.tag\/caliopen_tag\/taggers\/tagger.py#L30-L52"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.tag\/caliopen_tag\/models_manager\/manager.py","language":"python","identifier":"ModelManager.__init__","parameters":"(\n self,\n provider,\n use_pre=True,\n epoch=15,\n lr=0.1,\n word_n_grams=2,\n min_count=400,\n dim=100,\n loss=\"softmax\",\n thread=12,\n neg=5)","argument_list":"","return_statement":"","docstring":"Initialize a model manager.\n\n It requires a provider to iterate on for creating the data.\n All hyperparameters for training the model are optional.","docstring_summary":"Initialize a model manager.","docstring_tokens":["Initialize","a","model","manager","."],"function":"def __init__(\n self,\n provider,\n use_pre=True,\n epoch=15,\n lr=0.1,\n word_n_grams=2,\n min_count=400,\n dim=100,\n loss=\"softmax\",\n thread=12,\n neg=5):\n \"\"\"Initialize a model manager.\n\n It requires a provider to iterate on for creating the data.\n All hyperparameters for training the model are optional.\n \"\"\"\n self.provider = provider\n self.use_pre = use_pre\n self.epoch = epoch\n self.lr = lr\n self.wordNgrams = word_n_grams\n self.minCount = min_count\n self.dim = dim\n self.loss = loss\n self.thread = thread\n self.neg = neg","function_tokens":["def","__init__","(","self",",","provider",",","use_pre","=","True",",","epoch","=","15",",","lr","=","0.1",",","word_n_grams","=","2",",","min_count","=","400",",","dim","=","100",",","loss","=","\"softmax\"",",","thread","=","12",",","neg","=","5",")",":","self",".","provider","=","provider","self",".","use_pre","=","use_pre","self",".","epoch","=","epoch","self",".","lr","=","lr","self",".","wordNgrams","=","word_n_grams","self",".","minCount","=","min_count","self",".","dim","=","dim","self",".","loss","=","loss","self",".","thread","=","thread","self",".","neg","=","neg"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.tag\/caliopen_tag\/models_manager\/manager.py#L20-L46"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.tag\/caliopen_tag\/models_manager\/manager.py","language":"python","identifier":"ModelManager.get_new_model","parameters":"(self, output)","argument_list":"","return_statement":"return result_file","docstring":"Get a new model and save it in resources\/models\/output.\n\n It first fetches the data from cassandra and write it to a temporary\n file, following the fastText format.\n Then it pre-processes the data (tokenization + lowercase).\n Then it trains a model using fastText and saves it at output location.\n Finally it removes the temporary file.","docstring_summary":"Get a new model and save it in resources\/models\/output.","docstring_tokens":["Get","a","new","model","and","save","it","in","resources","\/","models","\/","output","."],"function":"def get_new_model(self, output):\n \"\"\"Get a new model and save it in resources\/models\/output.\n\n It first fetches the data from cassandra and write it to a temporary\n file, following the fastText format.\n Then it pre-processes the data (tokenization + lowercase).\n Then it trains a model using fastText and saves it at output location.\n Finally it removes the temporary file.\n \"\"\"\n self._write_training_data_to_file()\n result_file = self._train_tagging_model(output)\n self._remove_tempfile()\n return result_file","function_tokens":["def","get_new_model","(","self",",","output",")",":","self",".","_write_training_data_to_file","(",")","result_file","=","self",".","_train_tagging_model","(","output",")","self",".","_remove_tempfile","(",")","return","result_file"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.tag\/caliopen_tag\/models_manager\/manager.py#L48-L60"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.tag\/caliopen_tag\/models_manager\/manager.py","language":"python","identifier":"ModelManager._train_tagging_model","parameters":"(self, output, quantization=False)","argument_list":"","return_statement":"return model_file","docstring":"Train a tagging model using an annotated file and save it to output.\n\n Pre-processing of the input file must have been done prior to training.\n Training file should be utf-8.\n The model can be quantized to reduce memory usage\n (but quantization is quite expensive).","docstring_summary":"Train a tagging model using an annotated file and save it to output.","docstring_tokens":["Train","a","tagging","model","using","an","annotated","file","and","save","it","to","output","."],"function":"def _train_tagging_model(self, output, quantization=False):\n \"\"\"Train a tagging model using an annotated file and save it to output.\n\n Pre-processing of the input file must have been done prior to training.\n Training file should be utf-8.\n The model can be quantized to reduce memory usage\n (but quantization is quite expensive).\n \"\"\"\n log.info('Start training model.')\n new_model = fastText.train_supervised(input=self.tempfilename,\n epoch=self.epoch,\n lr=self.lr,\n wordNgrams=self.wordNgrams,\n minCount=self.minCount,\n dim=self.dim,\n loss=self.loss,\n thread=self.thread,\n neg=self.neg)\n log.info('Training model done.')\n if quantization:\n log.info('Start quantization.')\n new_model.quantize(thread=self.thread, retrain=False)\n log.info('Quantization done.')\n model_file = '{}\/{}.bin'.format(resources_path, output)\n new_model.save_model(model_file)\n log.info('Model saved at {}.'.format(model_file))\n return model_file","function_tokens":["def","_train_tagging_model","(","self",",","output",",","quantization","=","False",")",":","log",".","info","(","'Start training model.'",")","new_model","=","fastText",".","train_supervised","(","input","=","self",".","tempfilename",",","epoch","=","self",".","epoch",",","lr","=","self",".","lr",",","wordNgrams","=","self",".","wordNgrams",",","minCount","=","self",".","minCount",",","dim","=","self",".","dim",",","loss","=","self",".","loss",",","thread","=","self",".","thread",",","neg","=","self",".","neg",")","log",".","info","(","'Training model done.'",")","if","quantization",":","log",".","info","(","'Start quantization.'",")","new_model",".","quantize","(","thread","=","self",".","thread",",","retrain","=","False",")","log",".","info","(","'Quantization done.'",")","model_file","=","'{}\/{}.bin'",".","format","(","resources_path",",","output",")","new_model",".","save_model","(","model_file",")","log",".","info","(","'Model saved at {}.'",".","format","(","model_file",")",")","return","model_file"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.tag\/caliopen_tag\/models_manager\/manager.py#L76-L102"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/hkp.py","language":"python","identifier":"HKPDiscovery.lookup_identity","parameters":"(self, identity, type_)","argument_list":"","return_statement":"return DiscoveryResult(result_keys)","docstring":"Find pgp keys by user email.","docstring_summary":"Find pgp keys by user email.","docstring_tokens":["Find","pgp","keys","by","user","email","."],"function":"def lookup_identity(self, identity, type_):\n \"\"\"Find pgp keys by user email.\"\"\"\n pub_keys = self._search_keys(identity)\n result_keys = []\n for key in pub_keys:\n asc_key = self._search_key(key)\n if not asc_key:\n log.warn('Key {} not found on HKP server'.format(key))\n else:\n txt_key = asc_key.encode('utf-8').rstrip()\n result_keys.extend(self._parse_key(txt_key))\n return DiscoveryResult(result_keys)","function_tokens":["def","lookup_identity","(","self",",","identity",",","type_",")",":","pub_keys","=","self",".","_search_keys","(","identity",")","result_keys","=","[","]","for","key","in","pub_keys",":","asc_key","=","self",".","_search_key","(","key",")","if","not","asc_key",":","log",".","warn","(","'Key {} not found on HKP server'",".","format","(","key",")",")","else",":","txt_key","=","asc_key",".","encode","(","'utf-8'",")",".","rstrip","(",")","result_keys",".","extend","(","self",".","_parse_key","(","txt_key",")",")","return","DiscoveryResult","(","result_keys",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/hkp.py#L64-L75"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/discoverer.py","language":"python","identifier":"PublicKeyDiscoverer.lookup_identity","parameters":"(self, identity, type_)","argument_list":"","return_statement":"return results","docstring":"Search for public key for an identifier and a protocol type.","docstring_summary":"Search for public key for an identifier and a protocol type.","docstring_tokens":["Search","for","public","key","for","an","identifier","and","a","protocol","type","."],"function":"def lookup_identity(self, identity, type_):\n \"\"\"Search for public key for an identifier and a protocol type.\"\"\"\n results = []\n for disco in self.discoverers:\n if type_ in self.discoverers[disco]._types:\n discoverer = self.discoverers[disco]\n try:\n result = discoverer.lookup_identity(identity, type_)\n if result.keys:\n results.append(result)\n except Exception as exc:\n log.error('Exception during key lookup using {0} '\n 'for identifier {1}: {2}'.format(disco,\n identity,\n exc))\n return results","function_tokens":["def","lookup_identity","(","self",",","identity",",","type_",")",":","results","=","[","]","for","disco","in","self",".","discoverers",":","if","type_","in","self",".","discoverers","[","disco","]",".","_types",":","discoverer","=","self",".","discoverers","[","disco","]","try",":","result","=","discoverer",".","lookup_identity","(","identity",",","type_",")","if","result",".","keys",":","results",".","append","(","result",")","except","Exception","as","exc",":","log",".","error","(","'Exception during key lookup using {0} '","'for identifier {1}: {2}'",".","format","(","disco",",","identity",",","exc",")",")","return","results"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/discoverer.py#L35-L50"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py","language":"python","identifier":"PGPPublicKey._get_userids","parameters":"(self, ids)","argument_list":"","return_statement":"return [PGPUserId(u.name, u.email, u.is_primary, u.comment, u.signers)\n for u in ids]","docstring":"Return list of ``PgpUserId``.","docstring_summary":"Return list of ``PgpUserId``.","docstring_tokens":["Return","list","of","PgpUserId","."],"function":"def _get_userids(self, ids):\n \"\"\"Return list of ``PgpUserId``.\"\"\"\n return [PGPUserId(u.name, u.email, u.is_primary, u.comment, u.signers)\n for u in ids]","function_tokens":["def","_get_userids","(","self",",","ids",")",":","return","[","PGPUserId","(","u",".","name",",","u",".","email",",","u",".","is_primary",",","u",".","comment",",","u",".","signers",")","for","u","in","ids","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py#L65-L68"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py","language":"python","identifier":"PGPPublicKey.armored_key","parameters":"(self)","argument_list":"","return_statement":"return str(self._pgpkey)","docstring":"Return the armored key.","docstring_summary":"Return the armored key.","docstring_tokens":["Return","the","armored","key","."],"function":"def armored_key(self):\n \"\"\"Return the armored key.\"\"\"\n return str(self._pgpkey)","function_tokens":["def","armored_key","(","self",")",":","return","str","(","self",".","_pgpkey",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py#L71-L73"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py","language":"python","identifier":"DiscoveryResult.emails","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Return distinct list of emails found in keys.","docstring_summary":"Return distinct list of emails found in keys.","docstring_tokens":["Return","distinct","list","of","emails","found","in","keys","."],"function":"def emails(self):\n \"\"\"Return distinct list of emails found in keys.\"\"\"\n found_emails = []\n for key in self.keys:\n for userid in key.userids:\n if userid.email not in found_emails and userid.is_uid:\n found_emails.append(userid.email)\n yield userid","function_tokens":["def","emails","(","self",")",":","found_emails","=","[","]","for","key","in","self",".","keys",":","for","userid","in","key",".","userids",":","if","userid",".","email","not","in","found_emails","and","userid",".","is_uid",":","found_emails",".","append","(","userid",".","email",")","yield","userid"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py#L84-L91"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py","language":"python","identifier":"BaseDiscovery.empty_result","parameters":"(self)","argument_list":"","return_statement":"return DiscoveryResult([])","docstring":"No result found.","docstring_summary":"No result found.","docstring_tokens":["No","result","found","."],"function":"def empty_result(self):\n \"\"\"No result found.\"\"\"\n return DiscoveryResult([])","function_tokens":["def","empty_result","(","self",")",":","return","DiscoveryResult","(","[","]",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py#L98-L100"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py","language":"python","identifier":"BaseDiscovery.lookup_identity","parameters":"(self, identity, type_)","argument_list":"","return_statement":"","docstring":"Method to be implemented by sub class for discovery.","docstring_summary":"Method to be implemented by sub class for discovery.","docstring_tokens":["Method","to","be","implemented","by","sub","class","for","discovery","."],"function":"def lookup_identity(self, identity, type_):\n \"\"\"Method to be implemented by sub class for discovery.\"\"\"\n raise NotImplementedError","function_tokens":["def","lookup_identity","(","self",",","identity",",","type_",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/base.py#L102-L104"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/rfc7929.py","language":"python","identifier":"compute_qname","parameters":"(username, domain)","argument_list":"","return_statement":"return '{}._openpgpkey.{}'.format(hash.hexdigest()[:56], domain.lower())","docstring":"Compute qname value from an email (part 3 of RFC).","docstring_summary":"Compute qname value from an email (part 3 of RFC).","docstring_tokens":["Compute","qname","value","from","an","email","(","part","3","of","RFC",")","."],"function":"def compute_qname(username, domain):\n \"\"\"Compute qname value from an email (part 3 of RFC).\"\"\"\n hash = hashlib.sha256()\n hash.update(username.lower())\n return '{}._openpgpkey.{}'.format(hash.hexdigest()[:56], domain.lower())","function_tokens":["def","compute_qname","(","username",",","domain",")",":","hash","=","hashlib",".","sha256","(",")","hash",".","update","(","username",".","lower","(",")",")","return","'{}._openpgpkey.{}'",".","format","(","hash",".","hexdigest","(",")","[",":","56","]",",","domain",".","lower","(",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/rfc7929.py#L23-L27"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/rfc7929.py","language":"python","identifier":"DNSDiscovery.lookup_identity","parameters":"(self, identity, type_)","argument_list":"","return_statement":"return DiscoveryResult(keys)","docstring":"Find for a given email an openpgp key in its DNS zone.","docstring_summary":"Find for a given email an openpgp key in its DNS zone.","docstring_tokens":["Find","for","a","given","email","an","openpgp","key","in","its","DNS","zone","."],"function":"def lookup_identity(self, identity, type_):\n \"\"\"Find for a given email an openpgp key in its DNS zone.\"\"\"\n clean = clean_email_address(identity)\n local_part, domain = clean[0].split('@', 2)\n qname = compute_qname(local_part, domain)\n ns = resolver.ns_for(domain)\n if not ns:\n log.warn('No nameservers found for domain {}'.format(domain))\n return self.empty_result\n\n # XXX use a random one\n use_ns = ns[0]\n resolv = resolver.Resolver(timeout=self.resolve_timeout)\n # XXX use of dnssec validation\n query = resolv.query_at(qname, 'OPENPGPKEY', use_ns)\n response = query.get()\n if not response:\n log.warn('No response for OPENPGPKEY dns query')\n return self.empty_result\n rrsets = response.rrset\n if not rrsets:\n log.warn('No rrsets for OPENPGPKEY dns query')\n return self.empty_result\n # XXX many rrset, key and signature, must be considered\n key = self._extract_key(rrsets[0])\n keys = self._parse_key(key)\n return DiscoveryResult(keys)","function_tokens":["def","lookup_identity","(","self",",","identity",",","type_",")",":","clean","=","clean_email_address","(","identity",")","local_part",",","domain","=","clean","[","0","]",".","split","(","'@'",",","2",")","qname","=","compute_qname","(","local_part",",","domain",")","ns","=","resolver",".","ns_for","(","domain",")","if","not","ns",":","log",".","warn","(","'No nameservers found for domain {}'",".","format","(","domain",")",")","return","self",".","empty_result","# XXX use a random one","use_ns","=","ns","[","0","]","resolv","=","resolver",".","Resolver","(","timeout","=","self",".","resolve_timeout",")","# XXX use of dnssec validation","query","=","resolv",".","query_at","(","qname",",","'OPENPGPKEY'",",","use_ns",")","response","=","query",".","get","(",")","if","not","response",":","log",".","warn","(","'No response for OPENPGPKEY dns query'",")","return","self",".","empty_result","rrsets","=","response",".","rrset","if","not","rrsets",":","log",".","warn","(","'No rrsets for OPENPGPKEY dns query'",")","return","self",".","empty_result","# XXX many rrset, key and signature, must be considered","key","=","self",".","_extract_key","(","rrsets","[","0","]",")","keys","=","self",".","_parse_key","(","key",")","return","DiscoveryResult","(","keys",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/rfc7929.py#L39-L65"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/rfc7929.py","language":"python","identifier":"DNSDiscovery._extract_key","parameters":"(self, record)","argument_list":"","return_statement":"return record.data","docstring":"Extract an armored representation of key from dns record.","docstring_summary":"Extract an armored representation of key from dns record.","docstring_tokens":["Extract","an","armored","representation","of","key","from","dns","record","."],"function":"def _extract_key(self, record):\n \"\"\"Extract an armored representation of key from dns record.\"\"\"\n return record.data","function_tokens":["def","_extract_key","(","self",",","record",")",":","return","record",".","data"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/rfc7929.py#L67-L69"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py","language":"python","identifier":"ContactDiscoveryResult.__init__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Instanciate a `ContactDiscoveryResult`.","docstring_summary":"Instanciate a `ContactDiscoveryResult`.","docstring_tokens":["Instanciate","a","ContactDiscoveryResult","."],"function":"def __init__(self):\n \"\"\"Instanciate a `ContactDiscoveryResult`.\"\"\"\n self.keys = []\n self.emails = []\n self.identities = []","function_tokens":["def","__init__","(","self",")",":","self",".","keys","=","[","]","self",".","emails","=","[","]","self",".","identities","=","[","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py#L16-L20"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py","language":"python","identifier":"ContactPublicKeyManager.__init__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Instanciate a `ContactPublicKeyManager`.","docstring_summary":"Instanciate a `ContactPublicKeyManager`.","docstring_tokens":["Instanciate","a","ContactPublicKeyManager","."],"function":"def __init__(self):\n \"\"\"Instanciate a `ContactPublicKeyManager`.\"\"\"\n conf = Configuration('global').configuration\n self.discoverer = PublicKeyDiscoverer(conf)","function_tokens":["def","__init__","(","self",")",":","conf","=","Configuration","(","'global'",")",".","configuration","self",".","discoverer","=","PublicKeyDiscoverer","(","conf",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py#L26-L29"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py","language":"python","identifier":"ContactPublicKeyManager._find_keys","parameters":"(self, user, contact, new_identifier, type_)","argument_list":"","return_statement":"","docstring":"Find keys related to a new identifier for a contact.","docstring_summary":"Find keys related to a new identifier for a contact.","docstring_tokens":["Find","keys","related","to","a","new","identifier","for","a","contact","."],"function":"def _find_keys(self, user, contact, new_identifier, type_):\n \"\"\"Find keys related to a new identifier for a contact.\"\"\"\n results = self.discoverer.lookup_identity(new_identifier, type_)\n current_keys = PublicKey.find(user, contact.contact_id)\n known_keys = [x.fingerprint for x in current_keys]\n if results:\n for result in results:\n for key in result.keys:\n if key.fingerprint not in known_keys:\n log.info('Found new key {0}'.format(key.fingerprint))\n yield result\n else:\n log.info('Known key {0}'.format(key.fingerprint))","function_tokens":["def","_find_keys","(","self",",","user",",","contact",",","new_identifier",",","type_",")",":","results","=","self",".","discoverer",".","lookup_identity","(","new_identifier",",","type_",")","current_keys","=","PublicKey",".","find","(","user",",","contact",".","contact_id",")","known_keys","=","[","x",".","fingerprint","for","x","in","current_keys","]","if","results",":","for","result","in","results",":","for","key","in","result",".","keys",":","if","key",".","fingerprint","not","in","known_keys",":","log",".","info","(","'Found new key {0}'",".","format","(","key",".","fingerprint",")",")","yield","result","else",":","log",".","info","(","'Known key {0}'",".","format","(","key",".","fingerprint",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py#L31-L43"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py","language":"python","identifier":"ContactPublicKeyManager._filter_new_emails","parameters":"(self, contact, key)","argument_list":"","return_statement":"","docstring":"Find new emails related to a contact public key.","docstring_summary":"Find new emails related to a contact public key.","docstring_tokens":["Find","new","emails","related","to","a","contact","public","key","."],"function":"def _filter_new_emails(self, contact, key):\n \"\"\"Find new emails related to a contact public key.\"\"\"\n known_emails = [x.address for x in contact.emails]\n for userid in key.userids:\n if userid.email not in known_emails:\n known_emails.append(userid.email)\n yield userid","function_tokens":["def","_filter_new_emails","(","self",",","contact",",","key",")",":","known_emails","=","[","x",".","address","for","x","in","contact",".","emails","]","for","userid","in","key",".","userids",":","if","userid",".","email","not","in","known_emails",":","known_emails",".","append","(","userid",".","email",")","yield","userid"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py#L45-L51"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py","language":"python","identifier":"ContactPublicKeyManager._filter_new_identities","parameters":"(self, contact, identities)","argument_list":"","return_statement":"","docstring":"Create new identities found for a contact.","docstring_summary":"Create new identities found for a contact.","docstring_tokens":["Create","new","identities","found","for","a","contact","."],"function":"def _filter_new_identities(self, contact, identities):\n \"\"\"Create new identities found for a contact.\"\"\"\n known_ids = [(x.type, x.name) for x in contact.identities]\n for identity in identities:\n if identity not in known_ids:\n yield identity","function_tokens":["def","_filter_new_identities","(","self",",","contact",",","identities",")",":","known_ids","=","[","(","x",".","type",",","x",".","name",")","for","x","in","contact",".","identities","]","for","identity","in","identities",":","if","identity","not","in","known_ids",":","yield","identity"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py#L53-L58"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py","language":"python","identifier":"ContactPublicKeyManager.process_identity","parameters":"(self, user, contact, new_identifier, type_)","argument_list":"","return_statement":"return result","docstring":"Process a contact new identity.","docstring_summary":"Process a contact new identity.","docstring_tokens":["Process","a","contact","new","identity","."],"function":"def process_identity(self, user, contact, new_identifier, type_):\n \"\"\"Process a contact new identity.\"\"\"\n result = ContactDiscoveryResult()\n discovers = self._find_keys(user, contact, new_identifier, type_)\n found_emails = []\n found_ids = []\n for disco in discovers:\n for key in disco.keys:\n result.keys.append(key)\n found_emails.extend(self._filter_new_emails(contact, key))\n if disco.identities:\n ids = self._filter_new_identities(contact, disco.identities)\n found_ids.extend(ids)\n for email in found_emails:\n if email.email not in [x.email for x in result.emails]:\n result.emails.append(email)\n for identity in found_ids:\n if identity not in result.identities:\n result.identities.append(identity)\n return result","function_tokens":["def","process_identity","(","self",",","user",",","contact",",","new_identifier",",","type_",")",":","result","=","ContactDiscoveryResult","(",")","discovers","=","self",".","_find_keys","(","user",",","contact",",","new_identifier",",","type_",")","found_emails","=","[","]","found_ids","=","[","]","for","disco","in","discovers",":","for","key","in","disco",".","keys",":","result",".","keys",".","append","(","key",")","found_emails",".","extend","(","self",".","_filter_new_emails","(","contact",",","key",")",")","if","disco",".","identities",":","ids","=","self",".","_filter_new_identities","(","contact",",","disco",".","identities",")","found_ids",".","extend","(","ids",")","for","email","in","found_emails",":","if","email",".","email","not","in","[","x",".","email","for","x","in","result",".","emails","]",":","result",".","emails",".","append","(","email",")","for","identity","in","found_ids",":","if","identity","not","in","result",".","identities",":","result",".","identities",".","append","(","identity",")","return","result"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/contact.py#L60-L79"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/keybase.py","language":"python","identifier":"KeybaseDiscovery.lookup_identity","parameters":"(self, identifier, type_)","argument_list":"","return_statement":"return DiscoveryResult(public_keys, identities)","docstring":"Find by name and type.","docstring_summary":"Find by name and type.","docstring_tokens":["Find","by","name","and","type","."],"function":"def lookup_identity(self, identifier, type_):\n \"\"\"Find by name and type.\"\"\"\n if type_ not in self._types:\n raise Exception('Invalid identity type {}'.format(type_))\n users = []\n find = self._fetch_identity(identifier, type_)\n if find:\n log.debug('Got keybase result : {}'.format(find))\n users.extend(find)\n keys = []\n identities = []\n for user in users:\n user_key = self._get_public_key(user['username'])\n if user_key:\n keys.append(user_key)\n for ident in self._types:\n if user['remote_proofs'].get(ident) and type_ != ident:\n identities.append((ident, user['remote_proofs'][ident]))\n public_keys = []\n for key in keys:\n public_keys.extend(self._parse_key(key))\n return DiscoveryResult(public_keys, identities)","function_tokens":["def","lookup_identity","(","self",",","identifier",",","type_",")",":","if","type_","not","in","self",".","_types",":","raise","Exception","(","'Invalid identity type {}'",".","format","(","type_",")",")","users","=","[","]","find","=","self",".","_fetch_identity","(","identifier",",","type_",")","if","find",":","log",".","debug","(","'Got keybase result : {}'",".","format","(","find",")",")","users",".","extend","(","find",")","keys","=","[","]","identities","=","[","]","for","user","in","users",":","user_key","=","self",".","_get_public_key","(","user","[","'username'","]",")","if","user_key",":","keys",".","append","(","user_key",")","for","ident","in","self",".","_types",":","if","user","[","'remote_proofs'","]",".","get","(","ident",")","and","type_","!=","ident",":","identities",".","append","(","(","ident",",","user","[","'remote_proofs'","]","[","ident","]",")",")","public_keys","=","[","]","for","key","in","keys",":","public_keys",".","extend","(","self",".","_parse_key","(","key",")",")","return","DiscoveryResult","(","public_keys",",","identities",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/keybase.py#L29-L50"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/keybase.py","language":"python","identifier":"KeybaseDiscovery._clean_name","parameters":"(self, name, type_)","argument_list":"","return_statement":"return name.lower()","docstring":"Format a clean user name depending on type.","docstring_summary":"Format a clean user name depending on type.","docstring_tokens":["Format","a","clean","user","name","depending","on","type","."],"function":"def _clean_name(self, name, type_):\n \"\"\"Format a clean user name depending on type.\"\"\"\n if type_ == 'twitter':\n if name.startswith('@'):\n return name.lstrip('@').lower()\n return name.lower()","function_tokens":["def","_clean_name","(","self",",","name",",","type_",")",":","if","type_","==","'twitter'",":","if","name",".","startswith","(","'@'",")",":","return","name",".","lstrip","(","'@'",")",".","lower","(",")","return","name",".","lower","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/keybase.py#L52-L57"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/keybase.py","language":"python","identifier":"KeybaseDiscovery._fetch_identity","parameters":"(self, name, type_)","argument_list":"","return_statement":"return res","docstring":"Make a user discover API call on keybase for a name and type.","docstring_summary":"Make a user discover API call on keybase for a name and type.","docstring_tokens":["Make","a","user","discover","API","call","on","keybase","for","a","name","and","type","."],"function":"def _fetch_identity(self, name, type_):\n \"\"\"Make a user discover API call on keybase for a name and type.\"\"\"\n clean_name = self._clean_name(name, type_)\n url = '{}\/user\/discover.json?{}={}'. \\\n format(self.url, type_, clean_name)\n log.debug('Will query keybase url {}'.format(url))\n res = requests.get(url, headers=self.headers, timeout=self.timeout)\n if res.status_code != 200:\n log.error('Keybase discover status {} for {} on {}'.\n format(res.status_code, clean_name, type_))\n return []\n result = res.json()\n if not result.get('matches'):\n log.debug('No match for keybase discovery of {} {}'.\n format(clean_name, type_))\n return []\n matches = result['matches'].get(type_, [[]])\n res = []\n for match in matches:\n res.extend(match)\n return res","function_tokens":["def","_fetch_identity","(","self",",","name",",","type_",")",":","clean_name","=","self",".","_clean_name","(","name",",","type_",")","url","=","'{}\/user\/discover.json?{}={}'",".","format","(","self",".","url",",","type_",",","clean_name",")","log",".","debug","(","'Will query keybase url {}'",".","format","(","url",")",")","res","=","requests",".","get","(","url",",","headers","=","self",".","headers",",","timeout","=","self",".","timeout",")","if","res",".","status_code","!=","200",":","log",".","error","(","'Keybase discover status {} for {} on {}'",".","format","(","res",".","status_code",",","clean_name",",","type_",")",")","return","[","]","result","=","res",".","json","(",")","if","not","result",".","get","(","'matches'",")",":","log",".","debug","(","'No match for keybase discovery of {} {}'",".","format","(","clean_name",",","type_",")",")","return","[","]","matches","=","result","[","'matches'","]",".","get","(","type_",",","[","[","]","]",")","res","=","[","]","for","match","in","matches",":","res",".","extend","(","match",")","return","res"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/keybase.py#L59-L79"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/keybase.py","language":"python","identifier":"KeybaseDiscovery._get_public_key","parameters":"(self, username)","argument_list":"","return_statement":"return res.text","docstring":"Fetch a public key for an user.","docstring_summary":"Fetch a public key for an user.","docstring_tokens":["Fetch","a","public","key","for","an","user","."],"function":"def _get_public_key(self, username):\n \"\"\"Fetch a public key for an user.\"\"\"\n url = '{}\/{}\/key.asc'.format(self.base_url, username)\n log.debug('Will query keybase url {}'.format(url))\n res = requests.get(url, headers=self.headers, timeout=self.timeout)\n if res.status_code != 200:\n log.error('Keybase user key fetch status {} for {}'.\n format(res.status_code, username))\n return None\n return res.text","function_tokens":["def","_get_public_key","(","self",",","username",")",":","url","=","'{}\/{}\/key.asc'",".","format","(","self",".","base_url",",","username",")","log",".","debug","(","'Will query keybase url {}'",".","format","(","url",")",")","res","=","requests",".","get","(","url",",","headers","=","self",".","headers",",","timeout","=","self",".","timeout",")","if","res",".","status_code","!=","200",":","log",".","error","(","'Keybase user key fetch status {} for {}'",".","format","(","res",".","status_code",",","username",")",")","return","None","return","res",".","text"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pgp\/caliopen_pgp\/keys\/keybase.py#L81-L90"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.data\/caliopen_data\/provider.py","language":"python","identifier":"DataProvider.__init__","parameters":"(self, config)","argument_list":"","return_statement":"","docstring":"Initialize a data provider, connecting it to store.","docstring_summary":"Initialize a data provider, connecting it to store.","docstring_tokens":["Initialize","a","data","provider","connecting","it","to","store","."],"function":"def __init__(self, config):\n \"\"\"Initialize a data provider, connecting it to store.\"\"\"\n self.config = config\n self._store = self._connect_store()\n self._search = None\n self.iterator = None","function_tokens":["def","__init__","(","self",",","config",")",":","self",".","config","=","config","self",".","_store","=","self",".","_connect_store","(",")","self",".","_search","=","None","self",".","iterator","=","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.data\/caliopen_data\/provider.py#L16-L21"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.data\/caliopen_data\/provider.py","language":"python","identifier":"DataProvider.prepare","parameters":"(self, query, **kwargs)","argument_list":"","return_statement":"","docstring":"Prepare the query to be iterated.","docstring_summary":"Prepare the query to be iterated.","docstring_tokens":["Prepare","the","query","to","be","iterated","."],"function":"def prepare(self, query, **kwargs):\n \"\"\"Prepare the query to be iterated.\"\"\"\n self._search = self._prepare(query, **kwargs)\n self.iterator = self._execute(**kwargs)","function_tokens":["def","prepare","(","self",",","query",",","*","*","kwargs",")",":","self",".","_search","=","self",".","_prepare","(","query",",","*","*","kwargs",")","self",".","iterator","=","self",".","_execute","(","*","*","kwargs",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.data\/caliopen_data\/provider.py#L23-L26"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.data\/caliopen_data\/provider.py","language":"python","identifier":"DataProvider.next","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Iterator method over search results.","docstring_summary":"Iterator method over search results.","docstring_tokens":["Iterator","method","over","search","results","."],"function":"def next(self):\n \"\"\"Iterator method over search results.\"\"\"\n if not self.iterator:\n raise StopIteration\n for item in self.iterator:\n yield self._format_item(item)","function_tokens":["def","next","(","self",")",":","if","not","self",".","iterator",":","raise","StopIteration","for","item","in","self",".","iterator",":","yield","self",".","_format_item","(","item",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.data\/caliopen_data\/provider.py#L28-L33"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.data\/caliopen_data\/provider.py","language":"python","identifier":"FileDataProvider.__init__","parameters":"(self, config)","argument_list":"","return_statement":"","docstring":"Create a new FileDataProvider.","docstring_summary":"Create a new FileDataProvider.","docstring_tokens":["Create","a","new","FileDataProvider","."],"function":"def __init__(self, config):\n \"\"\"Create a new FileDataProvider.\"\"\"\n super(FileDataProvider, self).__init__(config)\n self._filename = None","function_tokens":["def","__init__","(","self",",","config",")",":","super","(","FileDataProvider",",","self",")",".","__init__","(","config",")","self",".","_filename","=","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.data\/caliopen_data\/provider.py#L41-L44"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.data\/caliopen_data\/interface.py","language":"python","identifier":"IDataProvider._format_item","parameters":"(self, item)","argument_list":"","return_statement":"","docstring":"Format a result item from store into processing format.","docstring_summary":"Format a result item from store into processing format.","docstring_tokens":["Format","a","result","item","from","store","into","processing","format","."],"function":"def _format_item(self, item):\n \"\"\"Format a result item from store into processing format.\"\"\"\n raise NotImplementedError","function_tokens":["def","_format_item","(","self",",","item",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.data\/caliopen_data\/interface.py#L18-L20"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.data\/caliopen_data\/interface.py","language":"python","identifier":"IDataProvider.next","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Iterator method to retrieve results from provider.","docstring_summary":"Iterator method to retrieve results from provider.","docstring_tokens":["Iterator","method","to","retrieve","results","from","provider","."],"function":"def next(self):\n \"\"\"Iterator method to retrieve results from provider.\"\"\"\n raise NotImplementedError","function_tokens":["def","next","(","self",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.data\/caliopen_data\/interface.py#L28-L30"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.data\/caliopen_data\/store.py","language":"python","identifier":"save_file","parameters":"(config, input_file, dest)","argument_list":"","return_statement":"","docstring":"Save an input file as dest on object store.","docstring_summary":"Save an input file as dest on object store.","docstring_tokens":["Save","an","input","file","as","dest","on","object","store","."],"function":"def save_file(config, input_file, dest):\n \"\"\"Save an input file as dest on object store.\"\"\"\n conf = config['object_store']\n bucket = conf['buckets']['learn_models']\n client = Minio(conf[\"endpoint\"],\n access_key=conf[\"access_key\"],\n secret_key=conf[\"secret_key\"],\n secure=False)\n try:\n client.make_bucket(bucket, conf['location'])\n except BucketAlreadyOwnedByYou:\n pass\n except BucketAlreadyExists:\n pass\n except Exception as exc:\n raise exc\n try:\n resp = client.fput_object(bucket, dest, input_file)\n log.info('Put file {0}: {1}'.format(input_file, resp))\n except Exception as exc:\n log.info('Unable to save file in object store %r' % exc)\n raise exc","function_tokens":["def","save_file","(","config",",","input_file",",","dest",")",":","conf","=","config","[","'object_store'","]","bucket","=","conf","[","'buckets'","]","[","'learn_models'","]","client","=","Minio","(","conf","[","\"endpoint\"","]",",","access_key","=","conf","[","\"access_key\"","]",",","secret_key","=","conf","[","\"secret_key\"","]",",","secure","=","False",")","try",":","client",".","make_bucket","(","bucket",",","conf","[","'location'","]",")","except","BucketAlreadyOwnedByYou",":","pass","except","BucketAlreadyExists",":","pass","except","Exception","as","exc",":","raise","exc","try",":","resp","=","client",".","fput_object","(","bucket",",","dest",",","input_file",")","log",".","info","(","'Put file {0}: {1}'",".","format","(","input_file",",","resp",")",")","except","Exception","as","exc",":","log",".","info","(","'Unable to save file in object store %r'","%","exc",")","raise","exc"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.data\/caliopen_data\/store.py#L11-L32"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py","language":"python","identifier":"Singleton.__new__","parameters":"(cls, *args, **kwargs)","argument_list":"","return_statement":"return cls._instance","docstring":"Create singleton instance of class.","docstring_summary":"Create singleton instance of class.","docstring_tokens":["Create","singleton","instance","of","class","."],"function":"def __new__(cls, *args, **kwargs):\n \"\"\"Create singleton instance of class.\"\"\"\n if not isinstance(cls._instance, cls):\n cls._instance = object.__new__(cls, *args, **kwargs)\n return cls._instance","function_tokens":["def","__new__","(","cls",",","*","args",",","*","*","kwargs",")",":","if","not","isinstance","(","cls",".","_instance",",","cls",")",":","cls",".","_instance","=","object",".","__new__","(","cls",",","*","args",",","*","*","kwargs",")","return","cls",".","_instance"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py#L21-L25"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py","language":"python","identifier":"GeoipReader.__init__","parameters":"(self, filename)","argument_list":"","return_statement":"","docstring":"A singleton around geoip reader.","docstring_summary":"A singleton around geoip reader.","docstring_tokens":["A","singleton","around","geoip","reader","."],"function":"def __init__(self, filename):\n \"\"\"A singleton around geoip reader.\"\"\"\n self.reader = geoip.Reader(filename)","function_tokens":["def","__init__","(","self",",","filename",")",":","self",".","reader","=","geoip",".","Reader","(","filename",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py#L31-L33"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py","language":"python","identifier":"DeviceFeature.__init__","parameters":"(self, user, conf=None)","argument_list":"","return_statement":"","docstring":"Instanciate a new qualifier for an user.","docstring_summary":"Instanciate a new qualifier for an user.","docstring_tokens":["Instanciate","a","new","qualifier","for","an","user","."],"function":"def __init__(self, user, conf=None):\n \"\"\"Instanciate a new qualifier for an user.\"\"\"\n self.user = user\n self.conf = conf\n self._features = init_features('device')","function_tokens":["def","__init__","(","self",",","user",",","conf","=","None",")",":","self",".","user","=","user","self",".","conf","=","conf","self",".","_features","=","init_features","(","'device'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py#L39-L43"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py","language":"python","identifier":"DeviceFeature.process","parameters":"(self, device)","argument_list":"","return_statement":"return None, features","docstring":"Process a device to compute it's privacy features and PI.","docstring_summary":"Process a device to compute it's privacy features and PI.","docstring_tokens":["Process","a","device","to","compute","it","s","privacy","features","and","PI","."],"function":"def process(self, device):\n \"\"\"Process a device to compute it's privacy features and PI.\"\"\"\n features = {}\n if device.user_agent:\n ua = parse_ua(device.user_agent)\n browser_version = ua.browser.version_string.lower()\n features.update({'browser_family': ua.browser.family.lower(),\n 'browser_version': browser_version,\n 'os_family': ua.os.family.lower(),\n 'os_version': ua.os.version_string.lower(),\n 'device_family': ua.device.family.lower(),\n 'device_type': self._get_device_type(ua)})\n # XXX processing IP address to detect some informations\n if device.ip_creation:\n features.update(self._process_ip_address(device.ip_creation))\n else:\n log.warn('No ip address found for device')\n return None, features","function_tokens":["def","process","(","self",",","device",")",":","features","=","{","}","if","device",".","user_agent",":","ua","=","parse_ua","(","device",".","user_agent",")","browser_version","=","ua",".","browser",".","version_string",".","lower","(",")","features",".","update","(","{","'browser_family'",":","ua",".","browser",".","family",".","lower","(",")",",","'browser_version'",":","browser_version",",","'os_family'",":","ua",".","os",".","family",".","lower","(",")",",","'os_version'",":","ua",".","os",".","version_string",".","lower","(",")",",","'device_family'",":","ua",".","device",".","family",".","lower","(",")",",","'device_type'",":","self",".","_get_device_type","(","ua",")","}",")","# XXX processing IP address to detect some informations","if","device",".","ip_creation",":","features",".","update","(","self",".","_process_ip_address","(","device",".","ip_creation",")",")","else",":","log",".","warn","(","'No ip address found for device'",")","return","None",",","features"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py#L45-L62"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py","language":"python","identifier":"DeviceFeature._get_device_type","parameters":"(self, ua)","argument_list":"","return_statement":"return 'other'","docstring":"Return guessed type of user agent.","docstring_summary":"Return guessed type of user agent.","docstring_tokens":["Return","guessed","type","of","user","agent","."],"function":"def _get_device_type(self, ua):\n \"\"\"Return guessed type of user agent.\"\"\"\n if ua.is_mobile:\n return 'smartphone'\n if ua.is_tablet:\n return 'tablet'\n if ua.is_pc:\n return 'desktop'\n return 'other'","function_tokens":["def","_get_device_type","(","self",",","ua",")",":","if","ua",".","is_mobile",":","return","'smartphone'","if","ua",".","is_tablet",":","return","'tablet'","if","ua",".","is_pc",":","return","'desktop'","return","'other'"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/device.py#L64-L72"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.__init__","parameters":"(self, message, config)","argument_list":"","return_statement":"","docstring":"Get a ``MailMessage`` instance and extract privacy features.","docstring_summary":"Get a ``MailMessage`` instance and extract privacy features.","docstring_tokens":["Get","a","MailMessage","instance","and","extract","privacy","features","."],"function":"def __init__(self, message, config):\n \"\"\"Get a ``MailMessage`` instance and extract privacy features.\"\"\"\n self.message = message\n self.config = config\n self._features = init_features('message')","function_tokens":["def","__init__","(","self",",","message",",","config",")",":","self",".","message","=","message","self",".","config","=","config","self",".","_features","=","init_features","(","'message'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L31-L35"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.is_blacklist_mx","parameters":"(self, mx)","argument_list":"","return_statement":"return False","docstring":"MX is blacklisted.","docstring_summary":"MX is blacklisted.","docstring_tokens":["MX","is","blacklisted","."],"function":"def is_blacklist_mx(self, mx):\n \"\"\"MX is blacklisted.\"\"\"\n blacklisted = self.config.get('blacklistes.mx')\n if not blacklisted:\n return False\n if mx in blacklisted:\n return True\n return False","function_tokens":["def","is_blacklist_mx","(","self",",","mx",")",":","blacklisted","=","self",".","config",".","get","(","'blacklistes.mx'",")","if","not","blacklisted",":","return","False","if","mx","in","blacklisted",":","return","True","return","False"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L37-L44"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.is_whitelist_mx","parameters":"(self, mx)","argument_list":"","return_statement":"return False","docstring":"MX is whitelisted.","docstring_summary":"MX is whitelisted.","docstring_tokens":["MX","is","whitelisted","."],"function":"def is_whitelist_mx(self, mx):\n \"\"\"MX is whitelisted.\"\"\"\n whitelistes = self.config.get('whitelistes.mx')\n if not whitelistes:\n return False\n if mx in whitelistes:\n return True\n return False","function_tokens":["def","is_whitelist_mx","(","self",",","mx",")",":","whitelistes","=","self",".","config",".","get","(","'whitelistes.mx'",")","if","not","whitelistes",":","return","False","if","mx","in","whitelistes",":","return","True","return","False"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L46-L53"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.internal_domains","parameters":"(self)","argument_list":"","return_statement":"return domains if domains else []","docstring":"Get internal hosts from configuration.","docstring_summary":"Get internal hosts from configuration.","docstring_tokens":["Get","internal","hosts","from","configuration","."],"function":"def internal_domains(self):\n \"\"\"Get internal hosts from configuration.\"\"\"\n domains = self.config.get('internal_domains')\n return domains if domains else []","function_tokens":["def","internal_domains","(","self",")",":","domains","=","self",".","config",".","get","(","'internal_domains'",")","return","domains","if","domains","else","[","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L56-L59"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.emitter_reputation","parameters":"(self, mx)","argument_list":"","return_statement":"return 'unknown'","docstring":"Return features about emitter.","docstring_summary":"Return features about emitter.","docstring_tokens":["Return","features","about","emitter","."],"function":"def emitter_reputation(self, mx):\n \"\"\"Return features about emitter.\"\"\"\n if self.is_blacklist_mx(mx):\n return 'blacklisted'\n if self.is_whitelist_mx(mx):\n return 'whitelisted'\n return 'unknown'","function_tokens":["def","emitter_reputation","(","self",",","mx",")",":","if","self",".","is_blacklist_mx","(","mx",")",":","return","'blacklisted'","if","self",".","is_whitelist_mx","(","mx",")",":","return","'whitelisted'","return","'unknown'"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L61-L67"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.emitter_certificate","parameters":"(self)","argument_list":"","return_statement":"return None","docstring":"Get the certificate from emitter.","docstring_summary":"Get the certificate from emitter.","docstring_tokens":["Get","the","certificate","from","emitter","."],"function":"def emitter_certificate(self):\n \"\"\"Get the certificate from emitter.\"\"\"\n return None","function_tokens":["def","emitter_certificate","(","self",")",":","return","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L69-L71"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.mail_agent","parameters":"(self)","argument_list":"","return_statement":"return self.message.mail.get('X-Mailer', '').lower()","docstring":"Get the mailer used for this message.","docstring_summary":"Get the mailer used for this message.","docstring_tokens":["Get","the","mailer","used","for","this","message","."],"function":"def mail_agent(self):\n \"\"\"Get the mailer used for this message.\"\"\"\n # XXX normalize better and more ?\n return self.message.mail.get('X-Mailer', '').lower()","function_tokens":["def","mail_agent","(","self",")",":","# XXX normalize better and more ?","return","self",".","message",".","mail",".","get","(","'X-Mailer'",",","''",")",".","lower","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L74-L77"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.transport_signature","parameters":"(self)","argument_list":"","return_statement":"return self.message.mail.get('DKIM-Signature')","docstring":"Get the transport signature if any.","docstring_summary":"Get the transport signature if any.","docstring_tokens":["Get","the","transport","signature","if","any","."],"function":"def transport_signature(self):\n \"\"\"Get the transport signature if any.\"\"\"\n return self.message.mail.get('DKIM-Signature')","function_tokens":["def","transport_signature","(","self",")",":","return","self",".","message",".","mail",".","get","(","'DKIM-Signature'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L80-L82"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.spam_informations","parameters":"(self)","argument_list":"","return_statement":"return {'spam_score': spam.score,\n 'spam_method': spam.method,\n 'is_spam': spam.is_spam}","docstring":"Return a global spam_score and related features.","docstring_summary":"Return a global spam_score and related features.","docstring_tokens":["Return","a","global","spam_score","and","related","features","."],"function":"def spam_informations(self):\n \"\"\"Return a global spam_score and related features.\"\"\"\n spam = SpamScorer(self.message.mail)\n return {'spam_score': spam.score,\n 'spam_method': spam.method,\n 'is_spam': spam.is_spam}","function_tokens":["def","spam_informations","(","self",")",":","spam","=","SpamScorer","(","self",".","message",".","mail",")","return","{","'spam_score'",":","spam",".","score",",","'spam_method'",":","spam",".","method",",","'is_spam'",":","spam",".","is_spam","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L85-L90"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.is_internal","parameters":"(self)","argument_list":"","return_statement":"return False","docstring":"Return true if it's an internal message.","docstring_summary":"Return true if it's an internal message.","docstring_tokens":["Return","true","if","it","s","an","internal","message","."],"function":"def is_internal(self):\n \"\"\"Return true if it's an internal message.\"\"\"\n from_ = self.message.mail.get('From')\n for domain in self.internal_domains:\n if domain in from_:\n return True\n return False","function_tokens":["def","is_internal","(","self",")",":","from_","=","self",".","message",".","mail",".","get","(","'From'",")","for","domain","in","self",".","internal_domains",":","if","domain","in","from_",":","return","True","return","False"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L93-L99"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.get_signature_informations","parameters":"(self)","argument_list":"","return_statement":"return features","docstring":"Get message signature features.","docstring_summary":"Get message signature features.","docstring_tokens":["Get","message","signature","features","."],"function":"def get_signature_informations(self):\n \"\"\"Get message signature features.\"\"\"\n signed_parts = [x for x in self.message.attachments\n if 'pgp-sign' in x.content_type]\n if not signed_parts:\n return {}\n sign = pgpy.PGPSignature()\n features = {'message_signed': True,\n 'message_signature_type': 'PGP'}\n try:\n sign.parse(signed_parts[0].data)\n features.update({'message_signer': sign.signer})\n except Exception as exc:\n log.error('Unable to parse pgp signature {}'.format(exc))\n return features","function_tokens":["def","get_signature_informations","(","self",")",":","signed_parts","=","[","x","for","x","in","self",".","message",".","attachments","if","'pgp-sign'","in","x",".","content_type","]","if","not","signed_parts",":","return","{","}","sign","=","pgpy",".","PGPSignature","(",")","features","=","{","'message_signed'",":","True",",","'message_signature_type'",":","'PGP'","}","try",":","sign",".","parse","(","signed_parts","[","0","]",".","data",")","features",".","update","(","{","'message_signer'",":","sign",".","signer","}",")","except","Exception","as","exc",":","log",".","error","(","'Unable to parse pgp signature {}'",".","format","(","exc",")",")","return","features"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L101-L115"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.get_encryption_informations","parameters":"(self)","argument_list":"","return_statement":"return {'message_encrypted': is_encrypted,\n 'message_encryption_method': 'pgp' if is_encrypted else ''}","docstring":"Get message encryption features.","docstring_summary":"Get message encryption features.","docstring_tokens":["Get","message","encryption","features","."],"function":"def get_encryption_informations(self):\n \"\"\"Get message encryption features.\"\"\"\n is_encrypted = False\n if 'encrypted' in self.message.extra_parameters:\n is_encrypted = True\n\n # Maybe pgp\/inline ?\n if not is_encrypted:\n try:\n body = self.message.body_plain.decode('utf-8')\n if body.startswith(PGP_MESSAGE_HEADER):\n is_encrypted = True\n except UnicodeDecodeError:\n log.warn('Invalid body_plain encoding for message')\n pass\n\n return {'message_encrypted': is_encrypted,\n 'message_encryption_method': 'pgp' if is_encrypted else ''}","function_tokens":["def","get_encryption_informations","(","self",")",":","is_encrypted","=","False","if","'encrypted'","in","self",".","message",".","extra_parameters",":","is_encrypted","=","True","# Maybe pgp\/inline ?","if","not","is_encrypted",":","try",":","body","=","self",".","message",".","body_plain",".","decode","(","'utf-8'",")","if","body",".","startswith","(","PGP_MESSAGE_HEADER",")",":","is_encrypted","=","True","except","UnicodeDecodeError",":","log",".","warn","(","'Invalid body_plain encoding for message'",")","pass","return","{","'message_encrypted'",":","is_encrypted",",","'message_encryption_method'",":","'pgp'","if","is_encrypted","else","''","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L117-L134"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature._get_features","parameters":"(self)","argument_list":"","return_statement":"return features","docstring":"Extract privacy features.","docstring_summary":"Extract privacy features.","docstring_tokens":["Extract","privacy","features","."],"function":"def _get_features(self):\n \"\"\"Extract privacy features.\"\"\"\n features = self._features.copy()\n received = self.message.headers.get('Received', [])\n features.update(get_ingress_features(received, self.internal_domains))\n mx = features.get('ingress_server')\n reputation = None if not mx else self.emitter_reputation(mx)\n features['mail_emitter_mx_reputation'] = reputation\n features['mail_emitter_certificate'] = self.emitter_certificate()\n features['mail_agent'] = self.mail_agent\n features['is_internal'] = self.is_internal\n features.update(self.get_signature_informations())\n features.update(self.get_encryption_informations())\n features.update(self.spam_informations)\n\n if self.transport_signature:\n features.update({'transport_signed': True})\n return features","function_tokens":["def","_get_features","(","self",")",":","features","=","self",".","_features",".","copy","(",")","received","=","self",".","message",".","headers",".","get","(","'Received'",",","[","]",")","features",".","update","(","get_ingress_features","(","received",",","self",".","internal_domains",")",")","mx","=","features",".","get","(","'ingress_server'",")","reputation","=","None","if","not","mx","else","self",".","emitter_reputation","(","mx",")","features","[","'mail_emitter_mx_reputation'","]","=","reputation","features","[","'mail_emitter_certificate'","]","=","self",".","emitter_certificate","(",")","features","[","'mail_agent'","]","=","self",".","mail_agent","features","[","'is_internal'","]","=","self",".","is_internal","features",".","update","(","self",".","get_signature_informations","(",")",")","features",".","update","(","self",".","get_encryption_informations","(",")",")","features",".","update","(","self",".","spam_informations",")","if","self",".","transport_signature",":","features",".","update","(","{","'transport_signed'",":","True","}",")","return","features"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L136-L153"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature._compute_pi","parameters":"(self, participants, features)","argument_list":"","return_statement":"return PIParameter({'technic': sum(pi_t.values()),\n 'context': sum(pi_cx.values()),\n 'comportment': sum(pi_co.values()),\n 'version': 0})","docstring":"Compute Privacy Indexes for a message.","docstring_summary":"Compute Privacy Indexes for a message.","docstring_tokens":["Compute","Privacy","Indexes","for","a","message","."],"function":"def _compute_pi(self, participants, features):\n \"\"\"Compute Privacy Indexes for a message.\"\"\"\n log.info('PI features {}'.format(features))\n pi_cx = {} # Contextual privacy index\n pi_co = {} # Comportemental privacy index\n pi_t = {} # Technical privacy index\n reput = features.get('mail_emitter_mx_reputation')\n if reput == 'whitelisted':\n pi_cx['reputation_whitelist'] = 20\n elif reput == 'unknown':\n pi_cx['reputation_unknow'] = 10\n known_contacts = []\n known_public_key = 0\n for part, contact in participants:\n if contact:\n known_contacts.append(contact)\n if contact.public_key:\n known_public_key += 1\n if len(participants) == len(known_contacts):\n # - Si tous les contacts sont d\u00e9j\u00e0 connus le PI\u1d9c\u02e3\n # augmente de la valeur du PI\u1d9c\u1d52 le plus bas des PI\u1d9c\u1d52 des contacts.\n contact_pi_cos = [x.pi['comportment'] for x in known_contacts\n if x.pi and 'comportment' in x.pi]\n if contact_pi_cos:\n pi_cx['known_contacts'] = min(contact_pi_cos)\n\n if known_public_key == len(known_contacts):\n pi_co['contact_pubkey'] = 20\n ext_hops = features.get('nb_external_hops', 0)\n if ext_hops <= 1:\n tls = features.get('ingress_socket_version')\n if tls:\n if tls not in TLS_VERSION_PI:\n log.warn('Unknown TLS version {}'.format(tls))\n else:\n pi_t += TLS_VERSION_PI[tls]\n if features.get('mail_emitter_certificate'):\n pi_t['emitter_certificate'] = 10\n if features.get('transport_signed'):\n pi_t['transport_signed'] = 10\n if features.get('message_encrypted'):\n pi_t['encrypted'] = 30\n log.info('PI compute t:{} cx:{} co:{}'.format(pi_t, pi_cx, pi_co))\n return PIParameter({'technic': sum(pi_t.values()),\n 'context': sum(pi_cx.values()),\n 'comportment': sum(pi_co.values()),\n 'version': 0})","function_tokens":["def","_compute_pi","(","self",",","participants",",","features",")",":","log",".","info","(","'PI features {}'",".","format","(","features",")",")","pi_cx","=","{","}","# Contextual privacy index","pi_co","=","{","}","# Comportemental privacy index","pi_t","=","{","}","# Technical privacy index","reput","=","features",".","get","(","'mail_emitter_mx_reputation'",")","if","reput","==","'whitelisted'",":","pi_cx","[","'reputation_whitelist'","]","=","20","elif","reput","==","'unknown'",":","pi_cx","[","'reputation_unknow'","]","=","10","known_contacts","=","[","]","known_public_key","=","0","for","part",",","contact","in","participants",":","if","contact",":","known_contacts",".","append","(","contact",")","if","contact",".","public_key",":","known_public_key","+=","1","if","len","(","participants",")","==","len","(","known_contacts",")",":","# - Si tous les contacts sont d\u00e9j\u00e0 connus le PI\u1d9c\u02e3","# augmente de la valeur du PI\u1d9c\u1d52 le plus bas des PI\u1d9c\u1d52 des contacts.","contact_pi_cos","=","[","x",".","pi","[","'comportment'","]","for","x","in","known_contacts","if","x",".","pi","and","'comportment'","in","x",".","pi","]","if","contact_pi_cos",":","pi_cx","[","'known_contacts'","]","=","min","(","contact_pi_cos",")","if","known_public_key","==","len","(","known_contacts",")",":","pi_co","[","'contact_pubkey'","]","=","20","ext_hops","=","features",".","get","(","'nb_external_hops'",",","0",")","if","ext_hops","<=","1",":","tls","=","features",".","get","(","'ingress_socket_version'",")","if","tls",":","if","tls","not","in","TLS_VERSION_PI",":","log",".","warn","(","'Unknown TLS version {}'",".","format","(","tls",")",")","else",":","pi_t","+=","TLS_VERSION_PI","[","tls","]","if","features",".","get","(","'mail_emitter_certificate'",")",":","pi_t","[","'emitter_certificate'","]","=","10","if","features",".","get","(","'transport_signed'",")",":","pi_t","[","'transport_signed'","]","=","10","if","features",".","get","(","'message_encrypted'",")",":","pi_t","[","'encrypted'","]","=","30","log",".","info","(","'PI compute t:{} cx:{} co:{}'",".","format","(","pi_t",",","pi_cx",",","pi_co",")",")","return","PIParameter","(","{","'technic'",":","sum","(","pi_t",".","values","(",")",")",",","'context'",":","sum","(","pi_cx",".","values","(",")",")",",","'comportment'",":","sum","(","pi_co",".","values","(",")",")",",","'version'",":","0","}",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L155-L201"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py","language":"python","identifier":"InboundMailFeature.process","parameters":"(self, user, message, participants)","argument_list":"","return_statement":"","docstring":"Process the message for privacy features and PI compute.\n\n :param user: user the message belong to\n :ptype user: caliopen_main.user.core.User\n :param message: a message parameter that will be updated with PI\n :ptype message: NewMessage\n :param participants: an array of participant with related Contact\n :ptype participants: list(Participant, Contact)","docstring_summary":"Process the message for privacy features and PI compute.","docstring_tokens":["Process","the","message","for","privacy","features","and","PI","compute","."],"function":"def process(self, user, message, participants):\n \"\"\"\n Process the message for privacy features and PI compute.\n\n :param user: user the message belong to\n :ptype user: caliopen_main.user.core.User\n :param message: a message parameter that will be updated with PI\n :ptype message: NewMessage\n :param participants: an array of participant with related Contact\n :ptype participants: list(Participant, Contact)\n \"\"\"\n features = self._get_features()\n message.pi = self._compute_pi(participants, features)\n il = compute_importance(user, message, features, participants)\n message.privacy_features = features\n message.importance_level = il","function_tokens":["def","process","(","self",",","user",",","message",",","participants",")",":","features","=","self",".","_get_features","(",")","message",".","pi","=","self",".","_compute_pi","(","participants",",","features",")","il","=","compute_importance","(","user",",","message",",","features",",","participants",")","message",".","privacy_features","=","features","message",".","importance_level","=","il"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/mail.py#L203-L218"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py","language":"python","identifier":"pstdev","parameters":"(avg, data)","argument_list":"","return_statement":"return (ss \/ float(len(data))) ** 0.5","docstring":"Population standard deviation.","docstring_summary":"Population standard deviation.","docstring_tokens":["Population","standard","deviation","."],"function":"def pstdev(avg, data):\n \"\"\"Population standard deviation.\"\"\"\n ss = sum((x - avg) ** 2 for x in data)\n return (ss \/ float(len(data))) ** 0.5","function_tokens":["def","pstdev","(","avg",",","data",")",":","ss","=","sum","(","(","x","-","avg",")","**","2","for","x","in","data",")","return","(","ss","\/","float","(","len","(","data",")",")",")","**","0.5"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py#L17-L20"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py","language":"python","identifier":"ContactFeature._compute_histogram","parameters":"(self, email)","argument_list":"","return_statement":"return (0.0, 0.0, 0.0)","docstring":"Get an histogram for a contact email and compute basic infos.","docstring_summary":"Get an histogram for a contact email and compute basic infos.","docstring_tokens":["Get","an","histogram","for","a","contact","email","and","compute","basic","infos","."],"function":"def _compute_histogram(self, email):\n \"\"\"Get an histogram for a contact email and compute basic infos.\"\"\"\n histo = ParticipantHistogram(self.user, 'day')\n data = histo.find_by_address(email)\n log.info('Got email {0} histogram result {1}'.format(email, data))\n if data:\n values = [x[1] for x in data]\n total = sum(values)\n avg = total \/ float(len(values))\n return (total, avg, pstdev(avg, values))\n return (0.0, 0.0, 0.0)","function_tokens":["def","_compute_histogram","(","self",",","email",")",":","histo","=","ParticipantHistogram","(","self",".","user",",","'day'",")","data","=","histo",".","find_by_address","(","email",")","log",".","info","(","'Got email {0} histogram result {1}'",".","format","(","email",",","data",")",")","if","data",":","values","=","[","x","[","1","]","for","x","in","data","]","total","=","sum","(","values",")","avg","=","total","\/","float","(","len","(","values",")",")","return","(","total",",","avg",",","pstdev","(","avg",",","values",")",")","return","(","0.0",",","0.0",",","0.0",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py#L31-L41"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py","language":"python","identifier":"ContactFeature._get_histogram","parameters":"(self, contact)","argument_list":"","return_statement":"return {}","docstring":"Get privacy features related to message histograms.","docstring_summary":"Get privacy features related to message histograms.","docstring_tokens":["Get","privacy","features","related","to","message","histograms","."],"function":"def _get_histogram(self, contact):\n \"\"\"Get privacy features related to message histograms.\"\"\"\n histograms = [self._compute_histogram(x.address)\n for x in contact.emails]\n if histograms:\n best = max(histograms)\n return {'message_day_total': best[0],\n 'message_day_avg': best[1],\n 'message_day_pstdev': best[2]}\n return {}","function_tokens":["def","_get_histogram","(","self",",","contact",")",":","histograms","=","[","self",".","_compute_histogram","(","x",".","address",")","for","x","in","contact",".","emails","]","if","histograms",":","best","=","max","(","histograms",")","return","{","'message_day_total'",":","best","[","0","]",",","'message_day_avg'",":","best","[","1","]",",","'message_day_pstdev'",":","best","[","2","]","}","return","{","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py#L43-L52"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py","language":"python","identifier":"ContactFeature._get_technical","parameters":"(self, contact)","argument_list":"","return_statement":"return features","docstring":"Get technical features for a contact.","docstring_summary":"Get technical features for a contact.","docstring_tokens":["Get","technical","features","for","a","contact","."],"function":"def _get_technical(self, contact):\n \"\"\"Get technical features for a contact.\"\"\"\n features = {}\n if hasattr(contact, 'public_keys') and contact.public_keys:\n max_size = max([x.size for x in contact.public_keys])\n if max_size:\n features.update({'public_key_best_size': max_size})\n return features","function_tokens":["def","_get_technical","(","self",",","contact",")",":","features","=","{","}","if","hasattr","(","contact",",","'public_keys'",")","and","contact",".","public_keys",":","max_size","=","max","(","[","x",".","size","for","x","in","contact",".","public_keys","]",")","if","max_size",":","features",".","update","(","{","'public_key_best_size'",":","max_size","}",")","return","features"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py#L54-L61"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py","language":"python","identifier":"ContactFeature.process","parameters":"(self, contact)","argument_list":"","return_statement":"return pi, marshal_features(features)","docstring":"Process a contact to extract all privacy features.","docstring_summary":"Process a contact to extract all privacy features.","docstring_tokens":["Process","a","contact","to","extract","all","privacy","features","."],"function":"def process(self, contact):\n \"\"\"Process a contact to extract all privacy features.\"\"\"\n features = self._get_histogram(contact)\n features.update(self._get_technical(contact))\n log.info('Contact {0} have features {1}'.\n format(contact.contact_id, features))\n pi = self._compute_pi(contact, features)\n return pi, marshal_features(features)","function_tokens":["def","process","(","self",",","contact",")",":","features","=","self",".","_get_histogram","(","contact",")","features",".","update","(","self",".","_get_technical","(","contact",")",")","log",".","info","(","'Contact {0} have features {1}'",".","format","(","contact",".","contact_id",",","features",")",")","pi","=","self",".","_compute_pi","(","contact",",","features",")","return","pi",",","marshal_features","(","features",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/contact.py#L94-L101"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py","language":"python","identifier":"check_feature_bounding","parameters":"(value, feature)","argument_list":"","return_statement":"return True","docstring":"Check that a feature fit between min and max value if apply.","docstring_summary":"Check that a feature fit between min and max value if apply.","docstring_tokens":["Check","that","a","feature","fit","between","min","and","max","value","if","apply","."],"function":"def check_feature_bounding(value, feature):\n \"\"\"Check that a feature fit between min and max value if apply.\"\"\"\n if 'min' in feature and value < feature['min']:\n return False\n if 'max' in feature and value > feature['max']:\n return False\n return True","function_tokens":["def","check_feature_bounding","(","value",",","feature",")",":","if","'min'","in","feature","and","value","<","feature","[","'min'","]",":","return","False","if","'max'","in","feature","and","value",">","feature","[","'max'","]",":","return","False","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py#L46-L52"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py","language":"python","identifier":"find_feature","parameters":"(name)","argument_list":"","return_statement":"","docstring":"Find a feature by its name.","docstring_summary":"Find a feature by its name.","docstring_tokens":["Find","a","feature","by","its","name","."],"function":"def find_feature(name):\n \"\"\"Find a feature by its name.\"\"\"\n if name in FEATURES:\n return FEATURES[name]","function_tokens":["def","find_feature","(","name",")",":","if","name","in","FEATURES",":","return","FEATURES","[","name","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py#L55-L58"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py","language":"python","identifier":"check_feature","parameters":"(name, value)","argument_list":"","return_statement":"","docstring":"Check that a feature have a correct value.","docstring_summary":"Check that a feature have a correct value.","docstring_tokens":["Check","that","a","feature","have","a","correct","value","."],"function":"def check_feature(name, value):\n \"\"\"Check that a feature have a correct value.\"\"\"\n\n feature = find_feature(name)\n if not feature:\n return False\n\n if feature['type'] == 'int':\n try:\n int(value)\n except ValueError:\n return False\n return check_feature_bounding(value, feature)\n\n elif feature['type'] == 'bool':\n return True if value in (True, False) else False\n elif feature['type'] == 'string':\n return True\n log.error('Invalid feature type %s, fail silently for the moment' %\n feature['type'])","function_tokens":["def","check_feature","(","name",",","value",")",":","feature","=","find_feature","(","name",")","if","not","feature",":","return","False","if","feature","[","'type'","]","==","'int'",":","try",":","int","(","value",")","except","ValueError",":","return","False","return","check_feature_bounding","(","value",",","feature",")","elif","feature","[","'type'","]","==","'bool'",":","return","True","if","value","in","(","True",",","False",")","else","False","elif","feature","[","'type'","]","==","'string'",":","return","True","log",".","error","(","'Invalid feature type %s, fail silently for the moment'","%","feature","[","'type'","]",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py#L61-L80"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py","language":"python","identifier":"unmarshal_feature","parameters":"(name, value)","argument_list":"","return_statement":"","docstring":"Unmarshal a feature to it's type representation.","docstring_summary":"Unmarshal a feature to it's type representation.","docstring_tokens":["Unmarshal","a","feature","to","it","s","type","representation","."],"function":"def unmarshal_feature(name, value):\n \"\"\"Unmarshal a feature to it's type representation.\"\"\"\n if not check_feature(name, value):\n raise ValueError('Invalid value {} for feature {}'.format(value, name))\n feature = find_feature(name)\n if not feature:\n log.warn('Unknow feature %s' % name)\n return None\n if feature['type'] == 'int':\n return int(value)\n elif feature['type'] == 'bool':\n return True if value.lower().startswith('t') else False\n elif feature['type'] == 'string':\n return value","function_tokens":["def","unmarshal_feature","(","name",",","value",")",":","if","not","check_feature","(","name",",","value",")",":","raise","ValueError","(","'Invalid value {} for feature {}'",".","format","(","value",",","name",")",")","feature","=","find_feature","(","name",")","if","not","feature",":","log",".","warn","(","'Unknow feature %s'","%","name",")","return","None","if","feature","[","'type'","]","==","'int'",":","return","int","(","value",")","elif","feature","[","'type'","]","==","'bool'",":","return","True","if","value",".","lower","(",")",".","startswith","(","'t'",")","else","False","elif","feature","[","'type'","]","==","'string'",":","return","value"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py#L83-L96"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py","language":"python","identifier":"unmarshal_features","parameters":"(features)","argument_list":"","return_statement":"return res","docstring":"Unmarshal a dict of features for suitable output.","docstring_summary":"Unmarshal a dict of features for suitable output.","docstring_tokens":["Unmarshal","a","dict","of","features","for","suitable","output","."],"function":"def unmarshal_features(features):\n \"\"\"Unmarshal a dict of features for suitable output.\"\"\"\n res = {}\n for name, value in features.items():\n try:\n new_value = unmarshal_feature(name, value)\n res[name] = new_value\n except ValueError:\n log.warn('Feature {} with {} do not marshall'.format(name, value))\n pass\n return res","function_tokens":["def","unmarshal_features","(","features",")",":","res","=","{","}","for","name",",","value","in","features",".","items","(",")",":","try",":","new_value","=","unmarshal_feature","(","name",",","value",")","res","[","name","]","=","new_value","except","ValueError",":","log",".","warn","(","'Feature {} with {} do not marshall'",".","format","(","name",",","value",")",")","pass","return","res"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py#L99-L109"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py","language":"python","identifier":"marshal_features","parameters":"(features)","argument_list":"","return_statement":"return res","docstring":"Unmarshall a dict of features suitable for storage.","docstring_summary":"Unmarshall a dict of features suitable for storage.","docstring_tokens":["Unmarshall","a","dict","of","features","suitable","for","storage","."],"function":"def marshal_features(features):\n \"\"\"Unmarshall a dict of features suitable for storage.\"\"\"\n res = {}\n for k, v in features.items():\n if not (v == '' or v is None):\n res[k] = str(v)\n return res","function_tokens":["def","marshal_features","(","features",")",":","res","=","{","}","for","k",",","v","in","features",".","items","(",")",":","if","not","(","v","==","''","or","v","is","None",")",":","res","[","k","]","=","str","(","v",")","return","res"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py#L112-L118"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py","language":"python","identifier":"init_features","parameters":"(type_)","argument_list":"","return_statement":"return output","docstring":"Initialize privacy features for a given object type.","docstring_summary":"Initialize privacy features for a given object type.","docstring_tokens":["Initialize","privacy","features","for","a","given","object","type","."],"function":"def init_features(type_):\n \"\"\"Initialize privacy features for a given object type.\"\"\"\n if type_ == 'contact':\n features = CONTACT\n elif type_ == 'device':\n features = DEVICE\n elif type_ == 'message':\n features = MESSAGE\n else:\n raise ValueError('Invalid feature type %s' % type_)\n\n output = {}\n for k, v in features.items():\n if v['type'] == 'bool':\n value = False\n elif v['type'] == 'int':\n value = 0\n else:\n value = ''\n output.update({k: value})\n return output","function_tokens":["def","init_features","(","type_",")",":","if","type_","==","'contact'",":","features","=","CONTACT","elif","type_","==","'device'",":","features","=","DEVICE","elif","type_","==","'message'",":","features","=","MESSAGE","else",":","raise","ValueError","(","'Invalid feature type %s'","%","type_",")","output","=","{","}","for","k",",","v","in","features",".","items","(",")",":","if","v","[","'type'","]","==","'bool'",":","value","=","False","elif","v","[","'type'","]","==","'int'",":","value","=","0","else",":","value","=","''","output",".","update","(","{","k",":","value","}",")","return","output"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/types.py#L121-L141"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/ingress_path.py","language":"python","identifier":"normalize_ssocket_infos","parameters":"(socket_info, cipher)","argument_list":"","return_statement":"return tls_version, cipher","docstring":"Normalize tls information from a Received header.","docstring_summary":"Normalize tls information from a Received header.","docstring_tokens":["Normalize","tls","information","from","a","Received","header","."],"function":"def normalize_ssocket_infos(socket_info, cipher):\n \"\"\"Normalize tls information from a Received header.\"\"\"\n if socket_info:\n tls_version = socket_info.replace('_', '.').lower()\n else:\n tls_version = ''\n return tls_version, cipher","function_tokens":["def","normalize_ssocket_infos","(","socket_info",",","cipher",")",":","if","socket_info",":","tls_version","=","socket_info",".","replace","(","'_'",",","'.'",")",".","lower","(",")","else",":","tls_version","=","''","return","tls_version",",","cipher"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/ingress_path.py#L19-L25"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/ingress_path.py","language":"python","identifier":"get_ingress_features","parameters":"(headers, internal_domains=None)","argument_list":"","return_statement":"return found_features","docstring":"Try to find information about ingress server that send this mail.","docstring_summary":"Try to find information about ingress server that send this mail.","docstring_tokens":["Try","to","find","information","about","ingress","server","that","send","this","mail","."],"function":"def get_ingress_features(headers, internal_domains=None):\n \"\"\"Try to find information about ingress server that send this mail.\"\"\"\n internal_domains = internal_domains if internal_domains else []\n\n def get_host(line):\n if ' ' not in line:\n return None\n parts = line.split(' ')\n return parts[0]\n\n def parse_ingress(header):\n \"\"\"Parse detected ingress header to find encryption infos.\"\"\"\n header = header.replace('\\n', '')\n # XXX to complete but MUST match with tls_version, cipher groups\n searches = ['.*using (\\S+) with cipher ([\\S-]+)']\n for regex in searches:\n search = re.compile(regex, re.MULTILINE)\n match = search.match(header)\n if match:\n return match.groups()\n return None\n\n found_features = {}\n\n # First step Search for 'paths' (from \/ by) information\n search = re.compile(r'^from (.*) by (.*)', re.MULTILINE + re.DOTALL)\n paths = []\n for r in headers:\n r = r.replace('\\n', '')\n match = search.match(r)\n if match:\n groups = match.groups()\n from_ = get_host(groups[0])\n by = get_host(groups[1])\n if from_ and by:\n paths.append((from_, by, groups))\n else:\n log.debug('Invalid from {} or by {} path in {}'.\n format(from_, by, r))\n else:\n if r.startswith('by'):\n # XXX first hop, to consider ?\n pass\n else:\n log.debug('Received header, does not match format {}'.\n format(r))\n\n # Second step: qualify path if internal and try to find the ingress one\n ingress = None\n internal_hops = 0\n for path in paths:\n is_internal = False\n for internal in internal_domains:\n if internal in path[0]:\n is_internal = True\n else:\n if internal in path[1]:\n ingress = path\n break\n if is_internal:\n internal_hops += 1\n\n # Qualify ingress connection\n if ingress:\n cnx_info = parse_ingress(ingress[2][0])\n if cnx_info and len(cnx_info) > 1:\n tls_version, cipher = normalize_ssocket_infos(cnx_info)\n found_features.update({'ingress_socket_version': tls_version,\n 'ingress_cipher': cipher})\n found_features.update({'ingress_server': ingress[0]})\n\n # Try to count external hops\n external_hops = len(paths) - internal_hops\n found_features.update({'nb_external_hops': external_hops})\n return found_features","function_tokens":["def","get_ingress_features","(","headers",",","internal_domains","=","None",")",":","internal_domains","=","internal_domains","if","internal_domains","else","[","]","def","get_host","(","line",")",":","if","' '","not","in","line",":","return","None","parts","=","line",".","split","(","' '",")","return","parts","[","0","]","def","parse_ingress","(","header",")",":","\"\"\"Parse detected ingress header to find encryption infos.\"\"\"","header","=","header",".","replace","(","'\\n'",",","''",")","# XXX to complete but MUST match with tls_version, cipher groups","searches","=","[","'.*using (\\S+) with cipher ([\\S-]+)'","]","for","regex","in","searches",":","search","=","re",".","compile","(","regex",",","re",".","MULTILINE",")","match","=","search",".","match","(","header",")","if","match",":","return","match",".","groups","(",")","return","None","found_features","=","{","}","# First step Search for 'paths' (from \/ by) information","search","=","re",".","compile","(","r'^from (.*) by (.*)'",",","re",".","MULTILINE","+","re",".","DOTALL",")","paths","=","[","]","for","r","in","headers",":","r","=","r",".","replace","(","'\\n'",",","''",")","match","=","search",".","match","(","r",")","if","match",":","groups","=","match",".","groups","(",")","from_","=","get_host","(","groups","[","0","]",")","by","=","get_host","(","groups","[","1","]",")","if","from_","and","by",":","paths",".","append","(","(","from_",",","by",",","groups",")",")","else",":","log",".","debug","(","'Invalid from {} or by {} path in {}'",".","format","(","from_",",","by",",","r",")",")","else",":","if","r",".","startswith","(","'by'",")",":","# XXX first hop, to consider ?","pass","else",":","log",".","debug","(","'Received header, does not match format {}'",".","format","(","r",")",")","# Second step: qualify path if internal and try to find the ingress one","ingress","=","None","internal_hops","=","0","for","path","in","paths",":","is_internal","=","False","for","internal","in","internal_domains",":","if","internal","in","path","[","0","]",":","is_internal","=","True","else",":","if","internal","in","path","[","1","]",":","ingress","=","path","break","if","is_internal",":","internal_hops","+=","1","# Qualify ingress connection","if","ingress",":","cnx_info","=","parse_ingress","(","ingress","[","2","]","[","0","]",")","if","cnx_info","and","len","(","cnx_info",")",">","1",":","tls_version",",","cipher","=","normalize_ssocket_infos","(","cnx_info",")","found_features",".","update","(","{","'ingress_socket_version'",":","tls_version",",","'ingress_cipher'",":","cipher","}",")","found_features",".","update","(","{","'ingress_server'",":","ingress","[","0","]","}",")","# Try to count external hops","external_hops","=","len","(","paths",")","-","internal_hops","found_features",".","update","(","{","'nb_external_hops'",":","external_hops","}",")","return","found_features"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/ingress_path.py#L28-L102"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/importance_level.py","language":"python","identifier":"get_importance_tags","parameters":"(tags)","argument_list":"","return_statement":"return max_value","docstring":"Get the max importance level from tags.","docstring_summary":"Get the max importance level from tags.","docstring_tokens":["Get","the","max","importance","level","from","tags","."],"function":"def get_importance_tags(tags):\n \"\"\"Get the max importance level from tags.\"\"\"\n max_value = 0\n for tag in tags:\n if getattr(tag, 'importance_level'):\n if tag.importance_level > max_value:\n max_value = tag.importance_level\n return max_value","function_tokens":["def","get_importance_tags","(","tags",")",":","max_value","=","0","for","tag","in","tags",":","if","getattr","(","tag",",","'importance_level'",")",":","if","tag",".","importance_level",">","max_value",":","max_value","=","tag",".","importance_level","return","max_value"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/importance_level.py#L28-L35"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/importance_level.py","language":"python","identifier":"compute_importance","parameters":"(user, message, features, participants)","argument_list":"","return_statement":"return round(min(MAX_VALUE, positive))","docstring":"Compute importance level for an inbound message.","docstring_summary":"Compute importance level for an inbound message.","docstring_tokens":["Compute","importance","level","for","an","inbound","message","."],"function":"def compute_importance(user, message, features, participants):\n \"\"\"Compute importance level for an inbound message.\"\"\"\n positive = 0\n negative = 0\n scores = []\n # Spam level\n if features.get('is_spam'):\n spam_score = features.get('spam_score', 0) \/ 100.0\n negative -= spam_score * abs(MIN_VALUE * SPAM_RATIO)\n scores.append(('spam_score', spam_score))\n # PI message\n if message.pi.context:\n context_score = message.pi.context \/ 100.0\n positive += context_score * PI_CX_RATIO * MAX_VALUE\n scores.append(('context_score', context_score))\n if message.pi.comportment:\n comportment_score = message.pi.comportment \/ 100.0\n positive += comportment_score * PI_CO_RATIO * MAX_VALUE\n scores.append(('comportment_score', comportment_score))\n # Tags\n if message.tags:\n tag_score = get_importance_tags(message.tags)\n positive += tag_score \/ MAX_TAG_SCORE * CONTEXT_RATIO\n scores.append(('tag_score', tag_score))\n\n # It's a reply ?\n if message.external_references:\n # XXX find if we know related messages to increment level\n positive += REPLY_VALUE\n scores.append(('reply_score', REPLY_VALUE))\n\n log.info('Importance scores: {0}'.format(scores))\n # Return the final value\n if negative:\n return round(max(MIN_VALUE, negative))\n return round(min(MAX_VALUE, positive))","function_tokens":["def","compute_importance","(","user",",","message",",","features",",","participants",")",":","positive","=","0","negative","=","0","scores","=","[","]","# Spam level","if","features",".","get","(","'is_spam'",")",":","spam_score","=","features",".","get","(","'spam_score'",",","0",")","\/","100.0","negative","-=","spam_score","*","abs","(","MIN_VALUE","*","SPAM_RATIO",")","scores",".","append","(","(","'spam_score'",",","spam_score",")",")","# PI message","if","message",".","pi",".","context",":","context_score","=","message",".","pi",".","context","\/","100.0","positive","+=","context_score","*","PI_CX_RATIO","*","MAX_VALUE","scores",".","append","(","(","'context_score'",",","context_score",")",")","if","message",".","pi",".","comportment",":","comportment_score","=","message",".","pi",".","comportment","\/","100.0","positive","+=","comportment_score","*","PI_CO_RATIO","*","MAX_VALUE","scores",".","append","(","(","'comportment_score'",",","comportment_score",")",")","# Tags","if","message",".","tags",":","tag_score","=","get_importance_tags","(","message",".","tags",")","positive","+=","tag_score","\/","MAX_TAG_SCORE","*","CONTEXT_RATIO","scores",".","append","(","(","'tag_score'",",","tag_score",")",")","# It's a reply ?","if","message",".","external_references",":","# XXX find if we know related messages to increment level","positive","+=","REPLY_VALUE","scores",".","append","(","(","'reply_score'",",","REPLY_VALUE",")",")","log",".","info","(","'Importance scores: {0}'",".","format","(","scores",")",")","# Return the final value","if","negative",":","return","round","(","max","(","MIN_VALUE",",","negative",")",")","return","round","(","min","(","MAX_VALUE",",","positive",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/importance_level.py#L38-L73"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/histogram.py","language":"python","identifier":"ParticipantHistogram.__init__","parameters":"(self, user, resolution='day')","argument_list":"","return_statement":"","docstring":"Instanciate a date histrogram for an user.","docstring_summary":"Instanciate a date histrogram for an user.","docstring_tokens":["Instanciate","a","date","histrogram","for","an","user","."],"function":"def __init__(self, user, resolution='day'):\n \"\"\"Instanciate a date histrogram for an user.\"\"\"\n self.esclient = get_index_connection()\n self.user = user\n self.resolution = resolution","function_tokens":["def","__init__","(","self",",","user",",","resolution","=","'day'",")",":","self",".","esclient","=","get_index_connection","(",")","self",".","user","=","user","self",".","resolution","=","resolution"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/histogram.py#L14-L18"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/histogram.py","language":"python","identifier":"ParticipantHistogram._format_results","parameters":"(self, results)","argument_list":"","return_statement":"return [(parse_date(x['key_as_string']),\n x['doc_count']) for x in results]","docstring":"Return a list of date, value tuples.","docstring_summary":"Return a list of date, value tuples.","docstring_tokens":["Return","a","list","of","date","value","tuples","."],"function":"def _format_results(self, results):\n \"\"\"Return a list of date, value tuples.\"\"\"\n return [(parse_date(x['key_as_string']),\n x['doc_count']) for x in results]","function_tokens":["def","_format_results","(","self",",","results",")",":","return","[","(","parse_date","(","x","[","'key_as_string'","]",")",",","x","[","'doc_count'","]",")","for","x","in","results","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/histogram.py#L20-L23"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/histogram.py","language":"python","identifier":"ParticipantHistogram.find_by_address","parameters":"(self, address)","argument_list":"","return_statement":"return self._do_query(address, term='participants.address')","docstring":"Build a date histogram with a participant address.","docstring_summary":"Build a date histogram with a participant address.","docstring_tokens":["Build","a","date","histogram","with","a","participant","address","."],"function":"def find_by_address(self, address):\n \"\"\"Build a date histogram with a participant address.\"\"\"\n return self._do_query(address, term='participants.address')","function_tokens":["def","find_by_address","(","self",",","address",")",":","return","self",".","_do_query","(","address",",","term","=","'participants.address'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/histogram.py#L41-L43"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/histogram.py","language":"python","identifier":"ParticipantHistogram.find_by_contact_id","parameters":"(self, contact_id)","argument_list":"","return_statement":"return self._do_query(contact_id, term='participants.contact_id')","docstring":"Build a date histogram with a know contact.","docstring_summary":"Build a date histogram with a know contact.","docstring_tokens":["Build","a","date","histogram","with","a","know","contact","."],"function":"def find_by_contact_id(self, contact_id):\n \"\"\"Build a date histogram with a know contact.\"\"\"\n return self._do_query(contact_id, term='participants.contact_id')","function_tokens":["def","find_by_contact_id","(","self",",","contact_id",")",":","return","self",".","_do_query","(","contact_id",",","term","=","'participants.contact_id'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/histogram.py#L45-L47"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/spam.py","language":"python","identifier":"extract_mail_spam_scores","parameters":"(mail)","argument_list":"","return_statement":"return scores","docstring":"Extract different spam scores from mail.","docstring_summary":"Extract different spam scores from mail.","docstring_tokens":["Extract","different","spam","scores","from","mail","."],"function":"def extract_mail_spam_scores(mail):\n \"\"\"Extract different spam scores from mail.\"\"\"\n scores = {}\n score = mail.get('X-Spam-Score', 0)\n if score:\n try:\n score = float(score)\n scores['score'] = score\n except TypeError:\n log.debug('Invalid type for X-Spam-Score value {}'.\n format(score))\n level = mail.get('X-Spam-Level', '')\n if '*' in level:\n # SpamAssassin style, level is *** notation, up to 25 *\n scores['level'] = level.count('*')\n status = mail.get('X-Spam-Status', '')\n if status:\n match = re.match('^(.*), score=(\\d.\\d).*', status)\n if match:\n flag = match.groups()[0]\n scores['status_score'] = float(match.groups()[1])\n if flag.lower().startswith('y'):\n scores['flag'] = True\n else:\n scores['flag'] = False\n\n flag = mail.get('X-Spam-Flag', '')\n if flag.lower().startswith('y'):\n scores['flag'] = True\n\n return scores","function_tokens":["def","extract_mail_spam_scores","(","mail",")",":","scores","=","{","}","score","=","mail",".","get","(","'X-Spam-Score'",",","0",")","if","score",":","try",":","score","=","float","(","score",")","scores","[","'score'","]","=","score","except","TypeError",":","log",".","debug","(","'Invalid type for X-Spam-Score value {}'",".","format","(","score",")",")","level","=","mail",".","get","(","'X-Spam-Level'",",","''",")","if","'*'","in","level",":","# SpamAssassin style, level is *** notation, up to 25 *","scores","[","'level'","]","=","level",".","count","(","'*'",")","status","=","mail",".","get","(","'X-Spam-Status'",",","''",")","if","status",":","match","=","re",".","match","(","'^(.*), score=(\\d.\\d).*'",",","status",")","if","match",":","flag","=","match",".","groups","(",")","[","0","]","scores","[","'status_score'","]","=","float","(","match",".","groups","(",")","[","1","]",")","if","flag",".","lower","(",")",".","startswith","(","'y'",")",":","scores","[","'flag'","]","=","True","else",":","scores","[","'flag'","]","=","False","flag","=","mail",".","get","(","'X-Spam-Flag'",",","''",")","if","flag",".","lower","(",")",".","startswith","(","'y'",")",":","scores","[","'flag'","]","=","True","return","scores"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/spam.py#L11-L41"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/spam.py","language":"python","identifier":"SpamScorer.__init__","parameters":"(self, mail)","argument_list":"","return_statement":"","docstring":"Compute a global score using multiple methods and mail.","docstring_summary":"Compute a global score using multiple methods and mail.","docstring_tokens":["Compute","a","global","score","using","multiple","methods","and","mail","."],"function":"def __init__(self, mail):\n \"\"\"Compute a global score using multiple methods and mail.\"\"\"\n self.scores = extract_mail_spam_scores(mail)\n log.debug('Found spam scores {s}'.format(s=self.scores))\n if 'level' in self.scores:\n self.method = 'level'\n self.score = min(100.0, self.scores['level'] * 4.0)\n if 'score' in self.scores:\n self.method = 'score'\n self.score = min(0.0, self.scores['score']) * 10.0\n if 'status_score' in self.scores:\n self.method = 'status'\n if self.scores['status_score'] < 2.0:\n self.score = 0.0\n else:\n tmp_score = min(100.0, self.scores['status_score'] * 10)\n self.score = max(0.0, tmp_score)\n if self.scores.get('flag'):\n self.is_spam = True\n self.source_flag = self.scores['flag']\n if not self.is_spam and self.score >= 50:\n self.is_spam = True\n if self.score < 0:\n self.score = 0.0\n if self.score > 100:\n self.score = 100.0","function_tokens":["def","__init__","(","self",",","mail",")",":","self",".","scores","=","extract_mail_spam_scores","(","mail",")","log",".","debug","(","'Found spam scores {s}'",".","format","(","s","=","self",".","scores",")",")","if","'level'","in","self",".","scores",":","self",".","method","=","'level'","self",".","score","=","min","(","100.0",",","self",".","scores","[","'level'","]","*","4.0",")","if","'score'","in","self",".","scores",":","self",".","method","=","'score'","self",".","score","=","min","(","0.0",",","self",".","scores","[","'score'","]",")","*","10.0","if","'status_score'","in","self",".","scores",":","self",".","method","=","'status'","if","self",".","scores","[","'status_score'","]","<","2.0",":","self",".","score","=","0.0","else",":","tmp_score","=","min","(","100.0",",","self",".","scores","[","'status_score'","]","*","10",")","self",".","score","=","max","(","0.0",",","tmp_score",")","if","self",".","scores",".","get","(","'flag'",")",":","self",".","is_spam","=","True","self",".","source_flag","=","self",".","scores","[","'flag'","]","if","not","self",".","is_spam","and","self",".","score",">=","50",":","self",".","is_spam","=","True","if","self",".","score","<","0",":","self",".","score","=","0.0","if","self",".","score",">","100",":","self",".","score","=","100.0"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/features\/helpers\/spam.py#L52-L77"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/device.py","language":"python","identifier":"NewDeviceQualifier.__init__","parameters":"(self, user)","argument_list":"","return_statement":"","docstring":"Create a new instance of an user device qualifier.","docstring_summary":"Create a new instance of an user device qualifier.","docstring_tokens":["Create","a","new","instance","of","an","user","device","qualifier","."],"function":"def __init__(self, user):\n \"\"\"Create a new instance of an user device qualifier.\"\"\"\n self.user = user\n self.conf = Configuration('global').configuration","function_tokens":["def","__init__","(","self",",","user",")",":","self",".","user","=","user","self",".","conf","=","Configuration","(","'global'",")",".","configuration"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/device.py#L17-L20"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/device.py","language":"python","identifier":"NewDeviceQualifier.process","parameters":"(self, device)","argument_list":"","return_statement":"return True","docstring":"Process a device to qualify it.","docstring_summary":"Process a device to qualify it.","docstring_tokens":["Process","a","device","to","qualify","it","."],"function":"def process(self, device):\n \"\"\"Process a device to qualify it.\"\"\"\n extractor = DeviceFeature(self.user, self.conf)\n pi, features = extractor.process(device)\n device.privacy_features = marshal_features(features)\n device.pi = pi\n return True","function_tokens":["def","process","(","self",",","device",")",":","extractor","=","DeviceFeature","(","self",".","user",",","self",".","conf",")","pi",",","features","=","extractor",".","process","(","device",")","device",".","privacy_features","=","marshal_features","(","features",")","device",".","pi","=","pi","return","True"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/device.py#L22-L28"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py","language":"python","identifier":"BaseQualifier.__init__","parameters":"(self, user, identity)","argument_list":"","return_statement":"","docstring":"Create a new instance of an user message qualifier.","docstring_summary":"Create a new instance of an user message qualifier.","docstring_tokens":["Create","a","new","instance","of","an","user","message","qualifier","."],"function":"def __init__(self, user, identity):\n \"\"\"Create a new instance of an user message qualifier.\"\"\"\n self.user = user\n self.identity = identity","function_tokens":["def","__init__","(","self",",","user",",","identity",")",":","self",".","user","=","user","self",".","identity","=","identity"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py#L18-L21"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py","language":"python","identifier":"BaseQualifier._get_tags","parameters":"(self, message)","argument_list":"","return_statement":"","docstring":"Get tags for a message.","docstring_summary":"Get tags for a message.","docstring_tokens":["Get","tags","for","a","message","."],"function":"def _get_tags(self, message):\n \"\"\"Get tags for a message.\"\"\"\n tags = []\n if message.privacy_features.get('is_internal', False):\n # XXX do not hardcode the wanted tag\n internal_tag = [x for x in self.user.tags if x.name == 'internal']\n if internal_tag:\n tags.append(internal_tag[0].name)\n message.tags = tags","function_tokens":["def","_get_tags","(","self",",","message",")",":","tags","=","[","]","if","message",".","privacy_features",".","get","(","'is_internal'",",","False",")",":","# XXX do not hardcode the wanted tag","internal_tag","=","[","x","for","x","in","self",".","user",".","tags","if","x",".","name","==","'internal'","]","if","internal_tag",":","tags",".","append","(","internal_tag","[","0","]",".","name",")","message",".","tags","=","tags"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py#L23-L31"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py","language":"python","identifier":"BaseQualifier.lookup","parameters":"(self, sequence)","argument_list":"","return_statement":"return None","docstring":"Process lookup sequence to find discussion to associate.","docstring_summary":"Process lookup sequence to find discussion to associate.","docstring_tokens":["Process","lookup","sequence","to","find","discussion","to","associate","."],"function":"def lookup(self, sequence):\n \"\"\"Process lookup sequence to find discussion to associate.\"\"\"\n log.debug('Lookup sequence %r' % sequence)\n for prop in sequence:\n try:\n kls = self._lookups[prop[0]]\n log.debug('Will lookup %s with value %s' %\n (prop[0], prop[1]))\n return kls.get(self.user, prop[1])\n except NotFound:\n log.debug('Lookup type %s with value %s failed' %\n (prop[0], prop[1]))\n\n return None","function_tokens":["def","lookup","(","self",",","sequence",")",":","log",".","debug","(","'Lookup sequence %r'","%","sequence",")","for","prop","in","sequence",":","try",":","kls","=","self",".","_lookups","[","prop","[","0","]","]","log",".","debug","(","'Will lookup %s with value %s'","%","(","prop","[","0","]",",","prop","[","1","]",")",")","return","kls",".","get","(","self",".","user",",","prop","[","1","]",")","except","NotFound",":","log",".","debug","(","'Lookup type %s with value %s failed'","%","(","prop","[","0","]",",","prop","[","1","]",")",")","return","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py#L33-L46"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py","language":"python","identifier":"BaseQualifier.create_lookups","parameters":"(self, sequence, message)","argument_list":"","return_statement":"","docstring":"Initialize lookup classes for the related sequence.","docstring_summary":"Initialize lookup classes for the related sequence.","docstring_tokens":["Initialize","lookup","classes","for","the","related","sequence","."],"function":"def create_lookups(self, sequence, message):\n \"\"\"Initialize lookup classes for the related sequence.\"\"\"\n for prop in sequence:\n kls = self._lookups[prop[0]]\n params = {\n kls._pkey_name: prop[1],\n 'discussion_id': message.discussion_id\n }\n lookup = kls.create(self.user, **params)\n log.info('Create lookup %r' % lookup)","function_tokens":["def","create_lookups","(","self",",","sequence",",","message",")",":","for","prop","in","sequence",":","kls","=","self",".","_lookups","[","prop","[","0","]","]","params","=","{","kls",".","_pkey_name",":","prop","[","1","]",",","'discussion_id'",":","message",".","discussion_id","}","lookup","=","kls",".","create","(","self",".","user",",","*","*","params",")","log",".","info","(","'Create lookup %r'","%","lookup",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py#L48-L57"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py","language":"python","identifier":"BaseQualifier.get_participant","parameters":"(self, message, participant)","argument_list":"","return_statement":"return p, c","docstring":"Try to find a related contact and return a Participant instance.","docstring_summary":"Try to find a related contact and return a Participant instance.","docstring_tokens":["Try","to","find","a","related","contact","and","return","a","Participant","instance","."],"function":"def get_participant(self, message, participant):\n \"\"\"Try to find a related contact and return a Participant instance.\"\"\"\n p = Participant()\n p.address = participant.address.lower()\n p.type = participant.type\n p.label = participant.label\n p.protocol = message.message_protocol\n log.debug('Will lookup contact {} for user {}'.\n format(participant.address, self.user.user_id))\n try:\n c = Contact.lookup(self.user, participant.address)\n except Exception as exc:\n log.error(\"Contact lookup failed in get_participant for participant {} : {}\".format(vars(participant), exc))\n raise exc\n if c:\n p.contact_ids = [c.contact_id]\n else:\n if p.address == self.identity.identifier and self.user.contact_id:\n p.contact_ids = [self.user.contact_id]\n return p, c","function_tokens":["def","get_participant","(","self",",","message",",","participant",")",":","p","=","Participant","(",")","p",".","address","=","participant",".","address",".","lower","(",")","p",".","type","=","participant",".","type","p",".","label","=","participant",".","label","p",".","protocol","=","message",".","message_protocol","log",".","debug","(","'Will lookup contact {} for user {}'",".","format","(","participant",".","address",",","self",".","user",".","user_id",")",")","try",":","c","=","Contact",".","lookup","(","self",".","user",",","participant",".","address",")","except","Exception","as","exc",":","log",".","error","(","\"Contact lookup failed in get_participant for participant {} : {}\"",".","format","(","vars","(","participant",")",",","exc",")",")","raise","exc","if","c",":","p",".","contact_ids","=","[","c",".","contact_id","]","else",":","if","p",".","address","==","self",".","identity",".","identifier","and","self",".","user",".","contact_id",":","p",".","contact_ids","=","[","self",".","user",".","contact_id","]","return","p",",","c"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/base.py#L59-L78"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/mail.py","language":"python","identifier":"UserMessageQualifier.lookup_discussion_sequence","parameters":"(self, mail, message)","argument_list":"","return_statement":"return seq, seq[0][1]","docstring":"Return list of lookups (type, value) from a mail message\n and the first lookup'hash from that list","docstring_summary":"Return list of lookups (type, value) from a mail message\n and the first lookup'hash from that list","docstring_tokens":["Return","list","of","lookups","(","type","value",")","from","a","mail","message","and","the","first","lookup","hash","from","that","list"],"function":"def lookup_discussion_sequence(self, mail, message):\n \"\"\"\n Return list of lookups (type, value) from a mail message\n and the first lookup'hash from that list\n \"\"\"\n seq = []\n\n # lists lookup first\n lists = []\n for list_id in mail.extra_parameters.get('lists', []):\n lists.append(list_id)\n if len(lists) > 0:\n # list_ids are considered `participants`\n # build uris' hash and upsert lookup tables\n participants = []\n for list_id in lists:\n participant = Participant()\n participant.address = list_id.lower()\n participant.protocol = 'email'\n participant.type = 'list-id'\n participants.append(participant)\n discuss = Discussion(self.user)\n discuss.upsert_lookups_for_participants(participants)\n # add list-id as a participant to the message\n message.participants.append(participant)\n hash = hash_participants_uri(participants)\n seq.append(('list', hash['hash']))\n\n # then participants\n seq.append(('hash', message.hash_participants))\n\n # try to link message to external thread's root message-id\n # if len(message.external_references[\"ancestors_ids\"]) > 0:\n # seq.append((\"thread\",\n # message.external_references[\"ancestors_ids\"][0]))\n # elif message.external_references[\"parent_id\"]:\n # seq.append((\"thread\", message.external_references[\"parent_id\"]))\n # elif message.external_references[\"message_id\"]:\n # seq.append((\"thread\", message.external_references[\"message_id\"]))\n\n return seq, seq[0][1]","function_tokens":["def","lookup_discussion_sequence","(","self",",","mail",",","message",")",":","seq","=","[","]","# lists lookup first","lists","=","[","]","for","list_id","in","mail",".","extra_parameters",".","get","(","'lists'",",","[","]",")",":","lists",".","append","(","list_id",")","if","len","(","lists",")",">","0",":","# list_ids are considered `participants`","# build uris' hash and upsert lookup tables","participants","=","[","]","for","list_id","in","lists",":","participant","=","Participant","(",")","participant",".","address","=","list_id",".","lower","(",")","participant",".","protocol","=","'email'","participant",".","type","=","'list-id'","participants",".","append","(","participant",")","discuss","=","Discussion","(","self",".","user",")","discuss",".","upsert_lookups_for_participants","(","participants",")","# add list-id as a participant to the message","message",".","participants",".","append","(","participant",")","hash","=","hash_participants_uri","(","participants",")","seq",".","append","(","(","'list'",",","hash","[","'hash'","]",")",")","# then participants","seq",".","append","(","(","'hash'",",","message",".","hash_participants",")",")","# try to link message to external thread's root message-id","# if len(message.external_references[\"ancestors_ids\"]) > 0:","# seq.append((\"thread\",","# message.external_references[\"ancestors_ids\"][0]))","# elif message.external_references[\"parent_id\"]:","# seq.append((\"thread\", message.external_references[\"parent_id\"]))","# elif message.external_references[\"message_id\"]:","# seq.append((\"thread\", message.external_references[\"message_id\"]))","return","seq",",","seq","[","0","]","[","1","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/mail.py#L40-L80"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/mail.py","language":"python","identifier":"UserMessageQualifier.process_inbound","parameters":"(self, raw)","argument_list":"","return_statement":"return new_message","docstring":"Process inbound message.\n\n @param raw: a RawMessage object\n @rtype: NewMessage","docstring_summary":"Process inbound message.","docstring_tokens":["Process","inbound","message","."],"function":"def process_inbound(self, raw):\n \"\"\"Process inbound message.\n\n @param raw: a RawMessage object\n @rtype: NewMessage\n \"\"\"\n email = MailMessage(raw.raw_data)\n new_message = NewInboundMessage()\n new_message.raw_msg_id = raw.raw_msg_id\n new_message.subject = email.subject\n new_message.body_html = email.body_html\n new_message.body_plain = email.body_plain\n new_message.date = email.date\n new_message.size = email.size\n new_message.protocol = email.message_protocol\n new_message.is_unread = True\n new_message.is_draft = False\n new_message.is_answered = False\n new_message.is_received = True\n new_message.importance_level = 0 # XXX tofix on parser\n new_message.external_references = email.external_references\n\n participants = []\n for p in email.participants:\n p.address = p.address.lower()\n try:\n participant, contact = self.get_participant(email, p)\n new_message.participants.append(participant)\n participants.append((participant, contact))\n except Exception as exc:\n log.error(\"process_inbound failed to lookup participant for email {} : {}\".format(vars(email), exc))\n raise exc\n\n\n if not participants:\n raise Exception(\"no participant found in raw email {}\".format(\n raw.raw_msg_id))\n\n for a in email.attachments:\n attachment = Attachment()\n attachment.content_type = a.content_type\n attachment.file_name = a.filename\n attachment.size = a.size\n attachment.mime_boundary = a.mime_boundary\n if hasattr(a, \"is_inline\"):\n attachment.is_inline = a.is_inline\n new_message.attachments.append(attachment)\n\n # Compute PI !!\n conf = Configuration('global').configuration\n extractor = InboundMailFeature(email, conf)\n extractor.process(self.user, new_message, participants)\n\n # compute user tags\n self._get_tags(new_message)\n # embed external flags if any\n new_message.ext_tags = email.external_flags\n if new_message.tags:\n log.debug('Resolved tags {}'.format(new_message.tags))\n\n # build discussion_id from lookup_sequence\n lookup_sequence, discussion_id = self.lookup_discussion_sequence(email,\n new_message)\n log.debug('Lookup with sequence {} gives {}'.format(lookup_sequence,\n discussion_id))\n new_message.discussion_id = discussion_id\n\n # upsert lookup tables\n discuss = Discussion(self.user)\n discuss.upsert_lookups_for_participants(new_message.participants)\n # Format features\n new_message.privacy_features = \\\n marshal_features(new_message.privacy_features)\n try:\n new_message.validate()\n except Exception as exc:\n log.error(\n \"validation failed with error : \u00ab {} \u00bb \\\n for new_message {}[dump : {}]\".format(\n exc, new_message, vars(new_message)))\n raise exc\n\n return new_message","function_tokens":["def","process_inbound","(","self",",","raw",")",":","email","=","MailMessage","(","raw",".","raw_data",")","new_message","=","NewInboundMessage","(",")","new_message",".","raw_msg_id","=","raw",".","raw_msg_id","new_message",".","subject","=","email",".","subject","new_message",".","body_html","=","email",".","body_html","new_message",".","body_plain","=","email",".","body_plain","new_message",".","date","=","email",".","date","new_message",".","size","=","email",".","size","new_message",".","protocol","=","email",".","message_protocol","new_message",".","is_unread","=","True","new_message",".","is_draft","=","False","new_message",".","is_answered","=","False","new_message",".","is_received","=","True","new_message",".","importance_level","=","0","# XXX tofix on parser","new_message",".","external_references","=","email",".","external_references","participants","=","[","]","for","p","in","email",".","participants",":","p",".","address","=","p",".","address",".","lower","(",")","try",":","participant",",","contact","=","self",".","get_participant","(","email",",","p",")","new_message",".","participants",".","append","(","participant",")","participants",".","append","(","(","participant",",","contact",")",")","except","Exception","as","exc",":","log",".","error","(","\"process_inbound failed to lookup participant for email {} : {}\"",".","format","(","vars","(","email",")",",","exc",")",")","raise","exc","if","not","participants",":","raise","Exception","(","\"no participant found in raw email {}\"",".","format","(","raw",".","raw_msg_id",")",")","for","a","in","email",".","attachments",":","attachment","=","Attachment","(",")","attachment",".","content_type","=","a",".","content_type","attachment",".","file_name","=","a",".","filename","attachment",".","size","=","a",".","size","attachment",".","mime_boundary","=","a",".","mime_boundary","if","hasattr","(","a",",","\"is_inline\"",")",":","attachment",".","is_inline","=","a",".","is_inline","new_message",".","attachments",".","append","(","attachment",")","# Compute PI !!","conf","=","Configuration","(","'global'",")",".","configuration","extractor","=","InboundMailFeature","(","email",",","conf",")","extractor",".","process","(","self",".","user",",","new_message",",","participants",")","# compute user tags","self",".","_get_tags","(","new_message",")","# embed external flags if any","new_message",".","ext_tags","=","email",".","external_flags","if","new_message",".","tags",":","log",".","debug","(","'Resolved tags {}'",".","format","(","new_message",".","tags",")",")","# build discussion_id from lookup_sequence","lookup_sequence",",","discussion_id","=","self",".","lookup_discussion_sequence","(","email",",","new_message",")","log",".","debug","(","'Lookup with sequence {} gives {}'",".","format","(","lookup_sequence",",","discussion_id",")",")","new_message",".","discussion_id","=","discussion_id","# upsert lookup tables","discuss","=","Discussion","(","self",".","user",")","discuss",".","upsert_lookups_for_participants","(","new_message",".","participants",")","# Format features","new_message",".","privacy_features","=","marshal_features","(","new_message",".","privacy_features",")","try",":","new_message",".","validate","(",")","except","Exception","as","exc",":","log",".","error","(","\"validation failed with error : \u00ab {} \u00bb \\\n for new_message {}[dump : {}]\"",".","format","(","exc",",","new_message",",","vars","(","new_message",")",")",")","raise","exc","return","new_message"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/mail.py#L82-L164"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/twitter.py","language":"python","identifier":"UserTwitterQualifier.lookup_discussion_sequence","parameters":"(self, message, *args, **kwargs)","argument_list":"","return_statement":"return seq, seq[0][1]","docstring":"Return list of lookup type, value from a tweet.","docstring_summary":"Return list of lookup type, value from a tweet.","docstring_tokens":["Return","list","of","lookup","type","value","from","a","tweet","."],"function":"def lookup_discussion_sequence(self, message, *args, **kwargs):\n \"\"\"Return list of lookup type, value from a tweet.\"\"\"\n seq = list()\n\n participants = message.hash_participants\n seq.append(('hash', participants))\n\n return seq, seq[0][1]","function_tokens":["def","lookup_discussion_sequence","(","self",",","message",",","*","args",",","*","*","kwargs",")",":","seq","=","list","(",")","participants","=","message",".","hash_participants","seq",".","append","(","(","'hash'",",","participants",")",")","return","seq",",","seq","[","0","]","[","1","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/twitter.py#L25-L32"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/twitter.py","language":"python","identifier":"UserTwitterQualifier.process_inbound","parameters":"(self, raw)","argument_list":"","return_statement":"return new_message","docstring":"Process inbound message.\n\n @param raw: a RawMessage object\n which should be a json conforming to\n https:\/\/developer.twitter.com\/en\/docs\/direct-messages\/\\\n sending-and-receiving\/guides\/message-create-object\n @rtype: NewMessage","docstring_summary":"Process inbound message.","docstring_tokens":["Process","inbound","message","."],"function":"def process_inbound(self, raw):\n \"\"\"\n Process inbound message.\n\n @param raw: a RawMessage object\n which should be a json conforming to\n https:\/\/developer.twitter.com\/en\/docs\/direct-messages\/\\\n sending-and-receiving\/guides\/message-create-object\n @rtype: NewMessage\n \"\"\"\n tweet = TwitterDM(raw.raw_data)\n new_message = NewInboundMessage()\n new_message.raw_msg_id = raw.raw_msg_id\n new_message.body_plain = tweet.body_plain\n new_message.date = tweet.date\n new_message.protocol = tweet.protocol\n new_message.is_unread = True\n new_message.is_draft = False\n new_message.is_answered = False\n new_message.is_received = True\n new_message.importance_level = 0 # XXX tofix on parser\n new_message.external_references = tweet.external_references\n\n participants = []\n for p in tweet.participants:\n p.address = clean_twitter_address(p.address)\n participant, contact = self.get_participant(tweet, p)\n new_message.participants.append(participant)\n participants.append((participant, contact))\n\n if not participants:\n raise Exception(\"no participant found in raw tweet {}\".format(\n raw.raw_msg_id))\n\n # Compute PI !!\n # TODO\n\n # compute tags\n self._get_tags(new_message)\n if new_message.tags:\n log.debug('Resolved tags {}'.format(new_message.tags))\n\n # build discussion_id from lookup_sequence\n lookup_sequence, discussion_id = self.lookup_discussion_sequence(\n new_message)\n log.debug('Lookup with sequence {} gives {}'.format(lookup_sequence,\n discussion_id))\n new_message.discussion_id = discussion_id\n\n # upsert lookup tables\n discuss = Discussion(self.user)\n discuss.upsert_lookups_for_participants(new_message.participants)\n # Format features\n new_message.privacy_features = \\\n marshal_features(new_message.privacy_features)\n try:\n new_message.validate()\n except Exception as exc:\n log.error(\n \"validation failed with error : \u00ab {} \u00bb \\\n for new_message {}[dump : {}]\".format(\n exc, new_message, vars(new_message)))\n raise exc\n\n return new_message","function_tokens":["def","process_inbound","(","self",",","raw",")",":","tweet","=","TwitterDM","(","raw",".","raw_data",")","new_message","=","NewInboundMessage","(",")","new_message",".","raw_msg_id","=","raw",".","raw_msg_id","new_message",".","body_plain","=","tweet",".","body_plain","new_message",".","date","=","tweet",".","date","new_message",".","protocol","=","tweet",".","protocol","new_message",".","is_unread","=","True","new_message",".","is_draft","=","False","new_message",".","is_answered","=","False","new_message",".","is_received","=","True","new_message",".","importance_level","=","0","# XXX tofix on parser","new_message",".","external_references","=","tweet",".","external_references","participants","=","[","]","for","p","in","tweet",".","participants",":","p",".","address","=","clean_twitter_address","(","p",".","address",")","participant",",","contact","=","self",".","get_participant","(","tweet",",","p",")","new_message",".","participants",".","append","(","participant",")","participants",".","append","(","(","participant",",","contact",")",")","if","not","participants",":","raise","Exception","(","\"no participant found in raw tweet {}\"",".","format","(","raw",".","raw_msg_id",")",")","# Compute PI !!","# TODO","# compute tags","self",".","_get_tags","(","new_message",")","if","new_message",".","tags",":","log",".","debug","(","'Resolved tags {}'",".","format","(","new_message",".","tags",")",")","# build discussion_id from lookup_sequence","lookup_sequence",",","discussion_id","=","self",".","lookup_discussion_sequence","(","new_message",")","log",".","debug","(","'Lookup with sequence {} gives {}'",".","format","(","lookup_sequence",",","discussion_id",")",")","new_message",".","discussion_id","=","discussion_id","# upsert lookup tables","discuss","=","Discussion","(","self",".","user",")","discuss",".","upsert_lookups_for_participants","(","new_message",".","participants",")","# Format features","new_message",".","privacy_features","=","marshal_features","(","new_message",".","privacy_features",")","try",":","new_message",".","validate","(",")","except","Exception","as","exc",":","log",".","error","(","\"validation failed with error : \u00ab {} \u00bb \\\n for new_message {}[dump : {}]\"",".","format","(","exc",",","new_message",",","vars","(","new_message",")",")",")","raise","exc","return","new_message"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/twitter.py#L34-L98"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/mastodon.py","language":"python","identifier":"UserMastodonQualifier.lookup_discussion_sequence","parameters":"(self, message, *args, **kwargs)","argument_list":"","return_statement":"return seq, seq[0][1]","docstring":"Return list of lookup type, value from a tweet.","docstring_summary":"Return list of lookup type, value from a tweet.","docstring_tokens":["Return","list","of","lookup","type","value","from","a","tweet","."],"function":"def lookup_discussion_sequence(self, message, *args, **kwargs):\n \"\"\"Return list of lookup type, value from a tweet.\"\"\"\n seq = list()\n\n participants = message.hash_participants\n seq.append(('hash', participants))\n\n return seq, seq[0][1]","function_tokens":["def","lookup_discussion_sequence","(","self",",","message",",","*","args",",","*","*","kwargs",")",":","seq","=","list","(",")","participants","=","message",".","hash_participants","seq",".","append","(","(","'hash'",",","participants",")",")","return","seq",",","seq","[","0","]","[","1","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/mastodon.py#L25-L32"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/mastodon.py","language":"python","identifier":"UserMastodonQualifier.process_inbound","parameters":"(self, raw)","argument_list":"","return_statement":"return new_message","docstring":"Process inbound message.\n\n @param raw: a RawMessage object\n which should be a json conforming to\n https:\/\/docs.joinmastodon.org\/api\/entities\/#status\n @rtype: NewMessage","docstring_summary":"Process inbound message.","docstring_tokens":["Process","inbound","message","."],"function":"def process_inbound(self, raw):\n \"\"\"\n Process inbound message.\n\n @param raw: a RawMessage object\n which should be a json conforming to\n https:\/\/docs.joinmastodon.org\/api\/entities\/#status\n @rtype: NewMessage\n \"\"\"\n toot = MastodonStatus(raw.raw_data)\n new_message = NewInboundMessage()\n new_message.raw_msg_id = raw.raw_msg_id\n new_message.body_html = toot.body_html\n new_message.date = toot.date\n new_message.protocol = toot.protocol\n new_message.is_unread = True\n new_message.is_draft = False\n new_message.is_answered = False\n new_message.is_received = True\n new_message.importance_level = 0 # XXX tofix on parser\n new_message.external_references = toot.external_references\n\n participants = []\n for p in toot.participants:\n p.address = p.address\n participant, contact = self.get_participant(toot, p)\n new_message.participants.append(participant)\n participants.append((participant, contact))\n\n if not participants:\n raise Exception(\"no participant found in raw tweet {}\".format(\n raw.raw_msg_id))\n\n # Compute PI !!\n # TODO\n\n # compute tags\n self._get_tags(new_message)\n if new_message.tags:\n log.debug('Resolved tags {}'.format(new_message.tags))\n\n # build discussion_id from lookup_sequence\n lookup_sequence, discussion_id = self.lookup_discussion_sequence(\n new_message)\n log.debug('Lookup with sequence {} gives {}'.format(lookup_sequence,\n discussion_id))\n new_message.discussion_id = discussion_id\n\n # upsert lookup tables\n discuss = Discussion(self.user)\n discuss.upsert_lookups_for_participants(new_message.participants)\n # Format features\n new_message.privacy_features = \\\n marshal_features(new_message.privacy_features)\n try:\n new_message.validate()\n except Exception as exc:\n log.error(\n \"validation failed with error : \u00ab {} \u00bb \\\n for new_message {}[dump : {}]\".format(\n exc, new_message, vars(new_message)))\n raise exc\n\n return new_message","function_tokens":["def","process_inbound","(","self",",","raw",")",":","toot","=","MastodonStatus","(","raw",".","raw_data",")","new_message","=","NewInboundMessage","(",")","new_message",".","raw_msg_id","=","raw",".","raw_msg_id","new_message",".","body_html","=","toot",".","body_html","new_message",".","date","=","toot",".","date","new_message",".","protocol","=","toot",".","protocol","new_message",".","is_unread","=","True","new_message",".","is_draft","=","False","new_message",".","is_answered","=","False","new_message",".","is_received","=","True","new_message",".","importance_level","=","0","# XXX tofix on parser","new_message",".","external_references","=","toot",".","external_references","participants","=","[","]","for","p","in","toot",".","participants",":","p",".","address","=","p",".","address","participant",",","contact","=","self",".","get_participant","(","toot",",","p",")","new_message",".","participants",".","append","(","participant",")","participants",".","append","(","(","participant",",","contact",")",")","if","not","participants",":","raise","Exception","(","\"no participant found in raw tweet {}\"",".","format","(","raw",".","raw_msg_id",")",")","# Compute PI !!","# TODO","# compute tags","self",".","_get_tags","(","new_message",")","if","new_message",".","tags",":","log",".","debug","(","'Resolved tags {}'",".","format","(","new_message",".","tags",")",")","# build discussion_id from lookup_sequence","lookup_sequence",",","discussion_id","=","self",".","lookup_discussion_sequence","(","new_message",")","log",".","debug","(","'Lookup with sequence {} gives {}'",".","format","(","lookup_sequence",",","discussion_id",")",")","new_message",".","discussion_id","=","discussion_id","# upsert lookup tables","discuss","=","Discussion","(","self",".","user",")","discuss",".","upsert_lookups_for_participants","(","new_message",".","participants",")","# Format features","new_message",".","privacy_features","=","marshal_features","(","new_message",".","privacy_features",")","try",":","new_message",".","validate","(",")","except","Exception","as","exc",":","log",".","error","(","\"validation failed with error : \u00ab {} \u00bb \\\n for new_message {}[dump : {}]\"",".","format","(","exc",",","new_message",",","vars","(","new_message",")",")",")","raise","exc","return","new_message"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/mastodon.py#L34-L97"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/contact.py","language":"python","identifier":"ContactMessageQualifier.process","parameters":"(self, contact)","argument_list":"","return_statement":"return False","docstring":"Qualification for a contact.","docstring_summary":"Qualification for a contact.","docstring_tokens":["Qualification","for","a","contact","."],"function":"def process(self, contact):\n \"\"\"Qualification for a contact.\"\"\"\n extractor = ContactFeature(self.user)\n pi, features = extractor.process(contact)\n # XXX for the moment apply features and pi\n if not contact.pi:\n current_pi = None\n else:\n current_pi = contact.pi.marshall_dict()\n new_pi = pi.serialize()\n new_pi.pop('date_update')\n current = {}\n patch = {}\n if pi.technic or pi.context or pi.comportment:\n current.update({'pi': current_pi})\n patch.update({'pi': new_pi})\n if contact.privacy_features:\n current_features = contact.privacy_features\n else:\n current_features = {}\n if current_features != features:\n current.update({'privacy_features': contact.privacy_features})\n patch.update({'privacy_features': features})\n if current and patch:\n patch.update({'current_state': current})\n log.info('Will patch with {0}'.format(patch))\n contact.apply_patch(patch, db=True)\n return True\n log.debug('No confidentiality update for contact')\n return False","function_tokens":["def","process","(","self",",","contact",")",":","extractor","=","ContactFeature","(","self",".","user",")","pi",",","features","=","extractor",".","process","(","contact",")","# XXX for the moment apply features and pi","if","not","contact",".","pi",":","current_pi","=","None","else",":","current_pi","=","contact",".","pi",".","marshall_dict","(",")","new_pi","=","pi",".","serialize","(",")","new_pi",".","pop","(","'date_update'",")","current","=","{","}","patch","=","{","}","if","pi",".","technic","or","pi",".","context","or","pi",".","comportment",":","current",".","update","(","{","'pi'",":","current_pi","}",")","patch",".","update","(","{","'pi'",":","new_pi","}",")","if","contact",".","privacy_features",":","current_features","=","contact",".","privacy_features","else",":","current_features","=","{","}","if","current_features","!=","features",":","current",".","update","(","{","'privacy_features'",":","contact",".","privacy_features","}",")","patch",".","update","(","{","'privacy_features'",":","features","}",")","if","current","and","patch",":","patch",".","update","(","{","'current_state'",":","current","}",")","log",".","info","(","'Will patch with {0}'",".","format","(","patch",")",")","contact",".","apply_patch","(","patch",",","db","=","True",")","return","True","log",".","debug","(","'No confidentiality update for contact'",")","return","False"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/contact.py#L20-L49"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/contact.py","language":"python","identifier":"ContactEmailQualifier.__init__","parameters":"(self, user)","argument_list":"","return_statement":"","docstring":"Create a new instance of an contact email qualifier.","docstring_summary":"Create a new instance of an contact email qualifier.","docstring_tokens":["Create","a","new","instance","of","an","contact","email","qualifier","."],"function":"def __init__(self, user):\n \"\"\"Create a new instance of an contact email qualifier.\"\"\"\n self.user = user\n conf = Configuration('global').configuration\n self.key_disco = PublicKeyDiscoverer(conf)","function_tokens":["def","__init__","(","self",",","user",")",":","self",".","user","=","user","conf","=","Configuration","(","'global'",")",".","configuration","self",".","key_disco","=","PublicKeyDiscoverer","(","conf",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/contact.py#L61-L65"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/contact.py","language":"python","identifier":"ContactEmailQualifier.create_new_email","parameters":"(self, contact, email)","argument_list":"","return_statement":"","docstring":"Add a new email for a contact.","docstring_summary":"Add a new email for a contact.","docstring_tokens":["Add","a","new","email","for","a","contact","."],"function":"def create_new_email(self, contact, email):\n \"\"\"Add a new email for a contact.\"\"\"\n found_keys = self.key_disco.search_email(email)\n if found_keys:\n log.info('Found keys for email {0}: {1}'.format(email, found_keys))\n self._process_new_keys(contact, found_keys)","function_tokens":["def","create_new_email","(","self",",","contact",",","email",")",":","found_keys","=","self",".","key_disco",".","search_email","(","email",")","if","found_keys",":","log",".","info","(","'Found keys for email {0}: {1}'",".","format","(","email",",","found_keys",")",")","self",".","_process_new_keys","(","contact",",","found_keys",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/components\/py.pi\/caliopen_pi\/qualifiers\/contact.py#L97-L102"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"BaseHandler.__init__","parameters":"(self, nats_cnx)","argument_list":"","return_statement":"","docstring":"Create a new inbound messsage handler from a nats connection.","docstring_summary":"Create a new inbound messsage handler from a nats connection.","docstring_tokens":["Create","a","new","inbound","messsage","handler","from","a","nats","connection","."],"function":"def __init__(self, nats_cnx):\n \"\"\"Create a new inbound messsage handler from a nats connection.\"\"\"\n self.natsConn = nats_cnx","function_tokens":["def","__init__","(","self",",","nats_cnx",")",":","self",".","natsConn","=","nats_cnx"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L26-L28"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"InboundEmail.process_raw","parameters":"(self, msg, payload)","argument_list":"","return_statement":"","docstring":"Process an inbound raw message.","docstring_summary":"Process an inbound raw message.","docstring_tokens":["Process","an","inbound","raw","message","."],"function":"def process_raw(self, msg, payload):\n \"\"\"Process an inbound raw message.\"\"\"\n nats_error = {\n 'error': '',\n 'message': 'inbound email message process failed'\n }\n nats_success = {\n 'message': 'OK : inbound email message proceeded'\n }\n try:\n user = User.get(payload['user_id'])\n identity = UserIdentity.get(user, payload['identity_id'])\n deliver = UserMailDelivery(user, identity)\n new_message = deliver.process_raw(payload['message_id'])\n nats_success['message_id'] = str(new_message.message_id)\n nats_success['discussion_id'] = str(new_message.discussion_id)\n self.natsConn.publish(msg.reply, json.dumps(nats_success))\n except DuplicateObject:\n log.info(\"Message already imported : {}\".format(payload))\n nats_success['message_id'] = str(payload['message_id'])\n nats_success['discussion_id'] = \"\" # message has not been parsed\n nats_success['message'] = 'raw message already imported'\n self.natsConn.publish(msg.reply, json.dumps(nats_success))\n except Exception as exc:\n # TODO: handle abort exception and report it as special case\n exc_info = sys.exc_info()\n log.error(\"deliver process failed for raw {}: {}\".\n format(payload, traceback.print_exception(*exc_info)))\n nats_error['error'] = str(exc)\n self.natsConn.publish(msg.reply, json.dumps(nats_error))\n return exc","function_tokens":["def","process_raw","(","self",",","msg",",","payload",")",":","nats_error","=","{","'error'",":","''",",","'message'",":","'inbound email message process failed'","}","nats_success","=","{","'message'",":","'OK : inbound email message proceeded'","}","try",":","user","=","User",".","get","(","payload","[","'user_id'","]",")","identity","=","UserIdentity",".","get","(","user",",","payload","[","'identity_id'","]",")","deliver","=","UserMailDelivery","(","user",",","identity",")","new_message","=","deliver",".","process_raw","(","payload","[","'message_id'","]",")","nats_success","[","'message_id'","]","=","str","(","new_message",".","message_id",")","nats_success","[","'discussion_id'","]","=","str","(","new_message",".","discussion_id",")","self",".","natsConn",".","publish","(","msg",".","reply",",","json",".","dumps","(","nats_success",")",")","except","DuplicateObject",":","log",".","info","(","\"Message already imported : {}\"",".","format","(","payload",")",")","nats_success","[","'message_id'","]","=","str","(","payload","[","'message_id'","]",")","nats_success","[","'discussion_id'","]","=","\"\"","# message has not been parsed","nats_success","[","'message'","]","=","'raw message already imported'","self",".","natsConn",".","publish","(","msg",".","reply",",","json",".","dumps","(","nats_success",")",")","except","Exception","as","exc",":","# TODO: handle abort exception and report it as special case","exc_info","=","sys",".","exc_info","(",")","log",".","error","(","\"deliver process failed for raw {}: {}\"",".","format","(","payload",",","traceback",".","print_exception","(","*","exc_info",")",")",")","nats_error","[","'error'","]","=","str","(","exc",")","self",".","natsConn",".","publish","(","msg",".","reply",",","json",".","dumps","(","nats_error",")",")","return","exc"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L34-L64"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"InboundEmail.handler","parameters":"(self, msg)","argument_list":"","return_statement":"","docstring":"Handle an process_raw nats messages.","docstring_summary":"Handle an process_raw nats messages.","docstring_tokens":["Handle","an","process_raw","nats","messages","."],"function":"def handler(self, msg):\n \"\"\"Handle an process_raw nats messages.\"\"\"\n payload = json.loads(msg.data)\n log.info('Get payload order {}'.format(payload))\n if payload['order'] == \"process_raw\":\n self.process_raw(msg, payload)\n else:\n log.warn(\n 'Unhandled payload order \"{}\" \\\n (queue: SMTPqueue, subject : inboundSMTP)'.format(\n payload['order']))\n raise NotImplementedError","function_tokens":["def","handler","(","self",",","msg",")",":","payload","=","json",".","loads","(","msg",".","data",")","log",".","info","(","'Get payload order {}'",".","format","(","payload",")",")","if","payload","[","'order'","]","==","\"process_raw\"",":","self",".","process_raw","(","msg",",","payload",")","else",":","log",".","warn","(","'Unhandled payload order \"{}\" \\\n (queue: SMTPqueue, subject : inboundSMTP)'",".","format","(","payload","[","'order'","]",")",")","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L66-L77"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"InboundTwitter.process_raw","parameters":"(self, msg, payload)","argument_list":"","return_statement":"","docstring":"Process an inbound raw message.","docstring_summary":"Process an inbound raw message.","docstring_tokens":["Process","an","inbound","raw","message","."],"function":"def process_raw(self, msg, payload):\n \"\"\"Process an inbound raw message.\"\"\"\n nats_error = {\n 'error': '',\n 'message': 'inbound twitter message process failed'\n }\n nats_success = {\n 'message': 'OK : inbound twitter message proceeded'\n }\n try:\n user = User.get(payload['user_id'])\n identity = UserIdentity.get(user, payload['identity_id'])\n deliver = UserTwitterDelivery(user, identity)\n new_message = deliver.process_raw(payload['message_id'])\n nats_success['message_id'] = str(new_message.message_id)\n nats_success['discussion_id'] = str(new_message.discussion_id)\n self.natsConn.publish(msg.reply, json.dumps(nats_success))\n except DuplicateObject:\n log.info(\"Message already imported : {}\".format(payload))\n nats_success['message_id'] = str(payload['message_id'])\n nats_success['discussion_id'] = \"\" # message has not been parsed\n nats_success['message'] = 'raw message already imported'\n self.natsConn.publish(msg.reply, json.dumps(nats_success))\n except Exception as exc:\n # TODO: handle abort exception and report it as special case\n exc_info = sys.exc_info()\n log.error(\"deliver process failed for raw {}: {}\".\n format(payload, traceback.print_exception(*exc_info)))\n nats_error['error'] = str(exc.message)\n self.natsConn.publish(msg.reply, json.dumps(nats_error))\n return exc","function_tokens":["def","process_raw","(","self",",","msg",",","payload",")",":","nats_error","=","{","'error'",":","''",",","'message'",":","'inbound twitter message process failed'","}","nats_success","=","{","'message'",":","'OK : inbound twitter message proceeded'","}","try",":","user","=","User",".","get","(","payload","[","'user_id'","]",")","identity","=","UserIdentity",".","get","(","user",",","payload","[","'identity_id'","]",")","deliver","=","UserTwitterDelivery","(","user",",","identity",")","new_message","=","deliver",".","process_raw","(","payload","[","'message_id'","]",")","nats_success","[","'message_id'","]","=","str","(","new_message",".","message_id",")","nats_success","[","'discussion_id'","]","=","str","(","new_message",".","discussion_id",")","self",".","natsConn",".","publish","(","msg",".","reply",",","json",".","dumps","(","nats_success",")",")","except","DuplicateObject",":","log",".","info","(","\"Message already imported : {}\"",".","format","(","payload",")",")","nats_success","[","'message_id'","]","=","str","(","payload","[","'message_id'","]",")","nats_success","[","'discussion_id'","]","=","\"\"","# message has not been parsed","nats_success","[","'message'","]","=","'raw message already imported'","self",".","natsConn",".","publish","(","msg",".","reply",",","json",".","dumps","(","nats_success",")",")","except","Exception","as","exc",":","# TODO: handle abort exception and report it as special case","exc_info","=","sys",".","exc_info","(",")","log",".","error","(","\"deliver process failed for raw {}: {}\"",".","format","(","payload",",","traceback",".","print_exception","(","*","exc_info",")",")",")","nats_error","[","'error'","]","=","str","(","exc",".","message",")","self",".","natsConn",".","publish","(","msg",".","reply",",","json",".","dumps","(","nats_error",")",")","return","exc"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L83-L113"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"InboundTwitter.handler","parameters":"(self, msg)","argument_list":"","return_statement":"","docstring":"Handle an process_raw nats messages.","docstring_summary":"Handle an process_raw nats messages.","docstring_tokens":["Handle","an","process_raw","nats","messages","."],"function":"def handler(self, msg):\n \"\"\"Handle an process_raw nats messages.\"\"\"\n payload = json.loads(msg.data)\n log.info('Get payload order {}'.format(payload['order']))\n if payload['order'] == \"process_raw\":\n self.process_raw(msg, payload)\n else:\n log.warn('Unhandled payload type {}'.format(payload['order']))","function_tokens":["def","handler","(","self",",","msg",")",":","payload","=","json",".","loads","(","msg",".","data",")","log",".","info","(","'Get payload order {}'",".","format","(","payload","[","'order'","]",")",")","if","payload","[","'order'","]","==","\"process_raw\"",":","self",".","process_raw","(","msg",",","payload",")","else",":","log",".","warn","(","'Unhandled payload type {}'",".","format","(","payload","[","'order'","]",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L115-L122"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"InboundMastodon.process_raw","parameters":"(self, msg, payload)","argument_list":"","return_statement":"","docstring":"Process an inbound raw message.","docstring_summary":"Process an inbound raw message.","docstring_tokens":["Process","an","inbound","raw","message","."],"function":"def process_raw(self, msg, payload):\n \"\"\"Process an inbound raw message.\"\"\"\n nats_error = {\n 'error': '',\n 'message': 'inbound mastodon message process failed'\n }\n nats_success = {\n 'message': 'OK : inbound mastodon message proceeded'\n }\n try:\n user = User.get(payload['user_id'])\n identity = UserIdentity.get(user, payload['identity_id'])\n deliver = UserMastodonDelivery(user, identity)\n new_message = deliver.process_raw(payload['message_id'])\n nats_success['message_id'] = str(new_message.message_id)\n nats_success['discussion_id'] = str(new_message.discussion_id)\n self.natsConn.publish(msg.reply, json.dumps(nats_success))\n except DuplicateObject:\n log.info(\"Message already imported : {}\".format(payload))\n nats_success['message_id'] = str(payload['message_id'])\n nats_success['discussion_id'] = \"\" # message has not been parsed\n nats_success['message'] = 'raw message already imported'\n self.natsConn.publish(msg.reply, json.dumps(nats_success))\n except Exception as exc:\n # TODO: handle abort exception and report it as special case\n exc_info = sys.exc_info()\n log.error(\"deliver process failed for raw {}: {}\".\n format(payload, traceback.print_exception(*exc_info)))\n nats_error['error'] = str(exc.message)\n self.natsConn.publish(msg.reply, json.dumps(nats_error))\n return exc","function_tokens":["def","process_raw","(","self",",","msg",",","payload",")",":","nats_error","=","{","'error'",":","''",",","'message'",":","'inbound mastodon message process failed'","}","nats_success","=","{","'message'",":","'OK : inbound mastodon message proceeded'","}","try",":","user","=","User",".","get","(","payload","[","'user_id'","]",")","identity","=","UserIdentity",".","get","(","user",",","payload","[","'identity_id'","]",")","deliver","=","UserMastodonDelivery","(","user",",","identity",")","new_message","=","deliver",".","process_raw","(","payload","[","'message_id'","]",")","nats_success","[","'message_id'","]","=","str","(","new_message",".","message_id",")","nats_success","[","'discussion_id'","]","=","str","(","new_message",".","discussion_id",")","self",".","natsConn",".","publish","(","msg",".","reply",",","json",".","dumps","(","nats_success",")",")","except","DuplicateObject",":","log",".","info","(","\"Message already imported : {}\"",".","format","(","payload",")",")","nats_success","[","'message_id'","]","=","str","(","payload","[","'message_id'","]",")","nats_success","[","'discussion_id'","]","=","\"\"","# message has not been parsed","nats_success","[","'message'","]","=","'raw message already imported'","self",".","natsConn",".","publish","(","msg",".","reply",",","json",".","dumps","(","nats_success",")",")","except","Exception","as","exc",":","# TODO: handle abort exception and report it as special case","exc_info","=","sys",".","exc_info","(",")","log",".","error","(","\"deliver process failed for raw {}: {}\"",".","format","(","payload",",","traceback",".","print_exception","(","*","exc_info",")",")",")","nats_error","[","'error'","]","=","str","(","exc",".","message",")","self",".","natsConn",".","publish","(","msg",".","reply",",","json",".","dumps","(","nats_error",")",")","return","exc"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L128-L158"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"InboundMastodon.handler","parameters":"(self, msg)","argument_list":"","return_statement":"","docstring":"Handle an process_raw nats messages.","docstring_summary":"Handle an process_raw nats messages.","docstring_tokens":["Handle","an","process_raw","nats","messages","."],"function":"def handler(self, msg):\n \"\"\"Handle an process_raw nats messages.\"\"\"\n payload = json.loads(msg.data)\n log.info('Get payload order {}'.format(payload['order']))\n if payload['order'] == \"process_raw\":\n self.process_raw(msg, payload)\n else:\n log.warn('Unhandled payload type {}'.format(payload['order']))","function_tokens":["def","handler","(","self",",","msg",")",":","payload","=","json",".","loads","(","msg",".","data",")","log",".","info","(","'Get payload order {}'",".","format","(","payload","[","'order'","]",")",")","if","payload","[","'order'","]","==","\"process_raw\"",":","self",".","process_raw","(","msg",",","payload",")","else",":","log",".","warn","(","'Unhandled payload type {}'",".","format","(","payload","[","'order'","]",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L160-L167"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"ContactAction.process_update","parameters":"(self, msg, payload)","argument_list":"","return_statement":"","docstring":"Process a contact update message.","docstring_summary":"Process a contact update message.","docstring_tokens":["Process","a","contact","update","message","."],"function":"def process_update(self, msg, payload):\n \"\"\"Process a contact update message.\"\"\"\n # XXX validate payload structure\n if 'user_id' not in payload or 'contact_id' not in payload:\n raise Exception('Invalid contact_update structure')\n user = User.get(payload['user_id'])\n contact = Contact(user, contact_id=payload['contact_id'])\n contact.get_db()\n contact.unmarshall_db()\n qualifier = ContactMessageQualifier(user)\n log.info('Will process update for contact {0} of user {1}'.\n format(contact.contact_id, user.user_id))\n # TODO: (re)discover GPG keys\n qualifier.process(contact)","function_tokens":["def","process_update","(","self",",","msg",",","payload",")",":","# XXX validate payload structure","if","'user_id'","not","in","payload","or","'contact_id'","not","in","payload",":","raise","Exception","(","'Invalid contact_update structure'",")","user","=","User",".","get","(","payload","[","'user_id'","]",")","contact","=","Contact","(","user",",","contact_id","=","payload","[","'contact_id'","]",")","contact",".","get_db","(",")","contact",".","unmarshall_db","(",")","qualifier","=","ContactMessageQualifier","(","user",")","log",".","info","(","'Will process update for contact {0} of user {1}'",".","format","(","contact",".","contact_id",",","user",".","user_id",")",")","# TODO: (re)discover GPG keys","qualifier",".","process","(","contact",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L173-L186"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"ContactAction.handler","parameters":"(self, msg)","argument_list":"","return_statement":"","docstring":"Handle an process_raw nats messages.","docstring_summary":"Handle an process_raw nats messages.","docstring_tokens":["Handle","an","process_raw","nats","messages","."],"function":"def handler(self, msg):\n \"\"\"Handle an process_raw nats messages.\"\"\"\n payload = json.loads(msg.data)\n # log.info('Get payload order {}'.format(payload['order']))\n if payload['order'] == \"contact_update\":\n self.process_update(msg, payload)\n else:\n log.warn(\n 'Unhandled payload order \"{}\" \\\n (queue: contactQueue, subject : contactAction)'.format(\n payload['order']))\n raise NotImplementedError","function_tokens":["def","handler","(","self",",","msg",")",":","payload","=","json",".","loads","(","msg",".","data",")","# log.info('Get payload order {}'.format(payload['order']))","if","payload","[","'order'","]","==","\"contact_update\"",":","self",".","process_update","(","msg",",","payload",")","else",":","log",".","warn","(","'Unhandled payload order \"{}\" \\\n (queue: contactQueue, subject : contactAction)'",".","format","(","payload","[","'order'","]",")",")","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L188-L199"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"KeyAction.process_key_discovery","parameters":"(self, msg, payload)","argument_list":"","return_statement":"","docstring":"Discover public keys related to a new contact identifier.","docstring_summary":"Discover public keys related to a new contact identifier.","docstring_tokens":["Discover","public","keys","related","to","a","new","contact","identifier","."],"function":"def process_key_discovery(self, msg, payload):\n \"\"\"Discover public keys related to a new contact identifier.\"\"\"\n if 'user_id' not in payload or 'contact_id' not in payload:\n raise Exception('Invalid contact_update structure')\n user = User.get(payload['user_id'])\n contact = Contact(user.user_id, contact_id=payload['contact_id'])\n contact.get_db()\n contact.unmarshall_db()\n manager = ContactPublicKeyManager()\n founds = []\n for ident in payload.get('emails', []):\n log.info('Process email identity {0}'.format(ident['address']))\n discovery = manager.process_identity(user, contact,\n ident['address'], 'email')\n if discovery:\n founds.append(discovery)\n for ident in payload.get('identities', []):\n log.info('Process identity {0}:{1}'.\n format(ident['type'], ident['name']))\n discovery = manager.process_identity(user, contact,\n ident['name'], ident['type'])\n if discovery:\n founds.append(discovery)\n if founds:\n log.info('Found %d results' % len(founds))\n self._process_results(user, contact, founds)","function_tokens":["def","process_key_discovery","(","self",",","msg",",","payload",")",":","if","'user_id'","not","in","payload","or","'contact_id'","not","in","payload",":","raise","Exception","(","'Invalid contact_update structure'",")","user","=","User",".","get","(","payload","[","'user_id'","]",")","contact","=","Contact","(","user",".","user_id",",","contact_id","=","payload","[","'contact_id'","]",")","contact",".","get_db","(",")","contact",".","unmarshall_db","(",")","manager","=","ContactPublicKeyManager","(",")","founds","=","[","]","for","ident","in","payload",".","get","(","'emails'",",","[","]",")",":","log",".","info","(","'Process email identity {0}'",".","format","(","ident","[","'address'","]",")",")","discovery","=","manager",".","process_identity","(","user",",","contact",",","ident","[","'address'","]",",","'email'",")","if","discovery",":","founds",".","append","(","discovery",")","for","ident","in","payload",".","get","(","'identities'",",","[","]",")",":","log",".","info","(","'Process identity {0}:{1}'",".","format","(","ident","[","'type'","]",",","ident","[","'name'","]",")",")","discovery","=","manager",".","process_identity","(","user",",","contact",",","ident","[","'name'","]",",","ident","[","'type'","]",")","if","discovery",":","founds",".","append","(","discovery",")","if","founds",":","log",".","info","(","'Found %d results'","%","len","(","founds",")",")","self",".","_process_results","(","user",",","contact",",","founds",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L227-L252"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py","language":"python","identifier":"KeyAction.handler","parameters":"(self, msg)","argument_list":"","return_statement":"","docstring":"Handle a discover_key nats messages.","docstring_summary":"Handle a discover_key nats messages.","docstring_tokens":["Handle","a","discover_key","nats","messages","."],"function":"def handler(self, msg):\n \"\"\"Handle a discover_key nats messages.\"\"\"\n payload = json.loads(msg.data)\n if payload['order'] == \"discover_key\":\n self.process_key_discovery(msg, payload)\n else:\n log.warn(\n 'Unhandled payload order \"{}\" \\\n (queue : keyQueue, subject : keyAction)'.format(\n payload['order']))\n raise NotImplementedError","function_tokens":["def","handler","(","self",",","msg",")",":","payload","=","json",".","loads","(","msg",".","data",")","if","payload","[","'order'","]","==","\"discover_key\"",":","self",".","process_key_discovery","(","msg",",","payload",")","else",":","log",".","warn","(","'Unhandled payload order \"{}\" \\\n (queue : keyQueue, subject : keyAction)'",".","format","(","payload","[","'order'","]",")",")","raise","NotImplementedError"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/subscribers.py#L254-L264"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/delivery.py","language":"python","identifier":"UserMessageDelivery.__init__","parameters":"(self, user, identity)","argument_list":"","return_statement":"","docstring":"Create a new UserMessageDelivery belong to an user.","docstring_summary":"Create a new UserMessageDelivery belong to an user.","docstring_tokens":["Create","a","new","UserMessageDelivery","belong","to","an","user","."],"function":"def __init__(self, user, identity):\n \"\"\"Create a new UserMessageDelivery belong to an user.\"\"\"\n self.user = user\n self.identity = identity\n self.qualifier = None","function_tokens":["def","__init__","(","self",",","user",",","identity",")",":","self",".","user","=","user","self",".","identity","=","identity","self",".","qualifier","=","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/delivery.py#L23-L27"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/delivery.py","language":"python","identifier":"UserMessageDelivery.process_raw","parameters":"(self, raw_msg_id)","argument_list":"","return_statement":"return obj","docstring":"Process a raw message for an user, ie makes it a rich 'message'.","docstring_summary":"Process a raw message for an user, ie makes it a rich 'message'.","docstring_tokens":["Process","a","raw","message","for","an","user","ie","makes","it","a","rich","message","."],"function":"def process_raw(self, raw_msg_id):\n \"\"\"Process a raw message for an user, ie makes it a rich 'message'.\"\"\"\n raw = RawMessage.get(raw_msg_id)\n if not raw:\n log.error('Raw message <{}> not found'.format(raw_msg_id))\n raise NotFound\n log.debug('Retrieved raw message {}'.format(raw_msg_id))\n\n message = self.qualifier.process_inbound(raw)\n # fill user_tag table with imported tags and embed in message\n for tag in message.ext_tags:\n try:\n Tag.get(user_id=self.user.user_id, name=tag.name)\n except NotFound:\n try:\n Tag.create(user_id=self.user.user_id, name=tag.name,\n label=tag.label, type=tag.type,\n date_insert=datetime.datetime.now(tz=pytz.utc))\n except Exception as exc:\n log.exception(\n \"UserMessageDelivery failed to create tag : {}\".format(\n exc))\n message.tags.append(tag.name)\n\n if message.external_msg_id:\n external_refs = Merl._model_class.filter(\n user_id=self.user.user_id,\n external_msg_id=message.external_msg_id)\n if external_refs:\n msg = external_refs[0]\n # message already imported, should update it with identity_id ?\n obj = Message(user=self.user,\n message_id=msg.message_id)\n if str(msg.identity_id) != self.identity.identity_id:\n obj.get_db()\n obj.unmarshall_db()\n obj.user_identities.append(self.identity.identity_id)\n obj.marshall_db()\n obj.save_db()\n obj.marshall_index()\n obj.save_index()\n Merl.create(self.user,\n external_msg_id=msg.external_msg_id,\n identity_id=self.identity.identity_id,\n message_id=msg.message_id)\n # TODO: update flags ?\n raise DuplicateObject(DUPLICATE_MESSAGE_EXC)\n else:\n log.warn('Message without external message_id for raw {}'.\n format(raw.raw_msg_id))\n # store and index Message\n obj = Message(user=self.user)\n obj.unmarshall_dict(message.to_native())\n obj.user_id = uuid.UUID(self.user.user_id)\n obj.user_identities = [uuid.UUID(self.identity.identity_id)]\n obj.message_id = uuid.uuid4()\n obj.date_insert = datetime.datetime.now(tz=pytz.utc)\n obj.date_sort = obj.date_insert\n obj.marshall_db()\n obj.save_db()\n obj.marshall_index()\n obj.save_index()\n\n if message.external_msg_id:\n # store external_msg_id in lookup table\n # but do not abort if it failed\n try:\n Merl.create(self.user,\n external_msg_id=obj.external_msg_id,\n identity_id=obj.user_identity,\n message_id=obj.message_id)\n except Exception as exc:\n log.exception(\"UserMessageDelivery failed \"\n \"to store message_external_ref : {}\".format(exc))\n\n return obj","function_tokens":["def","process_raw","(","self",",","raw_msg_id",")",":","raw","=","RawMessage",".","get","(","raw_msg_id",")","if","not","raw",":","log",".","error","(","'Raw message <{}> not found'",".","format","(","raw_msg_id",")",")","raise","NotFound","log",".","debug","(","'Retrieved raw message {}'",".","format","(","raw_msg_id",")",")","message","=","self",".","qualifier",".","process_inbound","(","raw",")","# fill user_tag table with imported tags and embed in message","for","tag","in","message",".","ext_tags",":","try",":","Tag",".","get","(","user_id","=","self",".","user",".","user_id",",","name","=","tag",".","name",")","except","NotFound",":","try",":","Tag",".","create","(","user_id","=","self",".","user",".","user_id",",","name","=","tag",".","name",",","label","=","tag",".","label",",","type","=","tag",".","type",",","date_insert","=","datetime",".","datetime",".","now","(","tz","=","pytz",".","utc",")",")","except","Exception","as","exc",":","log",".","exception","(","\"UserMessageDelivery failed to create tag : {}\"",".","format","(","exc",")",")","message",".","tags",".","append","(","tag",".","name",")","if","message",".","external_msg_id",":","external_refs","=","Merl",".","_model_class",".","filter","(","user_id","=","self",".","user",".","user_id",",","external_msg_id","=","message",".","external_msg_id",")","if","external_refs",":","msg","=","external_refs","[","0","]","# message already imported, should update it with identity_id ?","obj","=","Message","(","user","=","self",".","user",",","message_id","=","msg",".","message_id",")","if","str","(","msg",".","identity_id",")","!=","self",".","identity",".","identity_id",":","obj",".","get_db","(",")","obj",".","unmarshall_db","(",")","obj",".","user_identities",".","append","(","self",".","identity",".","identity_id",")","obj",".","marshall_db","(",")","obj",".","save_db","(",")","obj",".","marshall_index","(",")","obj",".","save_index","(",")","Merl",".","create","(","self",".","user",",","external_msg_id","=","msg",".","external_msg_id",",","identity_id","=","self",".","identity",".","identity_id",",","message_id","=","msg",".","message_id",")","# TODO: update flags ?","raise","DuplicateObject","(","DUPLICATE_MESSAGE_EXC",")","else",":","log",".","warn","(","'Message without external message_id for raw {}'",".","format","(","raw",".","raw_msg_id",")",")","# store and index Message","obj","=","Message","(","user","=","self",".","user",")","obj",".","unmarshall_dict","(","message",".","to_native","(",")",")","obj",".","user_id","=","uuid",".","UUID","(","self",".","user",".","user_id",")","obj",".","user_identities","=","[","uuid",".","UUID","(","self",".","identity",".","identity_id",")","]","obj",".","message_id","=","uuid",".","uuid4","(",")","obj",".","date_insert","=","datetime",".","datetime",".","now","(","tz","=","pytz",".","utc",")","obj",".","date_sort","=","obj",".","date_insert","obj",".","marshall_db","(",")","obj",".","save_db","(",")","obj",".","marshall_index","(",")","obj",".","save_index","(",")","if","message",".","external_msg_id",":","# store external_msg_id in lookup table","# but do not abort if it failed","try",":","Merl",".","create","(","self",".","user",",","external_msg_id","=","obj",".","external_msg_id",",","identity_id","=","obj",".","user_identity",",","message_id","=","obj",".","message_id",")","except","Exception","as","exc",":","log",".","exception","(","\"UserMessageDelivery failed \"","\"to store message_external_ref : {}\"",".","format","(","exc",")",")","return","obj"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/delivery.py#L29-L104"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py","language":"python","identifier":"inbound_smtp_handler","parameters":"(config)","argument_list":"","return_statement":"","docstring":"Inbound message NATS handler.","docstring_summary":"Inbound message NATS handler.","docstring_tokens":["Inbound","message","NATS","handler","."],"function":"def inbound_smtp_handler(config):\n \"\"\"Inbound message NATS handler.\"\"\"\n client = Nats()\n server = 'nats:\/\/{}:{}'.format(config['host'], config['port'])\n servers = [server]\n\n opts = {\"servers\": servers}\n yield client.connect(**opts)\n\n # create and register subscriber(s)\n inbound_email_sub = subscribers.InboundEmail(client)\n future = client.subscribe(\"inboundSMTP\", \"SMTPqueue\",\n inbound_email_sub.handler)\n log.info(\"nats subscription started for inboundSMTP\")\n future.result()","function_tokens":["def","inbound_smtp_handler","(","config",")",":","client","=","Nats","(",")","server","=","'nats:\/\/{}:{}'",".","format","(","config","[","'host'","]",",","config","[","'port'","]",")","servers","=","[","server","]","opts","=","{","\"servers\"",":","servers","}","yield","client",".","connect","(","*","*","opts",")","# create and register subscriber(s)","inbound_email_sub","=","subscribers",".","InboundEmail","(","client",")","future","=","client",".","subscribe","(","\"inboundSMTP\"",",","\"SMTPqueue\"",",","inbound_email_sub",".","handler",")","log",".","info","(","\"nats subscription started for inboundSMTP\"",")","future",".","result","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py#L21-L35"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py","language":"python","identifier":"inbound_twitter_handler","parameters":"(config)","argument_list":"","return_statement":"","docstring":"Inbound twitterDM NATS handler","docstring_summary":"Inbound twitterDM NATS handler","docstring_tokens":["Inbound","twitterDM","NATS","handler"],"function":"def inbound_twitter_handler(config):\n \"\"\"Inbound twitterDM NATS handler\"\"\"\n client = Nats()\n server = 'nats:\/\/{}:{}'.format(config['host'], config['port'])\n servers = [server]\n\n opts = {\"servers\": servers}\n yield client.connect(**opts)\n\n # create and register subscriber(s)\n inbound_twitter_sub = subscribers.InboundTwitter(client)\n future = client.subscribe(\"inboundTwitter\", \"Twitterqueue\",\n inbound_twitter_sub.handler)\n log.info(\"nats subscription started for inboundTwitter\")\n future.result()","function_tokens":["def","inbound_twitter_handler","(","config",")",":","client","=","Nats","(",")","server","=","'nats:\/\/{}:{}'",".","format","(","config","[","'host'","]",",","config","[","'port'","]",")","servers","=","[","server","]","opts","=","{","\"servers\"",":","servers","}","yield","client",".","connect","(","*","*","opts",")","# create and register subscriber(s)","inbound_twitter_sub","=","subscribers",".","InboundTwitter","(","client",")","future","=","client",".","subscribe","(","\"inboundTwitter\"",",","\"Twitterqueue\"",",","inbound_twitter_sub",".","handler",")","log",".","info","(","\"nats subscription started for inboundTwitter\"",")","future",".","result","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py#L38-L52"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py","language":"python","identifier":"inbound_mastodon_handler","parameters":"(config)","argument_list":"","return_statement":"","docstring":"Inbound mastodonDM NATS handler","docstring_summary":"Inbound mastodonDM NATS handler","docstring_tokens":["Inbound","mastodonDM","NATS","handler"],"function":"def inbound_mastodon_handler(config):\n \"\"\"Inbound mastodonDM NATS handler\"\"\"\n client = Nats()\n server = 'nats:\/\/{}:{}'.format(config['host'], config['port'])\n servers = [server]\n\n opts = {\"servers\": servers}\n yield client.connect(**opts)\n\n # create and register subscriber(s)\n inbound_mastodon_sub = subscribers.InboundMastodon(client)\n future = client.subscribe(\"inboundMastodon\", \"Mastodonqueue\",\n inbound_mastodon_sub.handler)\n log.info(\"nats subscription started for inboundMastodon\")\n future.result()","function_tokens":["def","inbound_mastodon_handler","(","config",")",":","client","=","Nats","(",")","server","=","'nats:\/\/{}:{}'",".","format","(","config","[","'host'","]",",","config","[","'port'","]",")","servers","=","[","server","]","opts","=","{","\"servers\"",":","servers","}","yield","client",".","connect","(","*","*","opts",")","# create and register subscriber(s)","inbound_mastodon_sub","=","subscribers",".","InboundMastodon","(","client",")","future","=","client",".","subscribe","(","\"inboundMastodon\"",",","\"Mastodonqueue\"",",","inbound_mastodon_sub",".","handler",")","log",".","info","(","\"nats subscription started for inboundMastodon\"",")","future",".","result","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py#L55-L69"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py","language":"python","identifier":"contact_handler","parameters":"(config)","argument_list":"","return_statement":"","docstring":"NATS handler for contact update events.","docstring_summary":"NATS handler for contact update events.","docstring_tokens":["NATS","handler","for","contact","update","events","."],"function":"def contact_handler(config):\n \"\"\"NATS handler for contact update events.\"\"\"\n client = Nats()\n server = 'nats:\/\/{}:{}'.format(config['host'], config['port'])\n servers = [server]\n\n opts = {\"servers\": servers}\n yield client.connect(**opts)\n\n # create and register subscriber(s)\n contact_subscriber = subscribers.ContactAction(client)\n future = client.subscribe(\"contactAction\", \"contactQueue\",\n contact_subscriber.handler)\n log.info(\"nats subscription started for contactAction\")\n future.result()","function_tokens":["def","contact_handler","(","config",")",":","client","=","Nats","(",")","server","=","'nats:\/\/{}:{}'",".","format","(","config","[","'host'","]",",","config","[","'port'","]",")","servers","=","[","server","]","opts","=","{","\"servers\"",":","servers","}","yield","client",".","connect","(","*","*","opts",")","# create and register subscriber(s)","contact_subscriber","=","subscribers",".","ContactAction","(","client",")","future","=","client",".","subscribe","(","\"contactAction\"",",","\"contactQueue\"",",","contact_subscriber",".","handler",")","log",".","info","(","\"nats subscription started for contactAction\"",")","future",".","result","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py#L72-L86"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py","language":"python","identifier":"key_handler","parameters":"(config)","argument_list":"","return_statement":"","docstring":"NATS handler for discover_key events.","docstring_summary":"NATS handler for discover_key events.","docstring_tokens":["NATS","handler","for","discover_key","events","."],"function":"def key_handler(config):\n \"\"\"NATS handler for discover_key events.\"\"\"\n client = Nats()\n server = 'nats:\/\/{}:{}'.format(config['host'], config['port'])\n servers = [server]\n\n opts = {\"servers\": servers}\n yield client.connect(**opts)\n\n # create and register subscriber(s)\n key_subscriber = subscribers.KeyAction(client)\n future = client.subscribe(\"keyAction\",\n \"keyQueue\",\n key_subscriber.handler)\n log.info(\"nats subscription started for keyAction\")\n future.result()","function_tokens":["def","key_handler","(","config",")",":","client","=","Nats","(",")","server","=","'nats:\/\/{}:{}'",".","format","(","config","[","'host'","]",",","config","[","'port'","]",")","servers","=","[","server","]","opts","=","{","\"servers\"",":","servers","}","yield","client",".","connect","(","*","*","opts",")","# create and register subscriber(s)","key_subscriber","=","subscribers",".","KeyAction","(","client",")","future","=","client",".","subscribe","(","\"keyAction\"",",","\"keyQueue\"",",","key_subscriber",".","handler",")","log",".","info","(","\"nats subscription started for keyAction\"",")","future",".","result","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/NATS\/py.client\/caliopen_nats\/listener.py#L90-L105"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/__init__.py","language":"python","identifier":"main","parameters":"(global_config, **settings)","argument_list":"","return_statement":"return config.make_wsgi_app()","docstring":"Caliopen entry point for WSGI application.\n\n Load Caliopen configuration and setup a WSGI application\n with loaded API services.","docstring_summary":"Caliopen entry point for WSGI application.","docstring_tokens":["Caliopen","entry","point","for","WSGI","application","."],"function":"def main(global_config, **settings):\n \"\"\"Caliopen entry point for WSGI application.\n\n Load Caliopen configuration and setup a WSGI application\n with loaded API services.\n \"\"\"\n # XXX ugly way to init caliopen configuration before pyramid\n caliopen_config = settings['caliopen.config'].split(':')[1]\n Configuration.load(caliopen_config, 'global')\n\n settings['pyramid_swagger.exclude_paths'] = [r'^\/api-ui\/?', r'^\/doc\/api\/?', r'^\/defs\/?']\n settings['pyramid_swagger.enable_response_validation'] = True\n config = Configurator(settings=settings)\n services = config.registry.settings. \\\n get('caliopen_api.services', []). \\\n split('\\n')\n route_prefix = settings.get('caliopen_api.route_prefix')\n for service in services:\n log.info('Loading %s service' % service)\n config.include(service, route_prefix=route_prefix)\n config.end()\n return config.make_wsgi_app()","function_tokens":["def","main","(","global_config",",","*","*","settings",")",":","# XXX ugly way to init caliopen configuration before pyramid","caliopen_config","=","settings","[","'caliopen.config'","]",".","split","(","':'",")","[","1","]","Configuration",".","load","(","caliopen_config",",","'global'",")","settings","[","'pyramid_swagger.exclude_paths'","]","=","[","r'^\/api-ui\/?'",",","r'^\/doc\/api\/?'",",","r'^\/defs\/?'","]","settings","[","'pyramid_swagger.enable_response_validation'","]","=","True","config","=","Configurator","(","settings","=","settings",")","services","=","config",".","registry",".","settings",".","get","(","'caliopen_api.services'",",","[","]",")",".","split","(","'\\n'",")","route_prefix","=","settings",".","get","(","'caliopen_api.route_prefix'",")","for","service","in","services",":","log",".","info","(","'Loading %s service'","%","service",")","config",".","include","(","service",",","route_prefix","=","route_prefix",")","config",".","end","(",")","return","config",".","make_wsgi_app","(",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/__init__.py#L15-L36"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/__init__.py","language":"python","identifier":"Api.get_limit","parameters":"(self)","argument_list":"","return_statement":"return int(self.request.params.get('limit', DEFAULT_LIMIT))","docstring":"Return pagination limit from request else default.","docstring_summary":"Return pagination limit from request else default.","docstring_tokens":["Return","pagination","limit","from","request","else","default","."],"function":"def get_limit(self):\n \"\"\"Return pagination limit from request else default.\"\"\"\n return int(self.request.params.get('limit', DEFAULT_LIMIT))","function_tokens":["def","get_limit","(","self",")",":","return","int","(","self",".","request",".","params",".","get","(","'limit'",",","DEFAULT_LIMIT",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/__init__.py#L17-L19"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/__init__.py","language":"python","identifier":"Api.get_offset","parameters":"(self)","argument_list":"","return_statement":"return int(self.request.params.get('offset', 0))","docstring":"Return pagination offset from request else 0.","docstring_summary":"Return pagination offset from request else 0.","docstring_tokens":["Return","pagination","offset","from","request","else","0","."],"function":"def get_offset(self):\n \"\"\"Return pagination offset from request else 0.\"\"\"\n return int(self.request.params.get('offset', 0))","function_tokens":["def","get_offset","(","self",")",":","return","int","(","self",".","request",".","params",".","get","(","'offset'",",","0",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/__init__.py#L21-L23"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/errors.py","language":"python","identifier":"format_response_detail","parameters":"(exc, request)","argument_list":"","return_statement":"return {'component': route,\n 'values': exc.code,\n 'property': exc.__class__.__name__,\n 'message': exc.message}","docstring":"Format error details for a server error.","docstring_summary":"Format error details for a server error.","docstring_tokens":["Format","error","details","for","a","server","error","."],"function":"def format_response_detail(exc, request):\n \"\"\"Format error details for a server error.\"\"\"\n route = (request.matched_route.name\n if request.matched_route else ('Unknown'))\n return {'component': route,\n 'values': exc.code,\n 'property': exc.__class__.__name__,\n 'message': exc.message}","function_tokens":["def","format_response_detail","(","exc",",","request",")",":","route","=","(","request",".","matched_route",".","name","if","request",".","matched_route","else","(","'Unknown'",")",")","return","{","'component'",":","route",",","'values'",":","exc",".","code",",","'property'",":","exc",".","__class__",".","__name__",",","'message'",":","exc",".","message","}"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/errors.py#L54-L61"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/errors.py","language":"python","identifier":"format_response","parameters":"(exc, request, details=None)","argument_list":"","return_statement":"return response","docstring":"Format response error, details contains application errors.","docstring_summary":"Format response error, details contains application errors.","docstring_tokens":["Format","response","error","details","contains","application","errors","."],"function":"def format_response(exc, request, details=None):\n \"\"\"Format response error, details contains application errors.\"\"\"\n # XXX better design for details as keys are not validated\n if not details:\n details = {'values': [exc.code],\n 'property': None,\n 'component': 'server'}\n error = {\"errors\": [{\"description\": exc.explanation,\n \"type\": exc.title,\n \"values\": details['values'],\n \"property\": details['property'],\n \"component\": details['component'],\n \"message\": \"{}\".format(details['message']),\n \"code\": exc.code}]}\n response = Response(json.dumps(error))\n response.content_type = str('application\/json; charset=UTF-8')\n response.status_int = exc.code\n return response","function_tokens":["def","format_response","(","exc",",","request",",","details","=","None",")",":","# XXX better design for details as keys are not validated","if","not","details",":","details","=","{","'values'",":","[","exc",".","code","]",",","'property'",":","None",",","'component'",":","'server'","}","error","=","{","\"errors\"",":","[","{","\"description\"",":","exc",".","explanation",",","\"type\"",":","exc",".","title",",","\"values\"",":","details","[","'values'","]",",","\"property\"",":","details","[","'property'","]",",","\"component\"",":","details","[","'component'","]",",","\"message\"",":","\"{}\"",".","format","(","details","[","'message'","]",")",",","\"code\"",":","exc",".","code","}","]","}","response","=","Response","(","json",".","dumps","(","error",")",")","response",".","content_type","=","str","(","'application\/json; charset=UTF-8'",")","response",".","status_int","=","exc",".","code","return","response"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/errors.py#L64-L81"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/errors.py","language":"python","identifier":"http_forbidden","parameters":"(exc, request)","argument_list":"","return_statement":"return http_exception(exc, request)","docstring":"Raise HTTPUnauthorized exception.","docstring_summary":"Raise HTTPUnauthorized exception.","docstring_tokens":["Raise","HTTPUnauthorized","exception","."],"function":"def http_forbidden(exc, request):\n \"\"\"Raise HTTPUnauthorized exception.\"\"\"\n if request.authenticated_userid is None:\n exc = HTTPUnauthorized(explanation=\"Invalid credentials\")\n return http_exception(exc, request)","function_tokens":["def","http_forbidden","(","exc",",","request",")",":","if","request",".","authenticated_userid","is","None",":","exc","=","HTTPUnauthorized","(","explanation","=","\"Invalid credentials\"",")","return","http_exception","(","exc",",","request",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/errors.py#L85-L89"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/renderer.py","language":"python","identifier":"JSONEncoder.default","parameters":"(self, obj)","argument_list":"","return_statement":"return super(JSONEncoder, self).default(obj)","docstring":"Convert object to JSON encodable type.","docstring_summary":"Convert object to JSON encodable type.","docstring_tokens":["Convert","object","to","JSON","encodable","type","."],"function":"def default(self, obj):\n '''Convert object to JSON encodable type.'''\n if isinstance(obj, Decimal):\n return float(obj)\n if isinstance(obj, datetime.datetime):\n if obj.tzinfo is None:\n return str(obj.replace(tzinfo=pytz.utc))\n if isinstance(obj, datetime.date):\n return obj.isoformat()\n if isinstance(obj, UUID):\n return str(obj)\n return super(JSONEncoder, self).default(obj)","function_tokens":["def","default","(","self",",","obj",")",":","if","isinstance","(","obj",",","Decimal",")",":","return","float","(","obj",")","if","isinstance","(","obj",",","datetime",".","datetime",")",":","if","obj",".","tzinfo","is","None",":","return","str","(","obj",".","replace","(","tzinfo","=","pytz",".","utc",")",")","if","isinstance","(","obj",",","datetime",".","date",")",":","return","obj",".","isoformat","(",")","if","isinstance","(","obj",",","UUID",")",":","return","str","(","obj",")","return","super","(","JSONEncoder",",","self",")",".","default","(","obj",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/renderer.py#L33-L44"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/deserializer.py","language":"python","identifier":"json_deserializer","parameters":"(request)","argument_list":"","return_statement":"return request.body","docstring":"Manage json content type.","docstring_summary":"Manage json content type.","docstring_tokens":["Manage","json","content","type","."],"function":"def json_deserializer(request):\n \"\"\"Manage json content type.\"\"\"\n if request.json_body:\n return request.json_body\n return request.body","function_tokens":["def","json_deserializer","(","request",")",":","if","request",".","json_body",":","return","request",".","json_body","return","request",".","body"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/deserializer.py#L6-L10"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/context.py","language":"python","identifier":"DefaultContext.authenticated_user","parameters":"(self)","argument_list":"","return_statement":"return user","docstring":"Return the authenticated user.\n\n :return: authenticated user\n :rtype: dict","docstring_summary":"Return the authenticated user.","docstring_tokens":["Return","the","authenticated","user","."],"function":"def authenticated_user(self):\n \"\"\"\n Return the authenticated user.\n\n :return: authenticated user\n :rtype: dict\n \"\"\"\n user = self.request.authenticated_userid\n return user","function_tokens":["def","authenticated_user","(","self",")",":","user","=","self",".","request",".","authenticated_userid","return","user"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/context.py#L29-L37"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/config.py","language":"python","identifier":"swagger_error_view","parameters":"(exc, request)","argument_list":"","return_statement":"","docstring":"Format swagger validation error.","docstring_summary":"Format swagger validation error.","docstring_tokens":["Format","swagger","validation","error","."],"function":"def swagger_error_view(exc, request):\n \"\"\"Format swagger validation error.\"\"\"\n raise ValidationError(exc.child.message)","function_tokens":["def","swagger_error_view","(","exc",",","request",")",":","raise","ValidationError","(","exc",".","child",".","message",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/config.py#L22-L24"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/config.py","language":"python","identifier":"includeme","parameters":"(config)","argument_list":"","return_statement":"","docstring":"Configure REST API.","docstring_summary":"Configure REST API.","docstring_tokens":["Configure","REST","API","."],"function":"def includeme(config):\n \"\"\"Configure REST API.\"\"\"\n connect_storage()\n config.commit()\n\n # configure renderers\n config.add_renderer('text_plain', TextPlainRenderer)\n config.add_renderer('json', JsonRenderer)\n config.add_renderer('simplejson', JsonRenderer)\n config.add_renderer('part', PartRenderer)\n\n # configure specific views for API errors\n config.scan('caliopen_api.base.errors')\n config.add_cornice_deserializer('application\/json',\n json_deserializer)\n swagger_context = 'pyramid_swagger.exceptions.RequestValidationError'\n config.add_exception_view(context=swagger_context,\n view=swagger_error_view,\n renderer='json')\n config.commit()\n log.info('Base API configured')","function_tokens":["def","includeme","(","config",")",":","connect_storage","(",")","config",".","commit","(",")","# configure renderers","config",".","add_renderer","(","'text_plain'",",","TextPlainRenderer",")","config",".","add_renderer","(","'json'",",","JsonRenderer",")","config",".","add_renderer","(","'simplejson'",",","JsonRenderer",")","config",".","add_renderer","(","'part'",",","PartRenderer",")","# configure specific views for API errors","config",".","scan","(","'caliopen_api.base.errors'",")","config",".","add_cornice_deserializer","(","'application\/json'",",","json_deserializer",")","swagger_context","=","'pyramid_swagger.exceptions.RequestValidationError'","config",".","add_exception_view","(","context","=","swagger_context",",","view","=","swagger_error_view",",","renderer","=","'json'",")","config",".","commit","(",")","log",".","info","(","'Base API configured'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/base\/config.py#L27-L47"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/authentication.py","language":"python","identifier":"AuthenticatedUser._validate_signature","parameters":"(self, request, device_id, infos)","argument_list":"","return_statement":"","docstring":"Validate device signature.","docstring_summary":"Validate device signature.","docstring_tokens":["Validate","device","signature","."],"function":"def _validate_signature(self, request, device_id, infos):\n \"\"\"Validate device signature.\"\"\"\n if infos['curve'] == 'P-256':\n curve = ecdsa.ecdsa.curve_256\n crv = ecdsa.curves.NIST256p\n hashfunc = hashlib.sha256\n else:\n log.warn('Unsupported curve %r' % infos['curve'])\n return False\n try:\n point = ecdsa.ellipticcurve.Point(curve, infos['x'], infos['y'])\n except AssertionError:\n log.warn('Invalid curve points')\n return False\n\n sign_header = request.headers.get('X-Caliopen-Device-Signature', None)\n if sign_header:\n data = '{}{}{}'.format(request.method, request.path_qs, '')\n try:\n b64_header = base64.decodestring(sign_header)\n ecdsasign = EcdsaSignature.load(b64_header)\n signature = ecdsasign['r'].contents + ecdsasign['s'].contents\n vk = ecdsa.VerifyingKey.from_public_point(point, crv,\n hashfunc=hashfunc)\n return vk.verify(signature, data)\n except ecdsa.BadSignatureError:\n pass\n except Exception as exc:\n log.error('Exception during signature verification %r' % exc)\n return False\n else:\n log.warn('no device signature')\n return False","function_tokens":["def","_validate_signature","(","self",",","request",",","device_id",",","infos",")",":","if","infos","[","'curve'","]","==","'P-256'",":","curve","=","ecdsa",".","ecdsa",".","curve_256","crv","=","ecdsa",".","curves",".","NIST256p","hashfunc","=","hashlib",".","sha256","else",":","log",".","warn","(","'Unsupported curve %r'","%","infos","[","'curve'","]",")","return","False","try",":","point","=","ecdsa",".","ellipticcurve",".","Point","(","curve",",","infos","[","'x'","]",",","infos","[","'y'","]",")","except","AssertionError",":","log",".","warn","(","'Invalid curve points'",")","return","False","sign_header","=","request",".","headers",".","get","(","'X-Caliopen-Device-Signature'",",","None",")","if","sign_header",":","data","=","'{}{}{}'",".","format","(","request",".","method",",","request",".","path_qs",",","''",")","try",":","b64_header","=","base64",".","decodestring","(","sign_header",")","ecdsasign","=","EcdsaSignature",".","load","(","b64_header",")","signature","=","ecdsasign","[","'r'","]",".","contents","+","ecdsasign","[","'s'","]",".","contents","vk","=","ecdsa",".","VerifyingKey",".","from_public_point","(","point",",","crv",",","hashfunc","=","hashfunc",")","return","vk",".","verify","(","signature",",","data",")","except","ecdsa",".","BadSignatureError",":","pass","except","Exception","as","exc",":","log",".","error","(","'Exception during signature verification %r'","%","exc",")","return","False","else",":","log",".","warn","(","'no device signature'",")","return","False"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/authentication.py#L99-L131"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/authentication.py","language":"python","identifier":"AuthenticationPolicy.remember","parameters":"(self, request, principal, **kw)","argument_list":"","return_statement":"return []","docstring":"Token Key mechanism can't remember anyone.","docstring_summary":"Token Key mechanism can't remember anyone.","docstring_tokens":["Token","Key","mechanism","can","t","remember","anyone","."],"function":"def remember(self, request, principal, **kw):\n \"\"\"Token Key mechanism can't remember anyone.\"\"\"\n return []","function_tokens":["def","remember","(","self",",","request",",","principal",",","*","*","kw",")",":","return","[","]"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/authentication.py#L182-L184"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/user.py","language":"python","identifier":"get_device_sig_key","parameters":"(user, device)","argument_list":"","return_statement":"return None","docstring":"Get device signature key.","docstring_summary":"Get device signature key.","docstring_tokens":["Get","device","signature","key","."],"function":"def get_device_sig_key(user, device):\n \"\"\"Get device signature key.\"\"\"\n keys = PublicKey._model_class.filter(user_id=user.user_id,\n resource_id=device.device_id)\n keys = [x for x in keys if x.resource_type == 'device' and\n x.use == 'sig']\n if keys:\n return keys[0]\n return None","function_tokens":["def","get_device_sig_key","(","user",",","device",")",":","keys","=","PublicKey",".","_model_class",".","filter","(","user_id","=","user",".","user_id",",","resource_id","=","device",".","device_id",")","keys","=","[","x","for","x","in","keys","if","x",".","resource_type","==","'device'","and","x",".","use","==","'sig'","]","if","keys",":","return","keys","[","0","]","return","None"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/user.py#L35-L43"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/user.py","language":"python","identifier":"patch_device_key","parameters":"(key, param)","argument_list":"","return_statement":"return False","docstring":"Patch a device signature public key as X and Y points are not valid.","docstring_summary":"Patch a device signature public key as X and Y points are not valid.","docstring_tokens":["Patch","a","device","signature","public","key","as","X","and","Y","points","are","not","valid","."],"function":"def patch_device_key(key, param):\n \"\"\"Patch a device signature public key as X and Y points are not valid.\"\"\"\n if not key.x and not key.y:\n key.x = int(param['ecdsa_key']['x'], 16)\n key.y = int(param['ecdsa_key']['y'], 16)\n key.save()\n return True\n return False","function_tokens":["def","patch_device_key","(","key",",","param",")",":","if","not","key",".","x","and","not","key",".","y",":","key",".","x","=","int","(","param","[","'ecdsa_key'","]","[","'x'","]",",","16",")","key",".","y","=","int","(","param","[","'ecdsa_key'","]","[","'y'","]",",","16",")","key",".","save","(",")","return","True","return","False"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/user.py#L46-L53"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/user.py","language":"python","identifier":"make_user_device_tokens","parameters":"(request, user, device, key, ttl=86400)","argument_list":"","return_statement":"return result","docstring":"Return (key, tokens) informations for cache entry management.","docstring_summary":"Return (key, tokens) informations for cache entry management.","docstring_tokens":["Return","(","key","tokens",")","informations","for","cache","entry","management","."],"function":"def make_user_device_tokens(request, user, device, key, ttl=86400):\n \"\"\"Return (key, tokens) informations for cache entry management.\"\"\"\n cache_key = '{}-{}'.format(user.user_id, device.device_id)\n\n previous = request.cache.get(cache_key)\n if previous:\n status = previous.get('user_status', 'unknown')\n log.info('Found current user device entry {} : {}'.\n format(cache_key, status))\n if status in ['locked', 'maintenance']:\n raise AuthenticationError('Status {} does not permit operations'.\n format(status))\n\n access_token = create_token()\n refresh_token = create_token(80)\n\n expires_at = (datetime.datetime.utcnow() +\n datetime.timedelta(seconds=ttl))\n\n tokens = {'access_token': access_token,\n 'refresh_token': refresh_token,\n 'expires_in': ttl, # TODO : remove this value\n 'shard_id': user.shard_id,\n 'expires_at': expires_at.isoformat(),\n 'user_status': 'active',\n 'key_id': str(key.key_id),\n 'x': key.x,\n 'y': key.y,\n 'curve': key.crv}\n\n request.cache.set(cache_key, tokens)\n result = tokens.copy()\n result.pop('shard_id')\n return result","function_tokens":["def","make_user_device_tokens","(","request",",","user",",","device",",","key",",","ttl","=","86400",")",":","cache_key","=","'{}-{}'",".","format","(","user",".","user_id",",","device",".","device_id",")","previous","=","request",".","cache",".","get","(","cache_key",")","if","previous",":","status","=","previous",".","get","(","'user_status'",",","'unknown'",")","log",".","info","(","'Found current user device entry {} : {}'",".","format","(","cache_key",",","status",")",")","if","status","in","[","'locked'",",","'maintenance'","]",":","raise","AuthenticationError","(","'Status {} does not permit operations'",".","format","(","status",")",")","access_token","=","create_token","(",")","refresh_token","=","create_token","(","80",")","expires_at","=","(","datetime",".","datetime",".","utcnow","(",")","+","datetime",".","timedelta","(","seconds","=","ttl",")",")","tokens","=","{","'access_token'",":","access_token",",","'refresh_token'",":","refresh_token",",","'expires_in'",":","ttl",",","# TODO : remove this value","'shard_id'",":","user",".","shard_id",",","'expires_at'",":","expires_at",".","isoformat","(",")",",","'user_status'",":","'active'",",","'key_id'",":","str","(","key",".","key_id",")",",","'x'",":","key",".","x",",","'y'",":","key",".","y",",","'curve'",":","key",".","crv","}","request",".","cache",".","set","(","cache_key",",","tokens",")","result","=","tokens",".","copy","(",")","result",".","pop","(","'shard_id'",")","return","result"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/user.py#L56-L89"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/user.py","language":"python","identifier":"no_such_user","parameters":"(request)","argument_list":"","return_statement":"","docstring":"Validator that an user does not exist.","docstring_summary":"Validator that an user does not exist.","docstring_tokens":["Validator","that","an","user","does","not","exist","."],"function":"def no_such_user(request):\n \"\"\"Validator that an user does not exist.\"\"\"\n username = request.swagger_data['user']['username']\n if not User.is_username_available(username):\n raise NotAcceptable(detail='User already exist')","function_tokens":["def","no_such_user","(","request",")",":","username","=","request",".","swagger_data","[","'user'","]","[","'username'","]","if","not","User",".","is_username_available","(","username",")",":","raise","NotAcceptable","(","detail","=","'User already exist'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/user.py#L163-L167"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/config.py","language":"python","identifier":"includeme","parameters":"(config)","argument_list":"","return_statement":"","docstring":"Configure REST API for user and contact.","docstring_summary":"Configure REST API for user and contact.","docstring_tokens":["Configure","REST","API","for","user","and","contact","."],"function":"def includeme(config):\n \"\"\"Configure REST API for user and contact.\"\"\"\n config.set_authentication_policy(AuthenticationPolicy())\n config.set_authorization_policy(AuthorizationPolicy())\n log.debug('Loading user API')\n config.scan('caliopen_api.user.user')\n\n log.debug('Loading contact API')\n config.scan('caliopen_api.user.contact')\n\n log.debug('Loading imports API')\n config.scan('caliopen_api.user.imports')\n\n log.debug('Loading settings API')\n config.scan('caliopen_api.user.settings')","function_tokens":["def","includeme","(","config",")",":","config",".","set_authentication_policy","(","AuthenticationPolicy","(",")",")","config",".","set_authorization_policy","(","AuthorizationPolicy","(",")",")","log",".","debug","(","'Loading user API'",")","config",".","scan","(","'caliopen_api.user.user'",")","log",".","debug","(","'Loading contact API'",")","config",".","scan","(","'caliopen_api.user.contact'",")","log",".","debug","(","'Loading imports API'",")","config",".","scan","(","'caliopen_api.user.imports'",")","log",".","debug","(","'Loading settings API'",")","config",".","scan","(","'caliopen_api.user.settings'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/user\/config.py#L11-L25"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/discussion\/config.py","language":"python","identifier":"includeme","parameters":"(config)","argument_list":"","return_statement":"","docstring":"Serve discussion related REST API.","docstring_summary":"Serve discussion related REST API.","docstring_tokens":["Serve","discussion","related","REST","API","."],"function":"def includeme(config):\n \"\"\"\n Serve discussion related REST API.\n \"\"\"\n\n config.commit()\n\n log.debug('Loading participants discussion API')\n config.scan('caliopen_api.discussion.participants')","function_tokens":["def","includeme","(","config",")",":","config",".","commit","(",")","log",".","debug","(","'Loading participants discussion API'",")","config",".","scan","(","'caliopen_api.discussion.participants'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/discussion\/config.py#L9-L17"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/message\/config.py","language":"python","identifier":"includeme","parameters":"(config)","argument_list":"","return_statement":"","docstring":"Serve message and discussion REST API.","docstring_summary":"Serve message and discussion REST API.","docstring_tokens":["Serve","message","and","discussion","REST","API","."],"function":"def includeme(config):\n \"\"\"\n Serve message and discussion REST API.\n \"\"\"\n\n config.commit()\n\n # Activate cornice in any case and scan\n log.debug('Loading message API')\n config.scan('caliopen_api.message.message')","function_tokens":["def","includeme","(","config",")",":","config",".","commit","(",")","# Activate cornice in any case and scan","log",".","debug","(","'Loading message API'",")","config",".","scan","(","'caliopen_api.message.message'",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/src\/backend\/interfaces\/REST\/py.server\/caliopen_api\/message\/config.py#L9-L18"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"devtools\/migrations\/index_migration_v4_to_v5.py","language":"python","identifier":"IndexMigrator.create_new_index","parameters":"(self, index)","argument_list":"","return_statement":"","docstring":"Create user index and setups mappings.","docstring_summary":"Create user index and setups mappings.","docstring_tokens":["Create","user","index","and","setups","mappings","."],"function":"def create_new_index(self, index):\n \"\"\"Create user index and setups mappings.\"\"\"\n log.info('Creating new index {}'.format(index))\n\n try:\n self.es_client.indices.create(\n index=index,\n timeout='30s',\n body={\n \"settings\": {\n \"index\": {\n \"number_of_shards\": 3,\n },\n \"analysis\": {\n \"analyzer\": {\n \"text_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"lowercase\",\n \"filter\": [\n \"ascii_folding\"\n ]\n },\n \"email_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"email_tokenizer\",\n \"filter\": [\n \"ascii_folding\"\n ]\n }\n },\n \"filter\": {\n \"ascii_folding\": {\n \"type\": \"asciifolding\",\n \"preserve_original\": True\n }\n },\n \"tokenizer\": {\n \"email_tokenizer\": {\n \"type\": \"ngram\",\n \"min_gram\": 3,\n \"max_gram\": 25\n }\n }\n }\n }\n })\n except Exception as exc:\n log.error(\"failed to create index {} :\u00a0{}\".format(index, exc))\n raise exc\n\n # PUT\u00a0mappings for each type\n for kls in self.types:\n kls._index_class().create_mapping(index)","function_tokens":["def","create_new_index","(","self",",","index",")",":","log",".","info","(","'Creating new index {}'",".","format","(","index",")",")","try",":","self",".","es_client",".","indices",".","create","(","index","=","index",",","timeout","=","'30s'",",","body","=","{","\"settings\"",":","{","\"index\"",":","{","\"number_of_shards\"",":","3",",","}",",","\"analysis\"",":","{","\"analyzer\"",":","{","\"text_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"lowercase\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}",",","\"email_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"email_tokenizer\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}","}",",","\"filter\"",":","{","\"ascii_folding\"",":","{","\"type\"",":","\"asciifolding\"",",","\"preserve_original\"",":","True","}","}",",","\"tokenizer\"",":","{","\"email_tokenizer\"",":","{","\"type\"",":","\"ngram\"",",","\"min_gram\"",":","3",",","\"max_gram\"",":","25","}","}","}","}","}",")","except","Exception","as","exc",":","log",".","error","(","\"failed to create index {} :\u00a0{}\".","f","ormat(","i","ndex,"," ","xc)",")","","raise","exc","# PUT\u00a0mappings for each type","for","kls","in","self",".","types",":","kls",".","_index_class","(",")",".","create_mapping","(","index",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/devtools\/migrations\/index_migration_v4_to_v5.py#L87-L139"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"devtools\/migrations\/index_migration_v4_to_v5.py","language":"python","identifier":"IndexMigrator.fill_date_sort","parameters":"(self, index)","argument_list":"","return_statement":"","docstring":"fill_date_sort updates all message docs in index\n with either message's date or date_insert into date_sort,\n depending of message being received or sent\n\n :param index: Elasticsearch index\n :return: None","docstring_summary":"fill_date_sort updates all message docs in index\n with either message's date or date_insert into date_sort,\n depending of message being received or sent","docstring_tokens":["fill_date_sort","updates","all","message","docs","in","index","with","either","message","s","date","or","date_insert","into","date_sort","depending","of","message","being","received","or","sent"],"function":"def fill_date_sort(self, index):\n \"\"\"\n fill_date_sort updates all message docs in index\n with either message's date or date_insert into date_sort,\n depending of message being received or sent\n\n :param index: Elasticsearch index\n :return: None\n \"\"\"\n log.info(\"filling date_sort prop for index {}\".format(index))\n q = {\n \"script\": {\n \"lang\": \"painless\",\n \"inline\": \"if (ctx._source.is_received) {ctx._source.date_sort = ctx._source.date_insert} else {ctx._source.date_sort = ctx._source.date}\"\n }\n }\n try:\n resp = requests.post(self.url + \"\/\" + index + \"\/indexed_message\/_update_by_query\", data=json.dumps(q), headers={'content-type': 'application\/json'})\n log.info(\"{} docs updated in {}\".format(resp.json()[\"updated\"], index))\n except Exception as exc:\n log.error(\n \"failed to update_by_query index {} : {}\".format(index, exc))","function_tokens":["def","fill_date_sort","(","self",",","index",")",":","log",".","info","(","\"filling date_sort prop for index {}\"",".","format","(","index",")",")","q","=","{","\"script\"",":","{","\"lang\"",":","\"painless\"",",","\"inline\"",":","\"if (ctx._source.is_received) {ctx._source.date_sort = ctx._source.date_insert} else {ctx._source.date_sort = ctx._source.date}\"","}","}","try",":","resp","=","requests",".","post","(","self",".","url","+","\"\/\"","+","index","+","\"\/indexed_message\/_update_by_query\"",",","data","=","json",".","dumps","(","q",")",",","headers","=","{","'content-type'",":","'application\/json'","}",")","log",".","info","(","\"{} docs updated in {}\"",".","format","(","resp",".","json","(",")","[","\"updated\"","]",",","index",")",")","except","Exception","as","exc",":","log",".","error","(","\"failed to update_by_query index {} : {}\"",".","format","(","index",",","exc",")",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/devtools\/migrations\/index_migration_v4_to_v5.py#L178-L199"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"devtools\/migrations\/index_migration_v5_to_v6.py","language":"python","identifier":"IndexMigrator.create_new_index","parameters":"(self, index)","argument_list":"","return_statement":"","docstring":"Create user index and setups mappings.","docstring_summary":"Create user index and setups mappings.","docstring_tokens":["Create","user","index","and","setups","mappings","."],"function":"def create_new_index(self, index):\n \"\"\"Create user index and setups mappings.\"\"\"\n log.info('Creating new index {}'.format(index))\n\n try:\n self.es_client.indices.create(\n index=index,\n timeout='30s',\n body={\n \"settings\": {\n \"index\": {\n \"number_of_shards\": 3,\n },\n \"analysis\": {\n \"analyzer\": {\n \"text_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"lowercase\",\n \"filter\": [\n \"ascii_folding\"\n ]\n },\n \"email_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"email_tokenizer\",\n \"filter\": [\n \"ascii_folding\"\n ]\n }\n },\n \"filter\": {\n \"ascii_folding\": {\n \"type\": \"asciifolding\",\n \"preserve_original\": True\n }\n },\n \"tokenizer\": {\n \"email_tokenizer\": {\n \"type\": \"ngram\",\n \"min_gram\": 3,\n \"max_gram\": 25\n }\n }\n }\n }\n })\n except Exception as exc:\n log.error(\"failed to create index {} :\u00a0{}\".format(index, exc))\n raise exc\n\n # PUT\u00a0mappings for each type\n for kls in self.types:\n kls._index_class().create_mapping(index)","function_tokens":["def","create_new_index","(","self",",","index",")",":","log",".","info","(","'Creating new index {}'",".","format","(","index",")",")","try",":","self",".","es_client",".","indices",".","create","(","index","=","index",",","timeout","=","'30s'",",","body","=","{","\"settings\"",":","{","\"index\"",":","{","\"number_of_shards\"",":","3",",","}",",","\"analysis\"",":","{","\"analyzer\"",":","{","\"text_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"lowercase\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}",",","\"email_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"email_tokenizer\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}","}",",","\"filter\"",":","{","\"ascii_folding\"",":","{","\"type\"",":","\"asciifolding\"",",","\"preserve_original\"",":","True","}","}",",","\"tokenizer\"",":","{","\"email_tokenizer\"",":","{","\"type\"",":","\"ngram\"",",","\"min_gram\"",":","3",",","\"max_gram\"",":","25","}","}","}","}","}",")","except","Exception","as","exc",":","log",".","error","(","\"failed to create index {} :\u00a0{}\".","f","ormat(","i","ndex,"," ","xc)",")","","raise","exc","# PUT\u00a0mappings for each type","for","kls","in","self",".","types",":","kls",".","_index_class","(",")",".","create_mapping","(","index",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/devtools\/migrations\/index_migration_v5_to_v6.py#L84-L136"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"devtools\/migrations\/index_migration_v0_to_v2.py","language":"python","identifier":"IndexMigrator.create_new_index","parameters":"(self, index)","argument_list":"","return_statement":"","docstring":"Creates user index and setups mappings.","docstring_summary":"Creates user index and setups mappings.","docstring_tokens":["Creates","user","index","and","setups","mappings","."],"function":"def create_new_index(self, index):\n \"\"\"Creates user index and setups mappings.\"\"\"\n log.warn('Creating new index {}'.format(index))\n\n try:\n self.es_client.indices.create(\n index=index,\n body={\n \"settings\": {\n \"analysis\": {\n \"analyzer\": {\n \"text_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"lowercase\",\n \"filter\": [\n \"ascii_folding\"\n ]\n },\n \"email_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"email_tokenizer\",\n \"filter\": [\n \"ascii_folding\"\n ]\n }\n },\n \"filter\": {\n \"ascii_folding\": {\n \"type\": \"asciifolding\",\n \"preserve_original\": True\n }\n },\n \"tokenizer\": {\n \"email_tokenizer\": {\n \"type\": \"ngram\",\n \"min_gram\": 3,\n \"max_gram\": 25\n }\n }\n }\n }\n })\n except Exception as exc:\n log.error(\"failed to create index {} :\u00a0{}\".format(index, exc))\n raise exc\n\n # PUT\u00a0mappings for each type\n for kls in self.types:\n kls._index_class().create_mapping(index)","function_tokens":["def","create_new_index","(","self",",","index",")",":","log",".","warn","(","'Creating new index {}'",".","format","(","index",")",")","try",":","self",".","es_client",".","indices",".","create","(","index","=","index",",","body","=","{","\"settings\"",":","{","\"analysis\"",":","{","\"analyzer\"",":","{","\"text_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"lowercase\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}",",","\"email_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"email_tokenizer\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}","}",",","\"filter\"",":","{","\"ascii_folding\"",":","{","\"type\"",":","\"asciifolding\"",",","\"preserve_original\"",":","True","}","}",",","\"tokenizer\"",":","{","\"email_tokenizer\"",":","{","\"type\"",":","\"ngram\"",",","\"min_gram\"",":","3",",","\"max_gram\"",":","25","}","}","}","}","}",")","except","Exception","as","exc",":","log",".","error","(","\"failed to create index {} :\u00a0{}\".","f","ormat(","i","ndex,"," ","xc)",")","","raise","exc","# PUT\u00a0mappings for each type","for","kls","in","self",".","types",":","kls",".","_index_class","(",")",".","create_mapping","(","index",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/devtools\/migrations\/index_migration_v0_to_v2.py#L47-L95"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"devtools\/migrations\/index_migration_v3_to_v4.py","language":"python","identifier":"IndexMigrator.create_new_index","parameters":"(self, index)","argument_list":"","return_statement":"","docstring":"Create user index and setups mappings.","docstring_summary":"Create user index and setups mappings.","docstring_tokens":["Create","user","index","and","setups","mappings","."],"function":"def create_new_index(self, index):\n \"\"\"Create user index and setups mappings.\"\"\"\n log.warn('Creating new index {}'.format(index))\n\n try:\n self.es_client.indices.create(\n index=index,\n timeout='30s',\n body={\n \"settings\": {\n \"index\": {\n \"number_of_shards\": 3,\n },\n \"analysis\": {\n \"analyzer\": {\n \"text_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"lowercase\",\n \"filter\": [\n \"ascii_folding\"\n ]\n },\n \"email_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"email_tokenizer\",\n \"filter\": [\n \"ascii_folding\"\n ]\n }\n },\n \"filter\": {\n \"ascii_folding\": {\n \"type\": \"asciifolding\",\n \"preserve_original\": True\n }\n },\n \"tokenizer\": {\n \"email_tokenizer\": {\n \"type\": \"ngram\",\n \"min_gram\": 3,\n \"max_gram\": 25\n }\n }\n }\n }\n })\n except Exception as exc:\n log.error(\"failed to create index {} :\u00a0{}\".format(index, exc))\n raise exc\n\n # PUT\u00a0mappings for each type\n for kls in self.types:\n kls._index_class().create_mapping(index)","function_tokens":["def","create_new_index","(","self",",","index",")",":","log",".","warn","(","'Creating new index {}'",".","format","(","index",")",")","try",":","self",".","es_client",".","indices",".","create","(","index","=","index",",","timeout","=","'30s'",",","body","=","{","\"settings\"",":","{","\"index\"",":","{","\"number_of_shards\"",":","3",",","}",",","\"analysis\"",":","{","\"analyzer\"",":","{","\"text_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"lowercase\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}",",","\"email_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"email_tokenizer\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}","}",",","\"filter\"",":","{","\"ascii_folding\"",":","{","\"type\"",":","\"asciifolding\"",",","\"preserve_original\"",":","True","}","}",",","\"tokenizer\"",":","{","\"email_tokenizer\"",":","{","\"type\"",":","\"ngram\"",",","\"min_gram\"",":","3",",","\"max_gram\"",":","25","}","}","}","}","}",")","except","Exception","as","exc",":","log",".","error","(","\"failed to create index {} :\u00a0{}\".","f","ormat(","i","ndex,"," ","xc)",")","","raise","exc","# PUT\u00a0mappings for each type","for","kls","in","self",".","types",":","kls",".","_index_class","(",")",".","create_mapping","(","index",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/devtools\/migrations\/index_migration_v3_to_v4.py#L80-L132"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"devtools\/migrations\/index_migration_v2_to_v3.py","language":"python","identifier":"IndexMigrator.create_new_index","parameters":"(self, index)","argument_list":"","return_statement":"","docstring":"Create user index and setups mappings.","docstring_summary":"Create user index and setups mappings.","docstring_tokens":["Create","user","index","and","setups","mappings","."],"function":"def create_new_index(self, index):\n \"\"\"Create user index and setups mappings.\"\"\"\n log.warn('Creating new index {}'.format(index))\n\n try:\n self.es_client.indices.create(\n index=index,\n timeout='30s',\n body={\n \"settings\": {\n \"index\": {\n \"number_of_shards\": 3,\n },\n \"analysis\": {\n \"analyzer\": {\n \"text_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"lowercase\",\n \"filter\": [\n \"ascii_folding\"\n ]\n },\n \"email_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"email_tokenizer\",\n \"filter\": [\n \"ascii_folding\"\n ]\n }\n },\n \"filter\": {\n \"ascii_folding\": {\n \"type\": \"asciifolding\",\n \"preserve_original\": True\n }\n },\n \"tokenizer\": {\n \"email_tokenizer\": {\n \"type\": \"ngram\",\n \"min_gram\": 3,\n \"max_gram\": 25\n }\n }\n }\n }\n })\n except Exception as exc:\n log.error(\"failed to create index {} :\u00a0{}\".format(index, exc))\n raise exc\n\n # PUT\u00a0mappings for each type\n for kls in self.types:\n kls._index_class().create_mapping(index)","function_tokens":["def","create_new_index","(","self",",","index",")",":","log",".","warn","(","'Creating new index {}'",".","format","(","index",")",")","try",":","self",".","es_client",".","indices",".","create","(","index","=","index",",","timeout","=","'30s'",",","body","=","{","\"settings\"",":","{","\"index\"",":","{","\"number_of_shards\"",":","3",",","}",",","\"analysis\"",":","{","\"analyzer\"",":","{","\"text_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"lowercase\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}",",","\"email_analyzer\"",":","{","\"type\"",":","\"custom\"",",","\"tokenizer\"",":","\"email_tokenizer\"",",","\"filter\"",":","[","\"ascii_folding\"","]","}","}",",","\"filter\"",":","{","\"ascii_folding\"",":","{","\"type\"",":","\"asciifolding\"",",","\"preserve_original\"",":","True","}","}",",","\"tokenizer\"",":","{","\"email_tokenizer\"",":","{","\"type\"",":","\"ngram\"",",","\"min_gram\"",":","3",",","\"max_gram\"",":","25","}","}","}","}","}",")","except","Exception","as","exc",":","log",".","error","(","\"failed to create index {} :\u00a0{}\".","f","ormat(","i","ndex,"," ","xc)",")","","raise","exc","# PUT\u00a0mappings for each type","for","kls","in","self",".","types",":","kls",".","_index_class","(",")",".","create_mapping","(","index",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/devtools\/migrations\/index_migration_v2_to_v3.py#L80-L132"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"devtools\/extract\/email_graph.py","language":"python","identifier":"valid_uuid","parameters":"(uuid)","argument_list":"","return_statement":"return bool(match)","docstring":"Validate uuid value using regex.","docstring_summary":"Validate uuid value using regex.","docstring_tokens":["Validate","uuid","value","using","regex","."],"function":"def valid_uuid(uuid):\n \"\"\"Validate uuid value using regex.\"\"\"\n regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab]'\n '[a-f0-9]{3}-?[a-f0-9]{12}\\Z', re.I)\n match = regex.match(uuid)\n return bool(match)","function_tokens":["def","valid_uuid","(","uuid",")",":","regex","=","re",".","compile","(","'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab]'","'[a-f0-9]{3}-?[a-f0-9]{12}\\Z'",",","re",".","I",")","match","=","regex",".","match","(","uuid",")","return","bool","(","match",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/devtools\/extract\/email_graph.py#L17-L22"} {"nwo":"CaliOpen\/Caliopen","sha":"5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8","path":"devtools\/extract\/email_graph.py","language":"python","identifier":"anonymise_email","parameters":"(email)","argument_list":"","return_statement":"return '{0}@{1}'.format(hash_local, hash_domain)","docstring":"Anonymise email field using an hash function.","docstring_summary":"Anonymise email field using an hash function.","docstring_tokens":["Anonymise","email","field","using","an","hash","function","."],"function":"def anonymise_email(email):\n \"\"\"Anonymise email field using an hash function.\"\"\"\n # XXX do a better email formatting, even if it's supposed to be clean ...\n assert '@' in email, 'Invalid email {0}'.format(email)\n local_part, domain = email.split('@')\n hash_local = hashlib.sha256(local_part.encode('utf-8')).hexdigest()\n hash_domain = hashlib.sha256(domain.encode('utf-8')).hexdigest()\n return '{0}@{1}'.format(hash_local, hash_domain)","function_tokens":["def","anonymise_email","(","email",")",":","# XXX do a better email formatting, even if it's supposed to be clean ...","assert","'@'","in","email",",","'Invalid email {0}'",".","format","(","email",")","local_part",",","domain","=","email",".","split","(","'@'",")","hash_local","=","hashlib",".","sha256","(","local_part",".","encode","(","'utf-8'",")",")",".","hexdigest","(",")","hash_domain","=","hashlib",".","sha256","(","domain",".","encode","(","'utf-8'",")",")",".","hexdigest","(",")","return","'{0}@{1}'",".","format","(","hash_local",",","hash_domain",")"],"url":"https:\/\/github.com\/CaliOpen\/Caliopen\/blob\/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8\/devtools\/extract\/email_graph.py#L25-L32"}