Merge remote branch 'remotes/elrond/dev/mount_storage'
[mediagoblin.git] / mediagoblin / util.py
index 8bb90acf77c5c4875c724c576533a7923199a786..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,8 +23,7 @@ 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
 
@@ -37,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():
     """
@@ -135,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):
@@ -254,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()
@@ -269,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']
@@ -286,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):
@@ -371,7 +385,7 @@ def clean_html(html):
     return HTML_CLEANER.clean_html(html)
 
 
-def convert_to_tag_list(tag_string):
+def convert_to_tag_list_of_dicts(tag_string):
     """
     Filter input from incoming string containing user tags,
 
@@ -388,16 +402,26 @@ def convert_to_tag_list(tag_string):
         for tag in stripped_tag_string.split(
                                        mg_globals.app_config['tags_delimiter']):
 
-            # Do not permit duplicate tags
-            if tag.strip() and tag not in taglist:
+            # Ignore empty or duplicate tags
+            if tag.strip() and tag.strip() not in [t['name'] for t in taglist]:
 
-                if mg_globals.app_config['tags_case_sensitive']:
-                    taglist.append(tag.strip())
-                else:
-                    taglist.append(tag.strip().lower())
+                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'
 
@@ -405,10 +429,10 @@ def tag_length_validator(form, field):
     """
     Make sure tags do not exceed the maximum tag length.
     """
-    tags = convert_to_tag_list(field.data)
+    tags = convert_to_tag_list_of_dicts(field.data)
     too_long_tags = [
-        tag for tag in tags
-        if len(tag) > mg_globals.app_config['tags_max_length']]
+        tag['name'] for tag in tags
+        if len(tag['name']) > mg_globals.app_config['tags_max_length']]
 
     if too_long_tags:
         raise wtforms.ValidationError(
@@ -464,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
 
@@ -472,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):
         """