Login

ultralize

Author:
catellar
Posted:
August 24, 2011
Language:
Python
Version:
1.3
Tags:
urlize parser dailymotion html vimeo urlze youtube url-to-image url-to-video
Score:
0 (after 0 ratings)

This is a function based on django's urlize modified to show different media based on their url. It supports images, links, mp3/ogg links, youtube videos, vimeo videos and dailymotion videos.

I added a switch called mini to have two modes to show things in different places. When mini is activated it will only parse the first url provided and discard the rest as well as limiting the height.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def ultralize(text, mini=False,trim_url_limit=None, nofollow=False, autoescape=False):
	text = unicodedata.normalize('NFKD', text).encode('ascii','ignore')
	trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
	safe_input = isinstance(text, SafeData)
	words = word_split_re.split(force_unicode(text))
	nofollow_attr = nofollow and ' rel="nofollow"' or ''
	has_stuff = False
	for i, word in enumerate(words):
		if word == "fun1":
			word = "http://bleachexile.com/exec/images/emoticons/th_funone3kk.gif"
		match = None
		if '.' in word or '@' in word or ':' in word:
			match = punctuation_re.match(word)
		if match:
			lead, middle, trail = match.groups()
			# Make URL we want to point to.
			url = None
			if middle.startswith('http://') or middle.startswith('https://'):
				url = urlquote(middle, safe='/&=:;#?+*')
			elif middle.startswith('www.') or ('@' not in middle and \
					middle and middle[0] in string.ascii_letters + string.digits and \
					(middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))):
				url = urlquote('http://%s' % middle, safe='/&=:;#?+*')
			elif '@' in middle and not ':' in middle and simple_email_re.match(middle):
				url = 'mailto:%s' % middle
				nofollow_attr = ''
			# Make link.
			if url:
				trimmed = trim_url(middle)
				ytregex = re.compile(r"^(http://)?(www\.)?(youtube\.com/watch\?v=)(?P<id>[A-Za-z0-9\-=_]{11})")
				vimeoregex = re.compile(r"^(http://)?(www\.)?(vimeo\.com/)(?P<id>\d+)")
				dmregex = re.compile(r"^(http://)?(www\.)?(dailymotion\.com/video/)(?P<id>[A-Za-z0-9]+)")
				ytmatch = ytregex.match(middle)
				vimeomatch = vimeoregex.match(middle)
				dmmatch = dmregex.match(middle)
				if ytmatch:
					video_id = ytmatch.group('id')
				if vimeomatch:
					video_id = vimeomatch.group('id')
				if dmmatch:
					video_id = dmmatch.group('id')
				if autoescape and not safe_input:
					lead, trail = escape(lead), escape(trail)
					url, trimmed = escape(url), escape(trimmed)
				if any(s in middle for s in ['.jpg', '.JPG', '.gif', '.GIF', '.bmp', '.BMP', '.png', '.PNG', '.jpeg', '.JPEG', 'gstatic.com/images']):
					if has_stuff and mini:
						middle = ''
					else:
						if mini:
							middle = '<a rel="lightbox" href="%s"><img class="contentimg" style="display:block; max-width:100%%;max-height:300px; padding-top:5px; margin-bottom:3px" src="%s"></a>' % (url, url)
						else:
							middle = '<a rel="lightbox" href="%s"><img class="contentimg" style="display:block; max-width:100%%;padding-top:5px; margin-bottom:3px" src="%s"></a>' % (url, url)
						has_stuff = True
				elif middle.startswith("http://www.youtube.com/watch?v=") or middle.startswith("www.youtube.com/watch?v="):
					if ytmatch:
						if has_stuff and mini:
							middle = ''
						else:
							middle = "<iframe style=\"display:block;padding-top:5px; margin-bottom:3px\" title=\"YouTube video player\" width=\"600\" height=\"365\" src=\"http://www.youtube.com/embed/%s\" frameborder=\"0\" allowfullscreen></iframe>" % (video_id + "?autohide=1&wmode=transparent")
							has_stuff = True
				elif middle.startswith("http://www.vimeo.com") or middle.startswith("www.vimeo.com") or middle.startswith("vimeo.com") or middle.startswith("http://vimeo.com"):
					if vimeomatch:
						if has_stuff and mini:
							middle = ''
						else:
							middle = "<iframe style='display:block;'src=\"http://player.vimeo.com/video/%s?title=0&amp;byline=0&amp;portrait=0\" width=\"600\" height=\"405\" frameborder=\"0\"></iframe>" % (video_id)
							has_stuff = True
				elif middle.startswith("http://www.dailymotion.com") or middle.startswith("www.dailymotion.com") or middle.startswith("dailymotion.com") or middle.startswith("http://dailymotion.com"):
					if dmmatch:
						if has_stuff and mini:
							middle = ''
						else:
							middle = "<iframe frameborder='0' width='560' height='315' src='http://www.dailymotion.com/embed/video/%s?width=560'></iframe>" % (video_id)
							has_stuff = True
				elif middle.endswith(".ogg") or middle.endswith(".mp3"):
					if has_stuff and mini:
						middle = ''
					else:
						middle = "<audio style=\"display:block;padding-top:5px; margin-bottom:6px\" src=\"%s\" controls=\"controls\"></audio>" % (url)
						has_stuff = True
				else:
					if has_stuff and mini:
						middle = ''
					else:
						middle = "<a style='display:block;' target='_blank' href='%s'%s>%s</a>" % (url, nofollow_attr, trimmed)
						has_stuff = True
				words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
			else:
				if safe_input:
					words[i] = mark_safe(word)
				elif autoescape:
					words[i] = escape(word)
		elif safe_input:
			words[i] = mark_safe(word)
		elif autoescape:
			words[i] = escape(word)
	return mark_safe(u''.join(words))

ultralize.is_safe=True
ultralize.needs_autoescape = True
ultralize = stringfilter(ultralize)
register.filter(ultralize)
ultralize = allow_lazy(ultralize, unicode)

More like this

  1. youtubize template tag by TheJester 8 years, 3 months ago
  2. "Youtube watch link to embed" custom tag. by I159 3 years, 10 months ago
  3. YouTube Template Filter by jgeewax 7 years, 1 month ago
  4. Get the youtube video thumbnail url template filter by fitoria 4 years, 9 months ago
  5. Template filter to convert timecodes into links by justin_h 5 years, 11 months ago

Comments

Cta (on December 28, 2011):

Nice, ty

#

Please login first before commenting.