Merge remote branch 'remotes/elrond/dev/mount_storage'
[mediagoblin.git] / mediagoblin / util.py
index 4421bec4436b8b6e1b011a250899e97cc29c78b7..c9f4a0ac72a48d5264b3eb692ca93cd4fe75a7e9 100644 (file)
@@ -14,6 +14,8 @@
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import division
+
 from email.MIMEText import MIMEText
 import gettext
 import pkg_resources
@@ -21,9 +23,9 @@ import smtplib
 import sys
 import re
 import urllib
-from math import ceil
-from string import strip
+from math import ceil, floor
 import copy
+import wtforms
 
 from babel.localedata import exists
 import jinja2
@@ -36,6 +38,10 @@ from mediagoblin import mg_globals
 from mediagoblin import messages
 from mediagoblin.db.util import ObjectId
 
+from itertools import izip, count
+
+DISPLAY_IMAGE_FETCHING_ORDER = [u'medium', u'original', u'thumb']
+
 TESTS_ENABLED = False
 def _activate_testing():
     """
@@ -134,7 +140,16 @@ def render_to_response(request, template, context):
 
 def redirect(request, *args, **kwargs):
     """Returns a HTTPFound(), takes a request and then urlgen params"""
-    return exc.HTTPFound(location=request.urlgen(*args, **kwargs))
+    
+    querystring = None
+    if kwargs.get('querystring'):
+        querystring = kwargs.get('querystring')
+        del kwargs['querystring']
+
+    return exc.HTTPFound(
+        location=''.join([
+                request.urlgen(*args, **kwargs),
+                querystring if querystring else '']))
 
 
 def setup_user_in_request(request):
@@ -253,9 +268,9 @@ def send_email(from_addr, to_addrs, subject, message_body):
      - message_body: email body text
     """
     # TODO: make a mock mhost if testing is enabled
-    if TESTS_ENABLED or mg_globals.email_debug_mode:
+    if TESTS_ENABLED or mg_globals.app_config['email_debug_mode']:
         mhost = FakeMhost()
-    elif not mg_globals.email_debug_mode:
+    elif not mg_globals.app_config['email_debug_mode']:
         mhost = smtplib.SMTP()
 
     mhost.connect()
@@ -268,7 +283,7 @@ def send_email(from_addr, to_addrs, subject, message_body):
     if TESTS_ENABLED:
         EMAIL_TEST_INBOX.append(message)
 
-    if getattr(mg_globals, 'email_debug_mode', False):
+    if mg_globals.app_config['email_debug_mode']:
         print u"===== Email ====="
         print u"From address: %s" % message['From']
         print u"To addresses: %s" % message['To']
@@ -285,7 +300,7 @@ def send_email(from_addr, to_addrs, subject, message_body):
 
 
 TRANSLATIONS_PATH = pkg_resources.resource_filename(
-    'mediagoblin', 'translations')
+    'mediagoblin', 'i18n')
 
 
 def locale_to_lower_upper(locale):
@@ -370,21 +385,59 @@ def clean_html(html):
     return HTML_CLEANER.clean_html(html)
 
 
-TAGS_DELIMITER = u' '
-
-def convert_to_tag_list(tag_string):
+def convert_to_tag_list_of_dicts(tag_string):
     """
-    Filter input from a "tags" field,
+    Filter input from incoming string containing user tags,
 
     Strips trailing, leading, and internal whitespace, and also converts
-    the user input into an array of tags
+    the "tags" text into an array of tags
     """
+    taglist = []
     if tag_string:
-        taglist = []
+
+        # Strip out internal, trailing, and leading whitespace
         stripped_tag_string = u' '.join(tag_string.strip().split())
-        for tag in stripped_tag_string.split(TAGS_DELIMITER):
-            if tag.strip(): taglist.append(tag.strip())
-        return taglist
+
+        # Split the tag string into a list of tags
+        for tag in stripped_tag_string.split(
+                                       mg_globals.app_config['tags_delimiter']):
+
+            # Ignore empty or duplicate tags
+            if tag.strip() and tag.strip() not in [t['name'] for t in taglist]:
+
+                taglist.append({'name': tag.strip(),
+                                'slug': slugify(tag.strip())})
+    return taglist
+
+
+def media_tags_as_string(media_entry_tags):
+    """
+    Generate a string from a media item's tags, stored as a list of dicts
+
+    This is the opposite of convert_to_tag_list_of_dicts
+    """
+    media_tag_string = ''
+    if media_entry_tags:
+        media_tag_string = mg_globals.app_config['tags_delimiter'].join(
+                                      [tag['name'] for tag in media_entry_tags])
+    return media_tag_string
+
+TOO_LONG_TAG_WARNING = \
+    u'Tags must be shorter than %s characters.  Tags that are too long: %s'
+
+def tag_length_validator(form, field):
+    """
+    Make sure tags do not exceed the maximum tag length.
+    """
+    tags = convert_to_tag_list_of_dicts(field.data)
+    too_long_tags = [
+        tag['name'] for tag in tags
+        if len(tag['name']) > mg_globals.app_config['tags_max_length']]
+
+    if too_long_tags:
+        raise wtforms.ValidationError(
+            TOO_LONG_TAG_WARNING % (mg_globals.app_config['tags_max_length'], \
+                                    ', '.join(too_long_tags)))
 
 
 MARKDOWN_INSTANCE = markdown.Markdown(safe_mode='escape')
@@ -435,7 +488,8 @@ class Pagination(object):
     get actual data slice through __call__().
     """
 
-    def __init__(self, page, cursor, per_page=PAGINATION_DEFAULT_PER_PAGE):
+    def __init__(self, page, cursor, per_page=PAGINATION_DEFAULT_PER_PAGE,
+                 jump_to_id=False):
         """
         Initializes Pagination
 
@@ -443,11 +497,25 @@ class Pagination(object):
          - page: requested page
          - per_page: number of objects per page
          - cursor: db cursor 
+         - jump_to_id: ObjectId, sets the page to the page containing the object
+           with _id == jump_to_id.
         """
-        self.page = page    
+        self.page = page
         self.per_page = per_page
         self.cursor = cursor
         self.total_count = self.cursor.count()
+        self.active_id = None
+
+        if jump_to_id:
+            cursor = copy.copy(self.cursor)
+
+            for (doc, increment) in izip(cursor, count(0)):
+                if doc['_id'] == jump_to_id:
+                    self.page = 1 + int(floor(increment / self.per_page))
+
+                    self.active_id = jump_to_id
+                    break
+
 
     def __call__(self):
         """