<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[12115] twext/trunk/twext/who/opendirectory/service.py</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/12115">12115</a></dd>
<dt>Author</dt> <dd>wsanchez@apple.com</dd>
<dt>Date</dt> <dd>2013-12-16 18:33:52 -0800 (Mon, 16 Dec 2013)</dd>
</dl>

<h3>Log Message</h3>
<pre>Remove dependency on opendirectory.py.  Woot.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#twexttrunktwextwhoopendirectoryservicepy">twext/trunk/twext/who/opendirectory/service.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="twexttrunktwextwhoopendirectoryservicepy"></a>
<div class="modfile"><h4>Modified: twext/trunk/twext/who/opendirectory/service.py (12114 => 12115)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/who/opendirectory/service.py        2013-12-17 00:16:53 UTC (rev 12114)
+++ twext/trunk/twext/who/opendirectory/service.py        2013-12-17 02:33:52 UTC (rev 12115)
</span><span class="lines">@@ -29,6 +29,8 @@
</span><span class="cx"> 
</span><span class="cx"> from itertools import chain
</span><span class="cx"> 
</span><ins>+import odframework
+
</ins><span class="cx"> from twext.python.log import Logger
</span><span class="cx"> from twisted.python.constants import Names, NamedConstant
</span><span class="cx"> from twisted.python.constants import Values, ValueConstant
</span><span class="lines">@@ -46,14 +48,8 @@
</span><span class="cx"> from twext.who.expression import MatchExpression, MatchType, MatchFlags
</span><span class="cx"> from twext.who.util import iterFlags, ConstantsContainer
</span><span class="cx"> 
</span><del>-from opendirectory import (
-    ODError, odInit,
-    getNodeAttributes,
-    queryRecordsWithAttribute_list,
-)
</del><span class="cx"> 
</span><span class="cx"> 
</span><del>-
</del><span class="cx"> #
</span><span class="cx"> # Exceptions
</span><span class="cx"> #
</span><span class="lines">@@ -63,8 +59,26 @@
</span><span class="cx">     OpenDirectory error.
</span><span class="cx">     &quot;&quot;&quot;
</span><span class="cx"> 
</span><ins>+    def __init__(self, message, odError):
+        super(DirectoryService, self).__init__(message)
+        self.odError = odError
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+
+class OpenDirectoryConnectionError(OpenDirectoryError):
+    &quot;&quot;&quot;
+    OpenDirectory connection error.
+    &quot;&quot;&quot;
+
+
+
+class OpenDirectoryQueryError(OpenDirectoryError):
+    &quot;&quot;&quot;
+    OpenDirectory query error.
+    &quot;&quot;&quot;
+
+
+
</ins><span class="cx"> #
</span><span class="cx"> # Constants
</span><span class="cx"> #
</span><span class="lines">@@ -195,6 +209,11 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+class ODMatchFlags(Values):
+    caseInsensitive = ValueConstant(0x100)
+
+
+
</ins><span class="cx"> #
</span><span class="cx"> # Directory Service
</span><span class="cx"> #
</span><span class="lines">@@ -230,61 +249,85 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @property
</span><ins>+    def session(self):
+        &quot;&quot;&quot;
+        Get the underlying directory session.
+        &quot;&quot;&quot;
+        self._connect()
+        return self._session
+
+
+    @property
</ins><span class="cx">     def node(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Get the underlying (network) directory node.
</span><span class="cx">         &quot;&quot;&quot;
</span><del>-        if not hasattr(self, &quot;_node&quot;):
-            try:
-                self._node = odInit(self.nodeName)
-            except ODError, e:
-                self.log.error(
-                    &quot;OpenDirectory initialization error&quot;
-                    &quot;(node={source.nodeName}): {error}&quot;,
-                    error=e
-                )
-                raise OpenDirectoryError(e)
-
</del><ins>+        self._connect()
</ins><span class="cx">         return self._node
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    @property
-    def localNode(self):
</del><ins>+    # @property
+    # def localNode(self):
+    #     &quot;&quot;&quot;
+    #     Get the local node from the search path (if any), so that we can handle
+    #     it specially.
+    #     &quot;&quot;&quot;
+    #     if not hasattr(self, &quot;_localNode&quot;):
+    #         if self.nodeName == ODSearchPath.search.value:
+    #             result = getNodeAttributes(
+    #                 self.node, ODSearchPath.search.value,
+    #                 (ODAttribute.searchPath.value,)
+    #             )
+    #             if (
+    #                 ODSearchPath.local.value in
+    #                 result[ODAttribute.searchPath.value]
+    #             ):
+    #                 try:
+    #                     self._localNode = odInit(ODSearchPath.local.value)
+    #                 except ODError, e:
+    #                     self.log.error(
+    #                         &quot;Failed to open local node: {error}}&quot;,
+    #                         error=e,
+    #                     )
+    #                     raise OpenDirectoryError(e)
+    #             else:
+    #                 self._localNode = None
+
+    #         elif self.nodeName == ODSearchPath.local.value:
+    #             self._localNode = self.node
+
+    #         else:
+    #             self._localNode = None
+
+    #     return self._localNode
+
+
+    def _connect(self):
</ins><span class="cx">         &quot;&quot;&quot;
</span><del>-        Get the local node from the search path (if any), so that we can handle
-        it specially.
</del><ins>+        Connect to the directory server.
+
+        @raises: L{OpenDirectoryConnectionError} if unable to connect.
</ins><span class="cx">         &quot;&quot;&quot;
</span><del>-        if not hasattr(self, &quot;_localNode&quot;):
-            if self.nodeName == ODSearchPath.search.value:
-                result = getNodeAttributes(
-                    self.node, ODSearchPath.search.value,
-                    (ODAttribute.searchPath.value,)
-                )
-                if (
-                    ODSearchPath.local.value in
-                    result[ODAttribute.searchPath.value]
-                ):
-                    try:
-                        self._localNode = odInit(ODSearchPath.local.value)
-                    except ODError, e:
-                        self.log.error(
-                            &quot;Failed to open local node: {error}}&quot;,
-                            error=e,
-                        )
-                        raise OpenDirectoryError(e)
-                else:
-                    self._localNode = None
</del><ins>+        if not hasattr(self, &quot;_session&quot;):
+            session = odframework.ODSession.defaultSession()
</ins><span class="cx"> 
</span><del>-            elif self.nodeName == ODSearchPath.local.value:
-                self._localNode = self.node
</del><ins>+            node, error = odframework.ODNode.nodeWithSession_name_error_(
+                session, self.nodeName, None
+            )
</ins><span class="cx"> 
</span><del>-            else:
-                self._localNode = None
</del><ins>+            if error:
+                self.log.error(
+                    &quot;Error while trying to connect to OpenDirectory node &quot;
+                    &quot;{source.nodeName!r}: {error}&quot;,
+                    error=error
+                )
+                raise OpenDirectoryConnectionError(error)
</ins><span class="cx"> 
</span><del>-        return self._localNode
</del><ins>+            self._session = session
+            self._node = node
</ins><span class="cx"> 
</span><span class="cx"> 
</span><del>-    def recordsFromMatchExpression(self, expression):
</del><ins>+    def _queryFromMatchExpression(self, expression):
</ins><span class="cx">         if not isinstance(expression, MatchExpression):
</span><span class="cx">             raise TypeError(expression)
</span><span class="cx"> 
</span><span class="lines">@@ -294,92 +337,105 @@
</span><span class="cx">                 &quot;Unknown match type: {0}&quot;.format(matchType)
</span><span class="cx">             )
</span><span class="cx"> 
</span><del>-        caseInsensitive = (
-            MatchFlags.caseInsensitive in iterFlags(expression.flags)
-        )
</del><ins>+        if MatchFlags.caseInsensitive in iterFlags(expression.flags):
+            caseInsensitive = 0x100
+        else:
+            caseInsensitive = 0x0
</ins><span class="cx"> 
</span><span class="cx">         if expression.fieldName is self.fieldName.recordType:
</span><span class="cx">             raise NotImplementedError()
</span><ins>+
</ins><span class="cx">         else:
</span><del>-            results = queryRecordsWithAttribute_list(
-                self.node,
-                ODAttribute.fromFieldName(expression.fieldName).value,
-                expression.fieldValue.encode(&quot;utf-8&quot;),
-                matchType.value,
-                caseInsensitive,
-                [
-                    recordType.value
-                    for recordType in ODRecordType.iterconstants()
-                ],
-                [attr.value for attr in ODAttribute.iterconstants()],
</del><ins>+            recordTypes = [t.value for t in ODRecordType.iterconstants()]
+            attributes = [a.value for a in ODAttribute.iterconstants()]
+            maxResults = 0
+
+        query, error = odframework.ODQuery.queryWithNode_forRecordTypes_attribute_matchType_queryValues_returnAttributes_maximumResults_error_(
+            self.node,
+            recordTypes,
+            ODAttribute.fromFieldName(expression.fieldName).value,
+            matchType.value | caseInsensitive,
+            expression.fieldValue,
+            attributes,
+            maxResults,
+            None
+        )
+
+        if error:
+            self.log.error(
+                &quot;Error while forming OpenDirectory query: {error}&quot;,
+                error=error
</ins><span class="cx">             )
</span><ins>+            raise OpenDirectoryQueryError(error)
</ins><span class="cx"> 
</span><del>-        # def uniqueTupleFromAttribute(self, attribute):
-        #     if attribute:
-        #         if isinstance(attribute, bytes):
-        #             return (attribute,)
-        #         else:
-        #             s = set()
-        #             return tuple((
-        #                 (s.add(x), x)[1] for x in attribute if x not in s
-        #             ))
-        #     else:
-        #         return ()
</del><ins>+        return query
</ins><span class="cx"> 
</span><del>-        for (shortName, attributes) in results:
-            fields = {}
</del><span class="cx"> 
</span><del>-            for (key, value) in attributes.iteritems():
-                if key == FieldName.metaRecordName:
-                    # We get this field even though we did not ask for it...
-                    continue
</del><ins>+    def _adaptODRecord(self, odRecord):
+        details, error = odRecord.recordDetailsForAttributes_error_(None, None)
</ins><span class="cx"> 
</span><del>-                try:
-                    attribute = ODAttribute.lookupByValue(key)
-                except ValueError:
-                    self.log.debug(
-                        &quot;Got back unexpected attribute {attribute} &quot;
-                        &quot;for record with short name {shortName}&quot;,
-                        attribute=key, shortName=shortName
-                    )
-                    continue
-                fieldName = attribute.fieldName
</del><ins>+        if error:
+            self.log.error(
+                &quot;Error while reading OpenDirectory record: {error}&quot;,
+                error=error
+            )
+            raise OpenDirectoryQueryError(error)
</ins><span class="cx"> 
</span><del>-                try:
-                    if BaseFieldName.isMultiValue(fieldName):
-                        if type(value) is bytes:
-                            value = (value,)
-                        elif type(value) is not list:
-                            raise TypeError()
</del><ins>+        fields = {}
+        for name, values in details.iteritems():
+            if name == ODAttribute.metaRecordName.value:
+                # We get this field even though we did not ask for it...
+                continue
</ins><span class="cx"> 
</span><del>-                        fields[fieldName] = tuple(
-                            x.decode(&quot;utf-8&quot;) for x in value
-                        )
</del><ins>+            try:
+                attribute = ODAttribute.lookupByValue(name)
+            except ValueError:
+                self.log.debug(
+                    &quot;Unexpected OpenDirectory record attribute: {attribute}&quot;,
+                    attribute=name
+                )
+                continue
+            fieldName = attribute.fieldName
</ins><span class="cx"> 
</span><del>-                    else:
-                        if type(value) is list:
-                            assert len(value) == 1
-                            value = value[0]
-                        elif type(value) is not bytes:
-                            raise TypeError()
</del><ins>+            if type(values) is bytes:
+                values = (unicode(values),)
+            else:
+                values = [unicode(v) for v in values]
</ins><span class="cx"> 
</span><del>-                        if fieldName is self.fieldName.recordType:
-                            fields[fieldName] = ODRecordType.lookupByValue(
-                                value
-                            ).recordType
-                        else:
-                            fields[fieldName] = value.decode(&quot;utf-8&quot;)
</del><ins>+            if BaseFieldName.isMultiValue(fieldName):
+                fields[fieldName] = values
+            else:
+                assert len(values) == 1
</ins><span class="cx"> 
</span><del>-                except TypeError:
-                    raise AssertionError(
-                        &quot;Unexpected type {0} for attribute {1}&quot;
-                        .format(type(value), fieldName)
-                    )
</del><ins>+                if fieldName is self.fieldName.recordType:
+                    fields[fieldName] = ODRecordType.lookupByValue(
+                        values[0]
+                    ).recordType
+                else:
+                    fields[fieldName] = values[0]
</ins><span class="cx"> 
</span><ins>+        return DirectoryRecord(self, fields)
</ins><span class="cx"> 
</span><del>-            yield DirectoryRecord(self, fields)
</del><span class="cx"> 
</span><ins>+    def _recordsFromQuery(self, query):
+        odRecords, error = query.resultsAllowingPartial_error_(False, None)
</ins><span class="cx"> 
</span><ins>+        if error:
+            self.log.error(
+                &quot;Error while executing OpenDirectory query: {error}&quot;,
+                error=error
+            )
+            raise OpenDirectoryQueryError(error)
+
+        for odRecord in odRecords:
+            yield self._adaptODRecord(odRecord)
+
+
+    def recordsFromMatchExpression(self, expression):
+        query = self._queryFromMatchExpression(expression)
+        return self._recordsFromQuery(query)
+
+
</ins><span class="cx">     def recordsFromExpression(self, expression):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         This implementation can handle L{MatchExpression} expressions; other
</span><span class="lines">@@ -434,18 +490,22 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx"> if __name__ == &quot;__main__&quot;:
</span><ins>+    import sys
+
</ins><span class="cx">     service = DirectoryService()
</span><span class="cx">     print(
</span><span class="cx">         &quot;Service = {service}\n&quot;
</span><ins>+        &quot;Session = {service.session}\n&quot;
</ins><span class="cx">         &quot;Node = {service.node}\n&quot;
</span><del>-        &quot;Local node = {service.localNode}\n&quot;
</del><ins>+        # &quot;Local node = {service.localNode}\n&quot;
</ins><span class="cx">         .format(service=service)
</span><span class="cx">     )
</span><span class="cx"> 
</span><del>-    matchMorgen = MatchExpression(
-        service.fieldName.shortNames, u&quot;sagen&quot;,
-        matchType=MatchType.equals,
-    )
-    for record in service.recordsFromExpression(matchMorgen):
-        print(&quot;*&quot; * 80)
-        print(record.description())
</del><ins>+    for shortName in sys.argv:
+        matchMorgen = MatchExpression(
+            service.fieldName.shortNames, shortName,
+            matchType=MatchType.equals,
+        )
+        for record in service.recordsFromExpression(matchMorgen):
+            print(&quot;*&quot; * 80)
+            print(record.description())
</ins></span></pre>
</div>
</div>

</body>
</html>