Add ldap-jpeg.py script for viewing jpegPhotos.
authorW. Trevor King <wking@tremily.us>
Fri, 11 May 2012 13:50:38 +0000 (09:50 -0400)
committerW. Trevor King <wking@tremily.us>
Fri, 11 May 2012 13:50:38 +0000 (09:50 -0400)
Lots of duplicated code between this new script and mutt-ldap.py and
mailcap-test.py.  But these snippets seem to simple to be worth
reorganizing into a full-blown module.  Perhaps I should switch to
importable names?

posts/LDAP/ldap-jpeg.py [new file with mode: 0755]

diff --git a/posts/LDAP/ldap-jpeg.py b/posts/LDAP/ldap-jpeg.py
new file mode 100755 (executable)
index 0000000..3e816d8
--- /dev/null
@@ -0,0 +1,127 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2011-2012  W. Trevor King
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+"""LDAP jpegPhoto viewer using your mailcap-configured JPEG viewer.
+"""
+
+import ConfigParser as _configparser
+import itertools as _itertools
+import mailcap as _mailcap
+import mimetypes as _mimetypes
+import os as _os
+import os.path as _os_path
+import shlex as _shlex
+if not hasattr(_shlex, 'quote'):  # Python < 3.3
+    import pipes as _pipes
+    _shlex.quote = _pipes.quote
+import subprocess as _subprocess
+import tempfile as _tempfile
+
+import ldap as _ldap
+import ldap.sasl as _ldap_sasl
+
+CONFIG = _configparser.SafeConfigParser()  # from mutt-ldap.py
+CONFIG.add_section('connection')
+CONFIG.set('connection', 'server', 'domaincontroller.yourdomain.com')
+CONFIG.set('connection', 'port', '389')  # set to 636 for default over SSL
+CONFIG.set('connection', 'ssl', 'no')
+CONFIG.set('connection', 'basedn', 'ou=x co.,dc=example,dc=net')
+CONFIG.add_section('auth')
+CONFIG.set('auth', 'user', '')
+CONFIG.set('auth', 'password', '')
+CONFIG.set('auth', 'gssapi', 'no')
+CONFIG.read(_os_path.expanduser('~/.mutt-ldap.rc'))
+
+_CAPS = _mailcap.getcaps()  # from mailcap-test.py
+
+def connect():
+    """Duplicated from mutt-ldap.py"""
+    protocol = 'ldap'
+    if CONFIG.getboolean('connection', 'ssl'):
+        protocol = 'ldaps'
+    url = '%s://%s:%s' % (
+        protocol,
+        CONFIG.get('connection', 'server'),
+        CONFIG.get('connection', 'port'))
+    connection = _ldap.initialize(url)
+    if CONFIG.getboolean('auth', 'gssapi'):
+        sasl = _ldap_sasl.gssapi()
+        connection.sasl_interactive_bind_s('', sasl)
+    else:
+        connection.bind(
+            CONFIG.get('auth', 'user'),
+            CONFIG.get('auth', 'password'),
+            ldap.AUTH_SIMPLE)
+    return connection
+
+def search(query, connection=None):
+    """Duplicated from mutt-ldap.py"""
+    local_connection = False
+    try:
+        if not connection:
+            local_connection = True
+            connection = connect()
+        post = ''
+        if query:
+            post = '*'
+        filterstr = '(|%s)' % (
+            u' '.join([u'(%s=*%s%s)' % (field, query, post)
+                       for field in ['cn', 'rdn', 'uid', 'mail']]))
+        r = connection.search_s(
+            CONFIG.get('connection', 'basedn'),
+            _ldap.SCOPE_SUBTREE,
+            filterstr.encode('utf-8'))
+    finally:
+        if local_connection and connection:
+            connection.unbind()
+    return r
+
+def view(filename, mime=None):
+    """Duplicated from mailcap-test.py"""
+    if mime is None:
+        mime,encoding = _mimetypes.guess_type(filename)
+        if mime is None:
+            return 1
+        print('guessed {} for {}'.format(mime, filename))
+    match = _mailcap.findmatch(_CAPS, mime, filename=_shlex.quote(filename))
+    if match[0] is None:
+        return 1
+    print('view {} with {}'.format(filename, match[0]))
+    return _subprocess.call(match[0], shell=True)
+
+def view_entry_photo(entry):
+    cn,data = entry
+    if 'jpegPhoto' in data:
+        for jpeg in data['jpegPhoto']:
+            name = data['cn'][-1]
+            fd,filename = _tempfile.mkstemp(
+                prefix= name + '-', suffix='.jpeg')
+            try:
+                _os.write(fd, jpeg)
+                view(filename=filename, mime='image/jpeg')
+            finally:
+                _os.remove(filename)
+                pass
+
+
+if __name__ == '__main__':
+    import sys
+
+    query = unicode(' '.join(sys.argv[1:]), 'utf-8')
+    entries = search(query)
+    for entry in sorted(entries):
+        view_entry_photo(entry)