Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

non-strict fixed width column on code

  • Loading branch information...
commit ed33b24810e6341eb29aaebfcc8234e27500a022 1 parent 606b563
Mime Čuvalo authored
Showing with 4,014 additions and 1,550 deletions.
  1. +72 −35 controllers/api.py
  2. +6 −4 controllers/auth.py
  3. +57 −29 controllers/base.py
  4. +2 −1  controllers/check_broken_links.py
  5. +57 −29 controllers/customize.py
  6. +53 −27 controllers/dashboard.py
  7. +4 −2 controllers/data_liberation.py
  8. +47 −26 controllers/facebook.py
  9. +12 −6 controllers/feed.py
  10. +6 −3 controllers/foaf.py
  11. +7 −5 controllers/google.py
  12. +14 −7 controllers/media.py
  13. +4 −3 controllers/oembed.py
  14. +2 −1  controllers/private.py
  15. +7 −3 controllers/push.py
  16. +59 −30 controllers/salmon.py
  17. +9 −5 controllers/search.py
  18. +21 −8 controllers/setup.py
  19. +2 −1  controllers/stats.py
  20. +57 −29 controllers/tumblr.py
  21. +58 −31 controllers/twitter.py
  22. +81 −41 controllers/uimodules.py
  23. +26 −12 controllers/upload.py
  24. +4 −2 controllers/users.py
  25. +138 −73 controllers/view.py
  26. +2 −1  controllers/webfinger.py
  27. +72 −33 helloworld.py
  28. +15 −3 license.txt
  29. +7 −3 logic/cache.py
  30. +8 −6 logic/constants.py
  31. +40 −20 logic/content.py
  32. +42 −24 logic/content_remote.py
  33. +29 −13 logic/media.py
  34. +2 −1  logic/pubsubhubbub_subscribe.py
  35. +22 −12 logic/smtp.py
  36. +14 −7 logic/socialize.py
  37. +25 −12 logic/url_factory.py
  38. +84 −39 logic/users.py
  39. +14 −7 models/base.py
  40. +62 −45 models/db.py
  41. +3 −2 models/validators.py
  42. +13 −6 readme.md
  43. +10 −5 setup/setup.py
  44. +4 −11 static/css/create.css
  45. +2 −1  static/html/error.html
  46. +27 −13 static/js/base.js
  47. +25 −13 static/js/cart.js
  48. +101 −49 static/js/create.js
  49. +108 −55 static/js/customize.js
  50. +27 −14 static/js/dragdrop.js
  51. +2 −1  static/js/hw_follow.js
  52. +6 −3 static/js/hw_reblog.js
  53. +56 −27 static/js/image_editor.js
  54. +26 −13 static/js/media.js
  55. +100 −46 static/js/moderate.js
  56. +9 −7 static/js/setup.js
  57. +58 −30 static/js/site.js
  58. +3 −1 static/js/slideshow.js
  59. +28 −14 static/js/thumbnails.js
  60. +7 −5 static/js/users.js
  61. +63 −29 static/js/wysiwyg.js
  62. +124 −60 static/js/wysiwyg_site.js
  63. +297 −77 templates/_create.html
  64. +47 −12 templates/_moderate.html
  65. +86 −8 templates/_sitemap.html
  66. +4 −2 templates/adult_content.html
  67. +33 −6 templates/album.html
  68. +25 −3 templates/archive.html
  69. +102 −26 templates/base.html
  70. +56 −9 templates/base_backend.html
  71. +68 −22 templates/base_content.html
  72. +19 −9 templates/check_broken_links.html
  73. +207 −51 templates/content.html
  74. +5 −2 templates/content_feed.html
  75. +225 −64 templates/customize.html
  76. +220 −48 templates/dashboard.html
  77. +13 −5 templates/data_liberation.html
  78. +8 −3 templates/error.html
  79. +82 −22 templates/feed.html
  80. +32 −12 templates/foaf.html
  81. +60 −7 templates/forum.html
  82. +7 −3 templates/host_meta.html
  83. +2 −1  templates/login.html
  84. +43 −8 templates/media.html
  85. +10 −5 templates/media_standalone.html
  86. +10 −2 templates/opensearch.html
  87. +4 −1 templates/redirect.html
  88. +24 −11 templates/search.html
  89. +53 −16 templates/setup.html
  90. +3 −1 templates/simple.html
  91. +19 −5 templates/slideshow.html
  92. +55 −13 templates/store.html
  93. +77 −21 templates/users.html
  94. +40 −16 templates/webfinger.html
  95. +11 −5 tools/prune_old_entries.py
  96. +9 −4 tools/rando.py
  97. +13 −6 tools/update_feeds.py
107 controllers/api.py
View
@@ -100,7 +100,8 @@ def embed(self):
os.makedirs(parent_directory)
response = urllib2.urlopen(url)
- original_size_url, url, thumb_url = media.save_locally(parent_url, full_path, response.read())
+ original_size_url, url, thumb_url = media.save_locally(parent_url,
+ full_path, response.read())
if thumb_url:
self.set_header('X-Helloworld-Thumbnail', thumb_url)
@@ -108,7 +109,8 @@ def embed(self):
self.write(media.generate_full_html(self, url, original_size_url))
return
- remote_title, remote_thumb, remote_html = content_remote.get_remote_title_and_thumb(url, 'text/html')
+ remote_title, remote_thumb, remote_html = \
+ content_remote.get_remote_title_and_thumb(url, 'text/html')
if remote_title:
self.set_header('X-Helloworld-Title', remote_title)
@@ -121,7 +123,8 @@ def embed(self):
return
if remote_thumb:
- self.write('<a href="' + url + '" title="' + remote_title + '"><img src="' + remote_thumb + '"></a>')
+ self.write('<a href="' + url + '" title="' + remote_title +
+ '"><img src="' + remote_thumb + '"></a>')
return
except:
pass
@@ -134,7 +137,8 @@ def read(self, read=True):
for item in ids:
remote_item = self.models.content_remote.get(int(item))
- if not self.constants['single_user_site'] and remote_item.to_username != self.current_user["username"]:
+ if (not self.constants['single_user_site'] and
+ remote_item.to_username != self.current_user["username"]):
raise tornado.web.HTTPError(400, "i call shenanigans")
remote_item.read = read
@@ -144,9 +148,11 @@ def read_all(self):
user = self.get_argument('user')
profile = self.get_author_username()
if user in self.constants['external_sources']:
- content = self.models.content_remote.get(to_username=profile, type=user)[:]
+ content = self.models.content_remote.get(to_username=profile,
+ type=user)[:]
else:
- content = self.models.content_remote.get(to_username=profile, from_user=user)[:]
+ content = self.models.content_remote.get(to_username=profile,
+ from_user=user)[:]
for item in content:
item.read = True
@@ -180,7 +186,9 @@ def order(self):
return
else:
section_album = section_album.split('_')
- collection, common_options = content_logic.get_collection(self, profile=profile, section=section_album[0], name=section_album[1])[:]
+ collection, common_options = content_logic.get_collection(self,
+ profile=profile, section=section_album[0],
+ name=section_album[1])[:]
elif op_type == 'section':
name = dragged
collection = content_logic.get_main_sections(self, profile=profile)
@@ -189,7 +197,8 @@ def order(self):
name = section_album[1]
if not new_section:
- collection = content_logic.get_albums(self, profile=profile, section=section_album[0])
+ collection = content_logic.get_albums(self, profile=profile,
+ section=section_album[0])
else:
album_items = self.models.content.get(username=profile,
album=name)[:]
@@ -202,7 +211,8 @@ def order(self):
album_item.section = new_section
album_item.save()
- collection = content_logic.get_albums(self, profile=profile, section=new_section)
+ collection = content_logic.get_albums(self, profile=profile,
+ section=new_section)
counter = 0
inserted = False
@@ -222,7 +232,8 @@ def order_following(self):
position = int(self.get_argument('position'))
profile = self.get_author_username()
- following = self.models.users_remote.get(local_username=profile, following=1).order_by('order,username')[:]
+ following = self.models.users_remote.get(local_username=profile,
+ following=1).order_by('order,username')[:]
dragged_id = int(dragged[len('hw-following-'):])
# TODO consolidate with above function?
@@ -250,7 +261,8 @@ def rename(self):
if op_type == 'section':
content_logic.rename_section(self, old_name, new_name, new_title)
else:
- content_logic.rename_album(self, section_album[0], section_album[1], new_name, new_title)
+ content_logic.rename_album(self, section_album[0], section_album[1],
+ new_name, new_title)
def follow(self):
user_url = self.get_argument('user_url').strip()
@@ -271,22 +283,27 @@ def follow(self):
# get some content, yo
feed_response = urllib2.urlopen(user.feed_url)
- content_remote.parse_feed(self.models, user, feed_response.read(), max_days_old=self.constants['feed_max_days_old'])
+ content_remote.parse_feed(self.models, user, feed_response.read(),
+ max_days_old=self.constants['feed_max_days_old'])
def unfollow(self):
user_url = self.get_argument('user')
profile = self.get_author_username()
- content_remote = self.models.content_remote.get(to_username=profile, from_user=user_url)[:]
+ content_remote = self.models.content_remote.get(to_username=profile,
+ from_user=user_url)[:]
for content in content_remote:
content.delete()
- user_remote = self.models.users_remote.get(local_username=profile, profile_url=user_url)[0]
+ user_remote = self.models.users_remote.get(local_username=profile,
+ profile_url=user_url)[0]
if user_remote.hub_url:
try:
- callback_url = self.nav_url(host=True, username=profile, section='push')
- pubsubhubbub_subscribe.subscribe_topic(user_remote.hub_url, user_remote.feed_url, callback_url, subscribe=False, verify="sync")
+ callback_url = self.nav_url(host=True, username=profile,
+ section='push')
+ pubsubhubbub_subscribe.subscribe_topic(user_remote.hub_url,
+ user_remote.feed_url, callback_url, subscribe=False, verify="sync")
except:
import logging
logging.error("couldn't unsubscribe from hub!")
@@ -298,13 +315,16 @@ def unfollow(self):
user_remote.save()
def check_ownership(self, content, is_remote):
- if is_remote and not self.constants['single_user_site'] and content.to_username != self.current_user["username"]:
+ if (is_remote and not self.constants['single_user_site'] and
+ content.to_username != self.current_user["username"]):
raise tornado.web.HTTPError(400, "i call shenanigans")
if not is_remote:
local_url = content.thread.split(':')[2]
original_url = url_factory.load_basic_parameters(self, url=local_url)
- original_content = self.models.content.get(username=original_url['profile'], name=original_url['name'])[0]
- if not self.constants['single_user_site'] and original_content.username != self.current_user["username"]:
+ original_content = self.models.content.get(
+ username=original_url['profile'], name=original_url['name'])[0]
+ if (not self.constants['single_user_site'] and
+ original_content.username != self.current_user["username"]):
raise tornado.web.HTTPError(400, "i call shenanigans")
def favorite(self):
@@ -312,7 +332,8 @@ def favorite(self):
local_id = self.get_argument('local_id')
is_remote = int(self.get_argument('is_remote'))
- content = self.models.content_remote.get(local_id) if is_remote else self.models.content.get(local_id)
+ content = (self.models.content_remote.get(local_id) if
+ is_remote else self.models.content.get(local_id))
if not content:
raise tornado.web.HTTPError(400)
@@ -329,20 +350,23 @@ def favorite(self):
if is_remote:
user = self.get_argument('user', '')
if user:
- user_remote = self.models.users_remote.get(local_username=profile, profile_url=user)[0]
+ user_remote = self.models.users_remote.get(local_username=profile,
+ profile_url=user)[0]
if not user_remote:
return
post_id = self.get_argument('post_id', '')
if post_id and user and user_remote.salmon_url:
- users.salmon_favorite(self, user_remote.salmon_url, post_id, favorite=(favorited == 1))
+ users.salmon_favorite(self, user_remote.salmon_url, post_id,
+ favorite=(favorited == 1))
def spam(self):
local_id = self.get_argument('local_id')
not_spam = self.get_argument('not_spam')
is_remote = int(self.get_argument('is_remote'))
- content = self.models.content_remote.get(local_id) if is_remote else self.models.content.get(local_id)
+ content = (self.models.content_remote.get(local_id) if
+ is_remote else self.models.content.get(local_id))
if not content:
raise tornado.web.HTTPError(400)
@@ -353,16 +377,19 @@ def spam(self):
content.save()
if not_spam:
- spam.train_ham(content.view, self.application.settings["private_path"], profile.username)
+ spam.train_ham(content.view, self.application.settings["private_path"],
+ profile.username)
else:
- spam.train_spam(content.view, self.application.settings["private_path"], profile.username)
+ spam.train_spam(content.view, self.application.settings["private_path"],
+ profile.username)
def delete(self):
local_id = self.get_argument('local_id')
not_deleted = self.get_argument('not_deleted')
is_remote = int(self.get_argument('is_remote'))
- content = self.models.content_remote.get(local_id) if is_remote else self.models.content.get(local_id)
+ content = (self.models.content_remote.get(local_id) if
+ is_remote else self.models.content.get(local_id))
if not content:
raise tornado.web.HTTPError(400)
@@ -372,31 +399,39 @@ def delete(self):
content.save()
def comment(self):
- commented_content = self.models.content.get(username=self.get_argument('local_user'), name=self.get_argument('local_name'))[0]
- self.display["user"] = commented_user = self.models.users.get(username=commented_content.username)[0]
+ commented_content = self.models.content.get(
+ username=self.get_argument('local_user'),
+ name=self.get_argument('local_name'))[0]
+ self.display["user"] = commented_user = self.models.users.get(
+ username=commented_content.username)[0]
comment = self.get_argument('comment')
sanitized_comment = content_remote.sanitize(comment)
- is_spam = spam.guess(comment, self.application.settings["private_path"], commented_content.username)
+ is_spam = spam.guess(comment, self.application.settings["private_path"],
+ commented_content.username)
post_remote = self.models.content_remote()
post_remote.to_username = commented_content.username
post_remote.from_user = self.current_user["email"]
post_remote.username = self.current_user["email"].split('@')[0]
- local_url = '/' + commented_content.username + '/remote-comments/comment-' + str(uuid.uuid4())
- post_remote.post_id = 'tag:' + self.request.host + ',' + self.display["tag_date"] + ':' + local_url
+ local_url = ('/' + commented_content.username +
+ '/remote-comments/comment-' + str(uuid.uuid4()))
+ post_remote.post_id = ('tag:' + self.request.host + ',' +
+ self.display["tag_date"] + ':' + local_url)
post_remote.link = 'http://' + self.request.host + local_url
from_username = post_remote.username
if self.current_user["user"]:
profile = self.get_author_user()
post_remote.avatar = profile.logo if profile.logo else profile.favicon
else:
- post_remote.avatar = 'http://www.gravatar.com/avatar/' + hashlib.md5(self.current_user["email"].lower()).hexdigest()
+ post_remote.avatar = ('http://www.gravatar.com/avatar/' +
+ hashlib.md5(self.current_user["email"].lower()).hexdigest())
post_remote.date_created = datetime.datetime.utcnow()
if is_spam:
post_remote.is_spam = True
else:
- spam.train_ham(comment, self.application.settings["private_path"], commented_content.username)
+ spam.train_ham(comment, self.application.settings["private_path"],
+ commented_content.username)
post_remote.type = 'comment'
post_remote.local_content_name = commented_content.name
post_remote.view = sanitized_comment
@@ -408,7 +443,9 @@ def comment(self):
cache.remove(self, self.content_url(commented_content))
socialize.socialize(self, commented_content)
- smtp.comment(self, from_username, post_remote.from_user, commented_user.email, self.content_url(commented_content, host=True), sanitized_comment)
+ smtp.comment(self, from_username, post_remote.from_user,
+ commented_user.email, self.content_url(commented_content, host=True),
+ sanitized_comment)
def topic(self):
username = self.get_argument('username')
@@ -436,7 +473,7 @@ def topic(self):
content.section = section
content.album = album
content.title = topic
- content.name = content_logic.get_unique_name(self, content, "_", topic)
+ content.name = content_logic.get_unique_name(self, content, "_", topic)
content.forum = True
current_datetime = datetime.datetime.utcnow()
content.date_created = current_datetime
10 controllers/auth.py
View
@@ -15,15 +15,16 @@ def post(self):
audience = self.request.host
try:
browserid = urllib2.urlopen("https://browserid.org/verify",
- "assertion=%(assertion)s&audience=%(audience)s"
- % { 'assertion': assertion, 'audience': audience })
+ "assertion=%(assertion)s&audience=%(audience)s"
+ % { 'assertion': assertion, 'audience': audience })
response = json.loads(browserid.read())
except:
raise tornado.web.HTTPError(500, "BrowserId auth failed")
if response['status'] == 'okay':
self.get_webfinger_data(response)
- self.set_secure_cookie("user", tornado.escape.json_encode(response), path=self.base_path, HttpOnly=True)
+ self.set_secure_cookie("user", tornado.escape.json_encode(response),
+ path=self.base_path, HttpOnly=True)
else:
raise tornado.web.HTTPError(500, "BrowserId auth failed")
@@ -41,7 +42,8 @@ def get_webfinger_data(self, user):
webfinger_doc = users.get_webfinger(lrdd, user['email'])
if webfinger_doc:
- ostatus_subscribe = webfinger_doc.find('link', rel='http://ostatus.org/schema/1.0/subscribe')
+ ostatus_subscribe = webfinger_doc.find('link',
+ rel='http://ostatus.org/schema/1.0/subscribe')
if ostatus_subscribe:
user['ostatus_subscribe'] = ostatus_subscribe['template']
86 controllers/base.py
View
@@ -38,18 +38,25 @@ def initialize(self):
self.hostname_user = None
self.display["original_uri"] = self.request.uri
self.request.uri = self.request.uri.replace('/helloworld.py', '')
- prefix_constant = self.constants['https_prefix'] if self.request.protocol == 'https' else self.constants['http_prefix']
- if self.request.uri.startswith(tornado.escape.url_escape(prefix_constant).replace('%2F', '/')):
+ prefix_constant = (self.constants['https_prefix'] if
+ self.request.protocol == 'https' else self.constants['http_prefix'])
+ if self.request.uri.startswith(
+ tornado.escape.url_escape(prefix_constant).replace('%2F', '/')):
self.prefix = prefix_constant
else:
self.prefix = ""
- self.base_path = (self.prefix if not self.constants['http_hide_prefix'] else '')
+ self.base_path = (self.prefix if not
+ self.constants['http_hide_prefix'] else '')
if self.base_path == '':
self.base_path = '/'
- self.base_uri = self.request.protocol + '://' + self.request.host + self.base_path
+ self.base_uri = (self.request.protocol + '://' +
+ self.request.host + self.base_path)
if not self.base_uri.endswith('/'):
self.base_uri += '/'
- self.request.uri = (self.prefix if not self.constants['http_hide_prefix'] else '') + self.request.uri[len(tornado.escape.url_escape(self.prefix).replace('%2F', '/')):]
+ self.request.uri = ((self.prefix if not
+ self.constants['http_hide_prefix'] else '') +
+ self.request.uri[len(
+ tornado.escape.url_escape(self.prefix).replace('%2F', '/')):])
self.breadcrumbs = url_factory.load_basic_parameters(self)
self.template = None
self.content = None
@@ -92,7 +99,8 @@ def initialize(self):
def check_version(self):
try:
- version_path = os.path.join(os.path.dirname(self.application.settings["app_path"]), 'mod_time')
+ version_path = os.path.join(os.path.dirname(
+ self.application.settings["app_path"]), 'mod_time')
if self.constants['use_mod_rails']:
touched_path = self.application.settings["restart_path"]
else:
@@ -122,7 +130,8 @@ def get_user_information(self):
self.current_user["author"] = user.author if user else 0
self.current_user["superuser"] = user.superuser if user else 0
self.current_user["avatar"] = user.logo if user else \
- 'http://www.gravatar.com/avatar/' + hashlib.md5(self.current_user["email"].lower()).hexdigest()
+ 'http://www.gravatar.com/avatar/' + hashlib.md5(
+ self.current_user["email"].lower()).hexdigest()
self.display["username"] = self.current_user["username"]
self.display["userid"] = self.current_user["userid"]
self.display["is_author"] = self.current_user["author"]
@@ -140,7 +149,8 @@ def get_user_by_hostname(self):
def get_author_user(self):
if not self.author_user:
- self.author_user = self.models.users.get(1) if self.constants['single_user_site'] else self.current_user["user"]
+ self.author_user = (self.models.users.get(1) if
+ self.constants['single_user_site'] else self.current_user["user"])
return self.author_user
@@ -154,7 +164,8 @@ def fill_debug_info(self):
self.display["show_debug"] = self.constants['debug']
self.display["debug_info"] = ""
if self.constants['debug'] and self.display["is_superuser"]:
- self.display["debug_info"] += repr(self.display).replace(',', ',\n').replace('<!--', '').replace('-->', '')
+ self.display["debug_info"] += repr(self.display).replace(
+ ',', ',\n').replace('<!--', '').replace('-->', '')
def fill_template(self, template="view.html"):
self.fill_debug_info()
@@ -162,7 +173,8 @@ def fill_template(self, template="view.html"):
self.write(rendered_content)
return rendered_content
- def authenticate(self, author=False, superuser=False, content=None, private_resource=None, auto_login=True):
+ def authenticate(self, author=False, superuser=False, content=None,
+ private_resource=None, auto_login=True):
access_granted = False
if author or superuser:
@@ -195,7 +207,8 @@ def authenticate(self, author=False, superuser=False, content=None, private_reso
if self.current_user["userid"]:
for access_entry in access_table:
- if self.current_user["userid"] == access_entry.user and access_entry.has_access:
+ if (self.current_user["userid"] == access_entry.user and
+ access_entry.has_access):
access_granted = True
break
@@ -229,14 +242,18 @@ def get_login_url(self):
def get_db_connection(self):
from autumn.db.connection import autumn_db
- autumn_db.conn.connect('mysql', host=self.constants['mysql_host'], user=self.constants['mysql_user'], passwd=self.constants['mysql_password'], db=self.constants['mysql_database'], charset="utf8", use_unicode=True)
+ autumn_db.conn.connect('mysql', host=self.constants['mysql_host'],
+ user=self.constants['mysql_user'],
+ passwd=self.constants['mysql_password'],
+ db=self.constants['mysql_database'], charset="utf8", use_unicode=True)
self.db = autumn_db
from models import base as models
self.models = models
def get_current_user(self):
- if self.application.settings["cookie_secret"] and self.get_secure_cookie("user"):
+ if (self.application.settings["cookie_secret"] and
+ self.get_secure_cookie("user")):
return tornado.escape.json_decode(self.get_secure_cookie("user"))
else:
return None
@@ -245,16 +262,17 @@ def write_error(self, status_code, **kwargs):
output = ""
for line in traceback.format_exception(*kwargs["exc_info"]):
output += line
- output += str(status_code) + "\n\n" \
- + httplib.responses[status_code] + "\n\n" \
- + tornado.escape.xhtml_escape(repr(self.display)).replace(',', ',\n')
+ output += (str(status_code) + "\n\n" +
+ httplib.responses[status_code] + "\n\n" +
+ tornado.escape.xhtml_escape(repr(self.display)).replace(',', ',\n'))
if self.constants['debug']:
self.display["debug_info"] = ""
self.display["licenses"] = ""
self.display["current_datetime"] = ""
for key, item in self.display.items():
- if isinstance(item, types.ModuleType) or isinstance(item, types.MethodType):
+ if (isinstance(item, types.ModuleType) or
+ isinstance(item, types.MethodType)):
del self.display[key]
self.set_header('Content-Type', 'text/plain')
@@ -266,12 +284,15 @@ def write_error(self, status_code, **kwargs):
self.display["name"] = self.breadcrumbs["name"]
self.fill_debug_info()
if status_code in (404, 405):
- logging.error(str(status_code) + ': ' + self.request.method + ' ' + self.display["original_uri"] + ' ' + self.request.headers["User-Agent"])
+ logging.error(str(status_code) + ': ' + self.request.method + ' ' +
+ self.display["original_uri"] + ' ' +
+ self.request.headers["User-Agent"])
else:
logging.error(output)
self.fill_template("error.html")
- def static_url(self, path, include_filename=None, include_host=False, include_sig=True):
+ def static_url(self, path, include_filename=None, include_host=False,
+ include_sig=True):
"""Returns a static URL for the given relative static file path.
This method requires you set the 'static_path' setting in your
@@ -298,13 +319,14 @@ def static_url(self, path, include_filename=None, include_host=False, include_si
if abs_path not in hashes:
try:
if include_filename:
- include_file = open(os.path.join(self.application.settings["static_path"],
- include_filename))
+ include_file = open(os.path.join(
+ self.application.settings["static_path"], include_filename))
combined_file = ''
lines = include_file.readlines()
for dependency in lines:
- file_abs_path = os.path.join(self.application.settings["static_path"],
- dependency.replace('\n', ''))
+ file_abs_path = os.path.join(
+ self.application.settings["static_path"],
+ dependency.replace('\n', ''))
f = open(file_abs_path)
combined_file = combined_file + '\n' + f.read()
f.close()
@@ -312,7 +334,8 @@ def static_url(self, path, include_filename=None, include_host=False, include_si
# XXX too many problems with jspacker...
#if is_js:
# packer = jspacker.JavaScriptPacker()
- # combined_file = packer.pack(combined_file, encoding=62, fastDecode=True)
+ # combined_file = packer.pack(combined_file, encoding=62,
+ # fastDecode=True)
f = open(abs_path, 'w')
f.write(combined_file)
f.close()
@@ -325,7 +348,8 @@ def static_url(self, path, include_filename=None, include_host=False, include_si
hashes[abs_path] = None
base = self.request.protocol + "://" + self.request.host \
if getattr(self, "include_host", False) or include_host else ""
- if self.request.protocol == 'https' or not self.constants['http_hide_prefix']:
+ if (self.request.protocol == 'https' or not
+ self.constants['http_hide_prefix']):
base += self.prefix
static_url_prefix = self.settings.get('static_url_prefix', '/static/')
if hashes.get(abs_path) and include_sig:
@@ -351,15 +375,18 @@ def xsrf_token(self):
if not token:
token = binascii.b2a_hex(uuid.uuid4().bytes)
expires_days = 30 if self.current_user else None
- self.set_cookie("_xsrf", token, expires_days=expires_days, path=self.base_path)
+ self.set_cookie("_xsrf", token, expires_days=expires_days,
+ path=self.base_path)
self._xsrf_token = token
return self._xsrf_token
def content_url(self, item, host=False, **arguments):
return url_factory.content_url(self, item, host, **arguments)
- def nav_url(self, host=False, username="", section="", name="", page=None, **arguments):
- return url_factory.nav_url(self, host, username, section, name, page, **arguments)
+ def nav_url(self, host=False, username="", section="", name="", page=None,
+ **arguments):
+ return url_factory.nav_url(self, host, username, section, name, page,
+ **arguments)
def add_base_uris(self, view):
return url_factory.add_base_uris(self, view)
@@ -367,5 +394,6 @@ def add_base_uris(self, view):
def prevent_caching(self):
self.set_header("Last-Modified", "Fri, 02 Jan 1970 14:19:41 GMT")
self.set_header("Expires", "Fri, 02 Jan 1970 14:19:41 GMT")
- self.set_header("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0")
+ self.set_header("Cache-Control",
+ "no-store, no-cache, must-revalidate, post-check=0, pre-check=0")
self.set_header("Pragma", "no-cache")
3  controllers/check_broken_links.py
View
@@ -15,7 +15,8 @@ def get(self):
self.display["user"] = self.get_author_user()
- all_content = self.models.content.get(username=self.display["user"].username)
+ all_content = self.models.content.get(
+ username=self.display["user"].username)
links = []
for content in all_content:
86 controllers/customize.py
View
@@ -24,57 +24,78 @@ def get(self):
for theme in local_themes:
theme_path = os.path.join(local_themes_directory, theme)
css_path = os.path.join(theme_path, theme + '.css')
- if not theme.startswith('.') and os.path.isdir(theme_path) and os.path.exists(css_path):
- self.display['themes'].append({ 'path': os.path.join(local_themes_stem, os.path.join(theme, theme + '.css')) })
+ if (not theme.startswith('.') and os.path.isdir(theme_path) and
+ os.path.exists(css_path)):
+ self.display['themes'].append({ 'path': os.path.join(
+ local_themes_stem, os.path.join(theme, theme + '.css')) })
local_themes = os.listdir(global_themes_directory)
for theme in local_themes:
theme_path = os.path.join(global_themes_directory, theme)
css_path = os.path.join(theme_path, theme + '.css')
- if not theme.startswith('.') and os.path.isdir(theme_path) and os.path.exists(css_path):
- self.display['themes'].append({ 'path': os.path.join('css/themes', os.path.join(theme, theme + '.css')) })
+ if (not theme.startswith('.') and os.path.isdir(theme_path) and
+ os.path.exists(css_path)):
+ self.display['themes'].append({ 'path': os.path.join('css/themes',
+ os.path.join(theme, theme + '.css')) })
if self.display["user"].theme.find('_current_theme') != -1:
- current_theme_path = os.path.join(local_themes_stem, '_current_theme')
- default_stylesheet_path = os.path.join(current_theme_path, '_default_.css')
+ current_theme_path = os.path.join(local_themes_stem, '_current_theme')
+ default_stylesheet_path = os.path.join(current_theme_path,
+ '_default_.css')
self.display['themes'].append({ 'path': default_stylesheet_path })
for theme in self.display['themes']:
f = open(os.path.join(static_path, theme['path']))
theme_data = f.read()
title = re.search(r'\* theme: (.*)(\s\(|$)', theme_data)
- theme['title'] = title.group(1) if title and len(title.groups()) > 1 else ''
+ theme['title'] = (title.group(1) if
+ title and len(title.groups()) > 1 else '')
link = re.search(r'\* theme: .*\((.*)\)', theme_data)
theme['link'] = link.group(1) if link and len(link.groups()) > 0 else ''
author = re.search(r'\* designed_by: (.*)(\s\(|$)', theme_data)
- theme['author'] = author.group(1) if author and len(author.groups()) > 1 else ''
+ theme['author'] = (author.group(1) if
+ author and len(author.groups()) > 1 else '')
author_link = re.search(r'\* designed_by: .*\((.*)\)', theme_data)
- theme['author_link'] = author_link.group(1) if author_link and len(author_link.groups()) > 0 else ''
- theme['thumb'] = os.path.join(os.path.dirname(theme['path']), 'thumb.png')
+ theme['author_link'] = (author_link.group(1) if
+ author_link and len(author_link.groups()) > 0 else '')
+ theme['thumb'] = os.path.join(os.path.dirname(theme['path']),
+ 'thumb.png')
theme['static_url'] = self.application.settings["static_url"]
- options = re.findall(r'\* ((?:color|font|image|if|text).*)', theme_data, re.M)
+ options = re.findall(
+ r'\* ((?:color|font|image|if|text).*)', theme_data, re.M)
for index, option in enumerate(options):
theme['option_' + str(index)] = option
- extra_head_html = re.search(r'\* extra_head_html: """(.*?)"""', theme_data, re.M | re.DOTALL)
- theme['extra_head_html'] = extra_head_html.group(1).replace('\n', '\\n') if extra_head_html and len(extra_head_html.groups()) > 0 else ''
- extra_body_end_html = re.search(r'\* extra_body_end_html: """(.*?)"""', theme_data, re.M | re.DOTALL)
- theme['extra_body_end_html'] = extra_body_end_html.group(1).replace('\n', '\\n') if extra_body_end_html and len(extra_body_end_html.groups()) > 0 else ''
-
- if ((self.display["user"].theme.find('_current_theme') != -1 and theme['path'].find('_current_theme') != -1)
- or self.display["user"].theme.replace('_compiled_', '') == theme['path']):
+ extra_head_html = re.search(r'\* extra_head_html: """(.*?)"""',
+ theme_data, re.M | re.DOTALL)
+ theme['extra_head_html'] = (extra_head_html.group(1).replace(
+ '\n', '\\n') if extra_head_html and
+ len(extra_head_html.groups()) > 0 else '')
+ extra_body_end_html = re.search(
+ r'\* extra_body_end_html: """(.*?)"""', theme_data, re.M | re.DOTALL)
+ theme['extra_body_end_html'] = extra_body_end_html.group(1).replace(
+ '\n', '\\n') if extra_body_end_html and len(
+ extra_body_end_html.groups()) > 0 else ''
+
+ if ((self.display["user"].theme.find('_current_theme') != -1 and
+ theme['path'].find('_current_theme') != -1)
+ or self.display["user"].theme.replace('_compiled_', '') ==
+ theme['path']):
self.display['user_theme'] = theme
if re.search('_compiled_', self.display["user"].theme):
self.display['user_theme_compiled'] = self.display["user"].theme
else:
self.display['user_theme_compiled'] = None
- self.display['user_theme_custom'] = self.display["user"].theme.find('_current_theme') != -1
+ self.display['user_theme_custom'] = self.display["user"].theme.find(
+ '_current_theme') != -1
f.close()
- self.display['currencies'] = [ "AUD", "CAD", "CZK", "DKK", "EUR", "HKD", "HUF", "ILS", "JPY", \
- "MXN", "NOK", "NZD", "PLN", "GBP", "SGD", "SEK", "CHF", "THB", "USD", ]
+ self.display['currencies'] = \
+ [ "AUD", "CAD", "CZK", "DKK", "EUR", "HKD", "HUF", "ILS", "JPY", \
+ "MXN", "NOK", "NZD", "PLN", "GBP", "SGD", "SEK", "CHF", "THB",
+ "USD", ]
self.fill_template("customize.html")
@@ -88,15 +109,18 @@ def post(self):
user.description = self.get_argument('description', '')
user.email = self.get_argument('email')
user.name = self.get_argument('name', '')
- user.favicon = url_factory.clean_filename(self.get_argument('favicon', ''))
+ user.favicon = url_factory.clean_filename(self.get_argument('favicon', ''))
user.currency = self.get_argument('currency', '')
user.theme_title = self.get_argument('theme_title', '')
user.theme_link = self.get_argument('theme_link', '')
user.theme_author = self.get_argument('theme_author', '')
user.theme_author_link = self.get_argument('theme_author_link', '')
- user.extra_head_html = self.get_argument('extra_head_html', '').replace('\\n', '\n')
- user.extra_body_end_html = self.get_argument('extra_body_end_html', '').replace('\\n', '\n')
- user.logo = url_factory.clean_filename(self.get_argument('logo', ''))
+ user.extra_head_html = self.get_argument(
+ 'extra_head_html', '').replace('\\n', '\n')
+ user.extra_body_end_html = self.get_argument(
+ 'extra_body_end_html', '').replace('\\n', '\n')
+ user.logo = url_factory.clean_filename(
+ self.get_argument('logo', ''))
user.google_analytics = self.get_argument('google_analytics', '')
user.adult_content = int(self.get_argument('adult_content', 0))
user.tipjar = self.get_argument('tipjar', '')
@@ -110,11 +134,14 @@ def post(self):
static_path = self.application.settings["static_path"]
theme = os.path.join(static_path, os.path.dirname(theme))
- user_path = os.path.join(self.application.settings["resource_path"], user.username)
+ user_path = os.path.join(
+ self.application.settings["resource_path"], user.username)
theme_path = os.path.join(user_path, 'themes')
current_theme_path = os.path.join(theme_path, '_current_theme')
- compiled_stylesheet_path = os.path.join(current_theme_path, '_compiled_.css')
- default_stylesheet_path = os.path.join(current_theme_path, '_default_.css')
+ compiled_stylesheet_path = os.path.join(
+ current_theme_path, '_compiled_.css')
+ default_stylesheet_path = os.path.join(
+ current_theme_path, '_default_.css')
if theme != current_theme_path:
if os.path.exists(current_theme_path):
@@ -127,7 +154,8 @@ def post(self):
f = open(default_stylesheet_path, 'w')
f.write(default_stylesheet)
f.close()
- user.theme = compiled_stylesheet_path[len(self.application.settings["static_path"]) + 1:]
+ user.theme = compiled_stylesheet_path[len(
+ self.application.settings["static_path"]) + 1:]
user.save()
80 controllers/dashboard.py
View
@@ -40,25 +40,32 @@ def get(self):
self.display["local_entry"] = self.get_argument('local_entry', None)
self.display["remote_entry"] = self.get_argument('remote_entry', None)
self.display["sort_type"] = self.get_argument('sort_type', None)
- self.display["sort_type"] = 'oldest' if self.display["sort_type"] == 'oldest' else ''
+ self.display["sort_type"] = ('oldest' if
+ self.display["sort_type"] == 'oldest' else '')
if self.get_argument('list_mode', None) != None:
self.display["list_mode"] = int(self.get_argument('list_mode', 0))
else:
- self.display["list_mode"] = int(self.get_cookie("list_mode")) if self.get_cookie("list_mode") != None else 0
+ self.display["list_mode"] = (int(self.get_cookie("list_mode")) if
+ self.get_cookie("list_mode") != None else 0)
if self.get_argument('read_all_mode', None) != None:
- self.display["read_all_mode"] = int(self.get_argument('read_all_mode', 0))
+ self.display["read_all_mode"] = \
+ int(self.get_argument('read_all_mode', 0))
else:
- self.display["read_all_mode"] = int(self.get_cookie("read_all_mode")) if self.get_cookie("read_all_mode") != None else 0
+ self.display["read_all_mode"] = (int(self.get_cookie("read_all_mode")) if
+ self.get_cookie("read_all_mode") != None else 0)
self.display["read_spam"] = int(self.get_argument('read_spam', 0))
- self.display["read_favorites"] = int(self.get_argument('read_favorites', 0))
+ self.display["read_favorites"] = \
+ int(self.get_argument('read_favorites', 0))
self.display["read_comments"] = int(self.get_argument('read_comments', 0))
for source in self.constants['external_sources']:
- self.display["read_" + source] = int(self.get_argument('read_' + source, 0))
+ self.display["read_" + source] = \
+ int(self.get_argument('read_' + source, 0))
self.display["from_local_id"] = self.get_argument('from_local_id', None)
self.display["from_remote_id"] = self.get_argument('from_remote_id', None)
self.display["q"] = self.get_argument('q', None)
self.display["specific_feed"] = self.get_argument('specific_feed', None)
- offset = int(self.breadcrumbs["modifier"]) if self.breadcrumbs["modifier"] else 1
+ offset = (int(self.breadcrumbs["modifier"]) if
+ self.breadcrumbs["modifier"] else 1)
offset -= 1
begin = self.constants['page_size'] * offset
end = self.constants['page_size'] * offset + self.constants['page_size']
@@ -70,7 +77,9 @@ def get(self):
break
if self.display["specific_feed"]:
- specific_user = self.models.users_remote.get(local_username=user.username, profile_url=self.display["specific_feed"])[0]
+ specific_user = self.models.users_remote.get(
+ local_username=user.username,
+ profile_url=self.display["specific_feed"])[0]
if self.display["sort_type"] != specific_user.sort_type:
specific_user.sort_type = self.display["sort_type"]
specific_user.save()
@@ -84,20 +93,24 @@ def get(self):
local_date = None
remote_date = None
if self.display["from_local_id"]:
- local_date = self.models.content.get(self.display["from_local_id"]).date_created
+ local_date = self.models.content.get(
+ self.display["from_local_id"]).date_created
if self.display["from_remote_id"]:
- remote_date = self.models.content_remote.get(self.display["from_remote_id"]).date_created
+ remote_date = self.models.content_remote.get(
+ self.display["from_remote_id"]).date_created
dashboard_objects = \
[ self.models.content_remote(**content) \
if content['post_id'] else \
self.models.content(**content) \
- for content in db.dashboard_feed(user.username, begin, self.constants['page_size'], self.display["sort_type"], self.display["read_all_mode"], \
- self.display["specific_feed"], self.display["own_feed"], \
- self.display["local_entry"], self.display["remote_entry"], \
- self.display["read_spam"], self.display["read_favorites"], self.display["read_comments"], \
- external, \
- self.display["q"], local_date, remote_date) ]
+ for content in db.dashboard_feed(
+ user.username, begin, self.constants['page_size'],
+ self.display["sort_type"], self.display["read_all_mode"], \
+ self.display["specific_feed"], self.display["own_feed"], \
+ self.display["local_entry"], self.display["remote_entry"], \
+ self.display["read_spam"], self.display["read_favorites"],
+ self.display["read_comments"], external, \
+ self.display["q"], local_date, remote_date) ]
self.display['combined_feed'] = \
[ self.ui["modules"].RemoteContent(content) \
@@ -106,17 +119,20 @@ def get(self):
for content in dashboard_objects ]
if self.display['combined_feed']:
- self.display['combined_feed'].sort(key=lambda x: x.date_created, reverse=(self.display["sort_type"] != 'oldest'))
+ self.display['combined_feed'].sort(key=lambda x: x.date_created,
+ reverse=(self.display["sort_type"] != 'oldest'))
- if (not self.display['combined_feed'] or self.display['combined_feed'] == 0) \
- and self.request.headers.get("X-Requested-With") == "XMLHttpRequest":
+ if ((not self.display['combined_feed'] or
+ self.display['combined_feed'] == 0) and
+ self.request.headers.get("X-Requested-With") == "XMLHttpRequest"):
raise tornado.web.HTTPError(404)
self.display["offset"] = offset + 1
if self.request.headers.get("X-Requested-With") == "XMLHttpRequest":
self.prevent_caching()
- self.write(self.ui["modules"].ContentView(self.display["combined_feed"], list_mode=self.display["list_mode"]))
+ self.write(self.ui["modules"].ContentView(self.display["combined_feed"],
+ list_mode=self.display["list_mode"]))
return
self.get_latest_counts(user)
@@ -124,21 +140,31 @@ def get(self):
self.fill_template("dashboard.html")
def get_latest_counts(self, user):
- self.display['followers'] = self.models.users_remote.get(local_username=user.username, follower=1).order_by('username')[:]
- self.display['following'] = self.models.users_remote.get(local_username=user.username, following=1).order_by('order,username')[:]
+ self.display['followers'] = self.models.users_remote.get(
+ local_username=user.username, follower=1).order_by('username')[:]
+ self.display['following'] = self.models.users_remote.get(
+ local_username=user.username, following=1).order_by(
+ 'order,username')[:]
total_count = 0
for profile in self.display['following']:
- profile_count = self.models.content_remote.get(to_username=user.username, from_user=profile.profile_url, type='post', read=0, is_spam=0, deleted=0).count()
+ profile_count = self.models.content_remote.get(to_username=user.username,
+ from_user=profile.profile_url, type='post', read=0, is_spam=0,
+ deleted=0).count()
profile.unread_entries = profile_count
total_count += profile_count
- self.display['favorites_count'] = self.models.content_remote.get(to_username=user.username, favorited=True, deleted=False).count()
- self.display['comments_count'] = self.models.content_remote.get(to_username=user.username, type='comment', deleted=False).count()
- self.display['spam_count'] = self.models.content_remote.get(to_username=user.username, is_spam=True, deleted=False).count()
+ self.display['favorites_count'] = self.models.content_remote.get(
+ to_username=user.username, favorited=True, deleted=False).count()
+ self.display['comments_count'] = self.models.content_remote.get(
+ to_username=user.username, type='comment', deleted=False).count()
+ self.display['spam_count'] = self.models.content_remote.get(
+ to_username=user.username, is_spam=True, deleted=False).count()
for source in self.constants['external_sources']:
- self.display[source + '_count'] = self.models.content_remote.get(to_username=user.username, type=source, read=0, is_spam=0, deleted=0).count()
+ self.display[source + '_count'] = self.models.content_remote.get(
+ to_username=user.username, type=source, read=0, is_spam=0,
+ deleted=0).count()
total_count += self.display[source + '_count']
self.display['total_count'] = total_count
6 controllers/data_liberation.py
View
@@ -50,12 +50,14 @@ def prepare_file(self):
for f in files:
for filename in f[2]:
path = os.path.join(f[0], filename)
- arcname = path[len(url_factory.resource_directory(self)) - len(username):]
+ arcname = path[len(
+ url_factory.resource_directory(self)) - len(username):]
zf.write(path, arcname)
zf.close()
-class DataLiberationDownloadHandler(tornado.web.StaticFileHandler, DataLiberationHandler):
+class DataLiberationDownloadHandler(tornado.web.StaticFileHandler,
+ DataLiberationHandler):
def get(self):
BaseHandler.initialize(self)
73 controllers/facebook.py
View
@@ -37,9 +37,10 @@ def get(self):
callback=self.async_callback(
self._on_auth))
return
- self.authorize_redirect(redirect_uri=self.nav_url(host=True, section='facebook'),
- client_id=self.settings["facebook_api_key"],
- extra_params={"scope": "read_stream,publish_stream" })
+ self.authorize_redirect(
+ redirect_uri=self.nav_url(host=True, section='facebook'),
+ client_id=self.settings["facebook_api_key"],
+ extra_params={"scope": "read_stream,publish_stream" })
def post(self):
if not self.authenticate(author=True):
@@ -54,11 +55,13 @@ def post(self):
self.user = self.get_author_user()
access_token = self.user.facebook
view = self.get_argument('view', '')
- status = content_remote.strip_html(self.get_argument('title', '')) \
- + ('\n' if self.get_argument('title', '') and self.get_argument('view', '') else '') \
- + content_remote.strip_html(view) \
- + ('\n' if self.get_argument('title', '') or self.get_argument('view', '') else '') \
- + self.get_argument('url')
+ status = (content_remote.strip_html(self.get_argument('title', ''))
+ + ('\n' if self.get_argument('title', '') and
+ self.get_argument('view', '') else '')
+ + content_remote.strip_html(view)
+ + ('\n' if self.get_argument('title', '') or
+ self.get_argument('view', '') else '')
+ + self.get_argument('url'))
thumb = self.get_argument('thumb', '')
picture = None
@@ -84,16 +87,21 @@ def post(self):
picture = thumb
post_args = {"message": status, "picture": picture}
- video = re.compile(r'<iframe[^>]*(youtube|vimeo)[^>]*>.*?</iframe>', re.M | re.S).search(view)
+ video = re.compile(r'<iframe[^>]*(youtube|vimeo)[^>]*>.*?</iframe>',
+ re.M | re.S).search(view)
if video:
video = video.group(0)
- is_youtube = re.compile(r'<iframe[^>]*(youtube)[^>]*>', re.M).search(view)
+ is_youtube = re.compile(r'<iframe[^>]*(youtube)[^>]*>', re.M).search(
+ view)
if is_youtube:
- video_id = re.compile(r'<iframe[^>]*youtube.com/embed/([^\?]*)[^>]*>', re.M).search(view).group(1)
+ video_id = re.compile(r'<iframe[^>]*youtube.com/embed/([^\?]*)[^>]*>',
+ re.M).search(view).group(1)
source = 'http://www.youtube.com/e/' + video_id + '?autoplay=1'
else:
- video_id = re.compile(r'<iframe[^>]*vimeo.com/video/([^\?"]*)[^>]*>', re.M).search(view).group(1)
- source = 'https://secure.vimeo.com/moogaloop.swf?clip_id=' + video_id + '&autoplay=1'
+ video_id = re.compile(r'<iframe[^>]*vimeo.com/video/([^\?"]*)[^>]*>',
+ re.M).search(view).group(1)
+ source = ('https://secure.vimeo.com/moogaloop.swf?clip_id=' +
+ video_id + '&autoplay=1')
post_args['source'] = source
self.facebook_request(
@@ -126,11 +134,13 @@ def favorite_result(self, response):
def timeline_result(self, response):
posts = response['data']
for post in posts:
- exists = self.models.content_remote.get(to_username=self.user.username, type='facebook', post_id=post['id'])[0]
+ exists = self.models.content_remote.get(to_username=self.user.username,
+ type='facebook', post_id=post['id'])[0]
date_updated = None
if post.has_key('updated_time'):
- date_updated = datetime.datetime.strptime(post['updated_time'][:-5], '%Y-%m-%dT%H:%M:%S')
+ date_updated = datetime.datetime.strptime(post['updated_time'][:-5],
+ '%Y-%m-%dT%H:%M:%S')
if exists:
if date_updated and date_updated != exists.date_updated \
@@ -147,10 +157,12 @@ def timeline_result(self, response):
new_post.from_user = post['actions'][0]['link']
#new_post.avatar = tweet['user']['profile_image_url']
- parsed_date = datetime.datetime.strptime(post['created_time'][:-5], '%Y-%m-%dT%H:%M:%S')
+ parsed_date = datetime.datetime.strptime(post['created_time'][:-5],
+ '%Y-%m-%dT%H:%M:%S')
# we don't keep items that are over 30 days old
- if parsed_date < datetime.datetime.utcnow() - datetime.timedelta(days=self.constants['feed_max_days_old']):
+ if parsed_date < datetime.datetime.utcnow() - datetime.timedelta(
+ days=self.constants['feed_max_days_old']):
continue
new_post.date_created = parsed_date
@@ -162,8 +174,10 @@ def timeline_result(self, response):
new_post.post_id = post['id']
new_post.comments_count = post['comments']['count']
if post['comments']['count'] and post['comments']['data']:
- last_updated = post['comments']['data'][len(post['comments']['data']) - 1]['created_time']
- new_post.comments_updated = datetime.datetime.strptime(last_updated[:-5], '%Y-%m-%dT%H:%M:%S')
+ last_updated = post['comments']['data'][len(
+ post['comments']['data']) - 1]['created_time']
+ new_post.comments_updated = datetime.datetime.strptime(
+ last_updated[:-5], '%Y-%m-%dT%H:%M:%S')
if post.has_key('actions'):
new_post.link = post['actions'][0]['link']
elif post.has_key('link'):
@@ -180,13 +194,15 @@ def timeline_result(self, response):
view = tornado.escape.linkify(view)
if post.has_key('picture'):
view = '<img src="' + post['picture'] + '">' + view
- new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(view))
+ new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(
+ view))
new_post.save()
# comments
if post['comments']['count']:
for comment in post['comments']['data']:
- exists = self.models.content_remote.get(to_username=self.user.username, post_id=comment['id'])[0]
+ exists = self.models.content_remote.get(
+ to_username=self.user.username, post_id=comment['id'])[0]
if exists:
continue
else:
@@ -194,8 +210,10 @@ def timeline_result(self, response):
new_comment.to_username = self.user.username
new_comment.username = comment['from']['name']
- new_comment.from_user = 'http://facebook.com/' + comment['from']['id']
- date_created = datetime.datetime.strptime(comment['created_time'][:-5], '%Y-%m-%dT%H:%M:%S')
+ new_comment.from_user = ('http://facebook.com/' +
+ comment['from']['id'])
+ date_created = datetime.datetime.strptime(
+ comment['created_time'][:-5], '%Y-%m-%dT%H:%M:%S')
new_comment.date_created = date_created
new_comment.type = 'remote-comment'
new_comment.thread = post['id']
@@ -205,7 +223,8 @@ def timeline_result(self, response):
new_comment.view = comment['message']
new_comment.save()
- count = self.models.content_remote.get(to_username=self.user.username, type='facebook', deleted=False).count()
+ count = self.models.content_remote.get(to_username=self.user.username,
+ type='facebook', deleted=False).count()
self.write(json.dumps({ 'count': count }))
def facebook_request(self, path, callback, access_token=None,
@@ -264,7 +283,8 @@ def get_sync_authenticated_user(self, redirect_uri, client_id, client_secret,
"redirect_uri": redirect_uri,
}
- response = content_remote.get_url(self._oauth_request_token_url(**args), post=True)
+ response = content_remote.get_url(self._oauth_request_token_url(**args),
+ post=True)
self._on_access_token(callback, response)
def _on_access_token(self, callback, response):
@@ -273,7 +293,8 @@ def _on_access_token(self, callback, response):
callback(None)
return
- args = tornado.escape.parse_qs_bytes(tornado.escape.native_str(response.body))
+ args = tornado.escape.parse_qs_bytes(
+ tornado.escape.native_str(response.body))
access_token = args["access_token"][-1]
callback(access_token)
18 controllers/feed.py
View
@@ -24,10 +24,12 @@ def get(self):
if comments_url:
content_url = url_factory.load_basic_parameters(self, url=comments_url)
- content = self.models.content.get(username=content_url["profile"], section=content_url["section"], name=content_url["name"])[0]
+ content = self.models.content.get(username=content_url["profile"],
+ section=content_url["section"], name=content_url["name"])[0]
comments = content_remote.get_comments(self, content)
- thread_url = 'tag:' + self.request.host + ',' + self.display["tag_date"] + ':' + self.content_url(content)
+ thread_url = ('tag:' + self.request.host + ',' +
+ self.display["tag_date"] + ':' + self.content_url(content))
self.display["thread_url"] = thread_url
comments.sort(key=lambda x: x.date_created, reverse=True)
self.display["feed"] = comments
@@ -46,16 +48,20 @@ def get(self):
content_options['album'] = album
content_options = dict(common_options.items() + content_options.items())
- feed = self.models.content.get(**content_options).order_by('date_created', 'DESC')
+ feed = self.models.content.get(**content_options).order_by(
+ 'date_created', 'DESC')
self.display["feed"] = [ self.ui["modules"].Content(content) \
- for content in feed[:100] if content.section != 'main' and content.album != 'main' ] # todo, this should move to query really
+ for content in feed[:100] if content.section != 'main' and \
+ content.album != 'main' ] # todo, this should move to query really
self.display["section"] = section
self.display["album"] = album
- self.display['sup_id'] = hashlib.md5(self.nav_url(host=True, username=user.username, section='feed')).hexdigest()[:10]
+ self.display['sup_id'] = hashlib.md5(self.nav_url(host=True,
+ username=user.username, section='feed')).hexdigest()[:10]
self.set_header("Content-Type", "application/atom+xml")
- self.set_header("X-SUP-ID", "http://friendfeed.com/api/public-sup.json#" + self.display['sup_id'])
+ self.set_header("X-SUP-ID", "http://friendfeed.com/api/public-sup.json#" +
+ self.display['sup_id'])
self.fill_template("feed.html")
9 controllers/foaf.py
View
@@ -13,9 +13,12 @@ def get(self):
self.display["user"] = user
- self.display['mbox_sha1sum'] = hashlib.sha1('mailto:' + user.email).hexdigest()
- self.display['followers'] = self.models.users_remote.get(local_username=user.username, follower=1)[:]
- self.display['following'] = self.models.users_remote.get(local_username=user.username, following=1)[:]
+ self.display['mbox_sha1sum'] = hashlib.sha1(
+ 'mailto:' + user.email).hexdigest()
+ self.display['followers'] = self.models.users_remote.get(
+ local_username=user.username, follower=1)[:]
+ self.display['following'] = self.models.users_remote.get(
+ local_username=user.username, following=1)[:]
self.set_header("Content-Type", "application/rdf+xml")
self.fill_template("foaf.html")
12 controllers/google.py
View
@@ -35,10 +35,11 @@ def get(self):
callback=self.async_callback(
self._on_auth))
return
- self.authorize_redirect(redirect_uri=self.nav_url(host=True, section='google'),
- client_id=self.settings["google_api_key"],
- extra_params={"scope": self._OAUTH_SCOPE_URL,
- "response_type": "code", })
+ self.authorize_redirect(redirect_uri=self.nav_url(host=True,
+ section='google'),
+ client_id=self.settings["google_api_key"],
+ extra_params={"scope": self._OAUTH_SCOPE_URL,
+ "response_type": "code", })
def timeline_result(self, response):
logging.error('google')
@@ -80,7 +81,8 @@ def get_sync_authenticated_user(self, redirect_uri, client_id, client_secret,
"grant_type": 'authorization_code', }
}
- response = content_remote.get_url(self._oauth_request_token_url(**args), post=True)
+ response = content_remote.get_url(self._oauth_request_token_url(**args),
+ post=True)
self._on_access_token(callback, response)
def _on_access_token(self, callback, response):
21 controllers/media.py
View
@@ -24,7 +24,8 @@ def get(self):
self.display["files"] = os.walk(parent_directory)
self.display["initial_section"] = None
initial_section_check = self.get_argument('initial_section', None)
- if initial_section_check and os.path.exists(os.path.join(url_factory.resource_directory(self), initial_section_check)):
+ if initial_section_check and os.path.exists(os.path.join(
+ url_factory.resource_directory(self), initial_section_check)):
self.display["initial_section"] = initial_section_check
self.display["basename"] = os.path.basename
@@ -37,14 +38,18 @@ def get(self):
if uploaded_file_check:
uploaded_file_check = url_factory.clean_filename(uploaded_file_check)
- uploaded_file_check = os.path.join(self.application.settings["base_path"], uploaded_file_check)
+ uploaded_file_check = os.path.join(
+ self.application.settings["base_path"], uploaded_file_check)
- if not uploaded_file_check.startswith(url_factory.resource_directory(self)):
+ if not uploaded_file_check.startswith(
+ url_factory.resource_directory(self)):
raise tornado.web.HTTPError(400, "i call shenanigans")
if os.path.exists(uploaded_file_check):
- self.display["uploaded_file"] = uploaded_file_check.replace(self.application.settings["base_path"] + '/', '')
- self.display["initial_section"] = os.path.dirname(self.display["uploaded_file"])
+ self.display["uploaded_file"] = uploaded_file_check.replace(
+ self.application.settings["base_path"] + '/', '')
+ self.display["initial_section"] = os.path.dirname(
+ self.display["uploaded_file"])
self.display["embedded"] = self.get_argument('embedded', '')
@@ -66,7 +71,8 @@ def preview(self):
html += self.locale.translate('download video:') + ' '
else:
html += self.locale.translate('download audio:') + ' '
- html += '<a href="' + uri + '" target="_blank">' + uri[uri.rfind('/') + 1:] + '</a>'
+ html += ('<a href="' + uri + '" target="_blank">' +
+ uri[uri.rfind('/') + 1:] + '</a>')
self.write(html)
@@ -76,7 +82,8 @@ def delete(self):
files = json.loads(self.get_argument('files'))
- parent_leading_path = self.application.settings["resource_url"] + "/" + self.get_author_username()
+ parent_leading_path = (self.application.settings["resource_url"] + "/" +
+ self.get_author_username())
for f in files:
f = url_factory.clean_filename(f).replace(parent_leading_path + '/', '')
7 controllers/oembed.py
View
@@ -6,9 +6,10 @@ class OembedHandler(BaseHandler):
def get(self):
url = self.get_argument("url")
content_url = url_factory.load_basic_parameters(self, url=url)
- self.display["content"] = content = self.models.content.get(username=content_url["profile"],
- section=content_url["section"],
- name=content_url["name"])[0]
+ self.display["content"] = content = self.models.content.get(
+ username=content_url["profile"],
+ section=content_url["section"],
+ name=content_url["name"])[0]
content_owner = self.models.users.get(username=content.username)[0]
self.display['content_owner'] = content_owner
self.display['content_thumb'] = content_logic.get_thumbnail(self, content)
3  controllers/private.py
View
@@ -7,7 +7,8 @@ def get(self, path):
BaseHandler.initialize(self)
try:
- if not self.authenticate(private_resource=self.request.uri, auto_login=False):
+ if not self.authenticate(private_resource=self.request.uri,
+ auto_login=False):
# 401, need to login
self.set_status(401)
self.prevent_caching()
10 controllers/push.py
View
@@ -6,7 +6,8 @@
from logic import content_remote
# monkeypatch
-feedparser._HTMLSanitizer.acceptable_elements = feedparser._HTMLSanitizer.acceptable_elements + ['iframe']
+feedparser._HTMLSanitizer.acceptable_elements = \
+ feedparser._HTMLSanitizer.acceptable_elements + ['iframe']
class PushHandler(BaseHandler):
def get(self):
@@ -24,9 +25,12 @@ def post(self):
feed_doc = feedparser.parse(self.request.body)
profile_url = feed_doc.feed['link']
- remote_user = self.models.users_remote.get(local_username=user.username, profile_url=profile_url)[0]
+ remote_user = self.models.users_remote.get(local_username=user.username,
+ profile_url=profile_url)[0]
if not remote_user:
return
- content_remote.parse_feed(self.models, remote_user, parsed_feed=self.request.body, max_days_old=self.constants['feed_max_days_old'])
+ content_remote.parse_feed(self.models, remote_user,
+ parsed_feed=self.request.body,
+ max_days_old=self.constants['feed_max_days_old'])
89 controllers/salmon.py
View
@@ -26,7 +26,8 @@ def __init__(self, handler, local_user):
def LookupPublicKey(self, signer_uri=None):
self.signer_uri = signer_uri
- user_remote = self.handler.models.users_remote.get(local_username=self.local_user.username, profile_url=signer_uri)[0]
+ user_remote = self.handler.models.users_remote.get(
+ local_username=self.local_user.username, profile_url=signer_uri)[0]
if not user_remote:
# get host-meta first
@@ -37,7 +38,9 @@ def LookupPublicKey(self, signer_uri=None):
# get webfinger
webfinger_doc = users.get_webfinger(lrdd_link, signer_uri)
- magic_key = webfinger_doc.find('link', rel='magic-public-key')['href'].replace('data:application/magic-public-key,', '')
+ magic_key = webfinger_doc.find('link',
+ rel='magic-public-key')['href'].replace(
+ 'data:application/magic-public-key,', '')
if not magic_key:
raise tornado.web.HTTPError(400)
@@ -70,8 +73,10 @@ def post(self):
self.display["user"] = user
salmonizer = salmoning.SalmonProtocol()
- salmonizer.key_retriever = self.MockKeyRetriever(handler=self, local_user=user)
- env = salmonizer.ParseSalmon(self.request.body, 'application/magic-envelope+xml')
+ salmonizer.key_retriever = self.MockKeyRetriever(handler=self,
+ local_user=user)
+ env = salmonizer.ParseSalmon(self.request.body,
+ 'application/magic-envelope+xml')
self.handle_activity_verb(env, salmonizer.key_retriever.signer_uri)
# tornado & python rock
@@ -82,14 +87,19 @@ def check_xsrf_cookie(self):
def handle_activity_verb(self, env, signer_uri):
salmon_doc = BeautifulSoup(env)
activity_verb = salmon_doc.find(re.compile('.+:verb$')).string
- user_remote = self.models.users_remote.get(local_username=self.display["user"].username, profile_url=signer_uri)[0]
+ user_remote = self.models.users_remote.get(
+ local_username=self.display["user"].username,
+ profile_url=signer_uri)[0]
if (activity_verb == 'http://activitystrea.ms/schema/1.0/follow'):
- user = users.get_remote_user_info(self, signer_uri, user_remote.local_username)
+ user = users.get_remote_user_info(self, signer_uri,
+ user_remote.local_username)
user.follower = 1
user.save()
- smtp.follow(self, user.username, self.display["user"].email, user.profile_url)
- elif (activity_verb == 'http://ostatus.org/schema/1.0/unfollow' or activity_verb == 'http://activitystrea.ms/schema/1.0/stop-following'):
+ smtp.follow(self, user.username, self.display["user"].email,
+ user.profile_url)
+ elif (activity_verb == 'http://ostatus.org/schema/1.0/unfollow' or
+ activity_verb == 'http://activitystrea.ms/schema/1.0/stop-following'):
user_remote.follower = 0
user_remote.save()
elif (activity_verb == 'http://activitystrea.ms/schema/1.0/favorite'):
@@ -98,10 +108,11 @@ def handle_activity_verb(self, env, signer_uri):
local_url = atom_id.split(':')[2]
content_url = url_factory.load_basic_parameters(self, url=local_url)
- already_favorited = self.models.content_remote.get(to_username=self.display["user"].username,
- from_user=signer_uri,
- type='favorite',
- local_content_name=content_url['name'])[0]
+ already_favorited = self.models.content_remote.get(
+ to_username=self.display["user"].username,
+ from_user=signer_uri,
+ type='favorite',
+ local_content_name=content_url['name'])[0]
if already_favorited:
return
@@ -116,11 +127,13 @@ def handle_activity_verb(self, env, signer_uri):
favorite_record.to_username = self.display["user"].username
favorite_record.from_user = signer_uri
favorite_record.username = user_remote.username
- favorite_record.date_created = datetime.datetime.strptime(salmon_doc.find('atom:updated').string[:-6], '%Y-%m-%dT%H:%M:%S')
+ favorite_record.date_created = datetime.datetime.strptime(
+ salmon_doc.find('atom:updated').string[:-6], '%Y-%m-%dT%H:%M:%S')
favorite_record.type = 'favorite'
favorite_record.local_content_name = content.name
favorite_record.save()
- elif (activity_verb == 'http://activitystrea.ms/schema/1.0/unfavorite' or activity_verb == 'http://ostatus.org/schema/1.0/unfavorite'):
+ elif (activity_verb == 'http://activitystrea.ms/schema/1.0/unfavorite' or
+ activity_verb == 'http://ostatus.org/schema/1.0/unfavorite'):
# TODO no activity object at least with ostatus??
pass
elif (activity_verb == 'http://activitystrea.ms/schema/1.0/share'):
@@ -128,11 +141,13 @@ def handle_activity_verb(self, env, signer_uri):
pass
elif (activity_verb == 'http://activitystrea.ms/schema/1.0/post'):
atom_content = salmon_doc.find('atom:content').string
- sanitized_atom_content = content_remote.sanitize(tornado.escape.xhtml_unescape(atom_content))
+ sanitized_atom_content = content_remote.sanitize(
+ tornado.escape.xhtml_unescape(atom_content))
- existing_content = self.models.content_remote.get(to_username=self.display["user"].username,
- from_user=signer_uri,
- view=sanitized_atom_content)[0]
+ existing_content = self.models.content_remote.get(
+ to_username=self.display["user"].username,
+ from_user=signer_uri,
+ view=sanitized_atom_content)[0]
thread = salmon_doc.find('thr:in-reply-to')
ref = ''
@@ -140,8 +155,9 @@ def handle_activity_verb(self, env, signer_uri):
try:
local_url = thread['ref'].split(':')[2]
content_url = url_factory.load_basic_parameters(self, url=local_url)
- content = self.models.content.get(username=self.display["user"].username,
- name=content_url['name'])[0]
+ content = self.models.content.get(
+ username=self.display["user"].username,
+ name=content_url['name'])[0]
if not content:
raise tornado.web.HTTPError(400)
ref = content_url['name']
@@ -162,7 +178,8 @@ def handle_activity_verb(self, env, signer_uri):
if replies.has_key('updated'):
comments_updated = replies['updated']
comments_response = urllib2.urlopen(replies['href'])
- content_remote.parse_feed(self.models, user_remote, comments_response.read(), remote_comments=True)
+ content_remote.parse_feed(self.models, user_remote,
+ comments_response.read(), remote_comments=True)
mentioned = salmon_doc.findAll('atom:link', rel='mentioned')
if not mentioned:
@@ -170,14 +187,17 @@ def handle_activity_verb(self, env, signer_uri):
this_user_mentioned = False
if mentioned:
- this_user_url = self.nav_url(host=True, username=self.display["user"].username)
+ this_user_url = self.nav_url(host=True,
+ username=self.display["user"].username)
for mentions in mentioned:
if mentions['href'] == this_user_url:
# hey, you've been mentioned. cool.
this_user_mentioned = True
break
- is_spam = spam.guess(atom_content, self.application.settings["private_path"], self.display["user"].username)
+ is_spam = spam.guess(atom_content,
+ self.application.settings["private_path"],
+ self.display["user"].username)
if existing_content:
# possible that it's picked up via feed, before we get the salmon call
@@ -188,18 +208,23 @@ def handle_activity_verb(self, env, signer_uri):
post_remote.from_user = signer_uri
post_remote.username = user_remote.username
post_remote.avatar = user_remote.avatar
- post_remote.date_created = datetime.datetime.strptime(salmon_doc.find('atom:published').string[:-6], '%Y-%m-%dT%H:%M:%S')
- post_remote.date_updated = datetime.datetime.strptime(salmon_doc.find('atom:updated').string[:-6], '%Y-%m-%dT%H:%M:%S')
+ post_remote.date_created = datetime.datetime.strptime(
+ salmon_doc.find('atom:published').string[:-6], '%Y-%m-%dT%H:%M:%S')
+ post_remote.date_updated = datetime.datetime.strptime(
+ salmon_doc.find('atom:updated').string[:-6], '%Y-%m-%dT%H:%M:%S')
post_remote.comments_count = comments_count
if comments_updated:
- post_remote.comments_updated = datetime.datetime.strptime(comments_updated[:-6], '%Y-%m-%dT%H:%M:%S')
+ post_remote.comments_updated = datetime.datetime.strptime(
+ comments_updated[:-6], '%Y-%m-%dT%H:%M:%S')
else:
post_remote.comments_updated = None
if is_spam:
post_remote.is_spam = True
else:
- spam.train_ham(atom_content, self.application.settings["private_path"], self.display["user"].username)
- post_remote.type = 'comment' if ref or (existing_content and existing_content.type == 'comment') else 'post'
+ spam.train_ham(atom_content, self.application.settings["private_path"],
+ self.display["user"].username)
+ post_remote.type = 'comment' if ref or (existing_content and
+ existing_content.type == 'comment') else 'post'
post_remote.title = salmon_doc.find('atom:title').string
post_remote.post_id = salmon_doc.find('atom:id').string
post_remote.link = salmon_doc.find('atom:link', rel='alternate')['href']
@@ -211,6 +236,10 @@ def handle_activity_verb(self, env, signer_uri):
socialize.socialize(self, content)
if ref:
- smtp.comment(self, post_remote.username, post_remote.from_user, self.display["user"].email, self.content_url(content, host=True), sanitized_atom_content)
+ smtp.comment(self, post_remote.username, post_remote.from_user,
+ self.display["user"].email, self.content_url(content, host=True),
+ sanitized_atom_content)
elif this_user_mentioned:
- smtp.comment(self, post_remote.username, post_remote.from_user, self.display["user"].email, post_remote.link, sanitized_atom_content, this_user_mentioned=True)
+ smtp.comment(self, post_remote.username, post_remote.from_user,
+ self.display["user"].email, post_remote.link,
+ sanitized_atom_content, this_user_mentioned=True)
14 controllers/search.py
View
@@ -8,24 +8,28 @@ class SearchHandler(BaseHandler):
def get(self):
query = self.get_argument('q', "")
- content_owner = self.models.users.get(username=self.breadcrumbs["profile"])[0]
+ content_owner = self.models.users.get(
+ username=self.breadcrumbs["profile"])[0]
if not content_owner:
content_owner = self.models.users.get(1)
self.breadcrumbs["profile"] = content_owner.username
- offset = int(self.breadcrumbs["modifier"]) if self.breadcrumbs["modifier"] else 1
+ offset = (int(self.breadcrumbs["modifier"]) if
+ self.breadcrumbs["modifier"] else 1)
offset -= 1
begin = self.constants['page_size'] * offset
if query:
- if content_owner.adult_content \
- and self.get_cookie("adult_content") != "1" and not self.is_owner_viewing(self.breadcrumbs["profile"]):
+ if (content_owner.adult_content
+ and self.get_cookie("adult_content") != "1" and not
+ self.is_owner_viewing(self.breadcrumbs["profile"])):
self.fill_template("adult_content.html")
return
query = urllib.unquote_plus(query)
- resultsQuery = db.search(profile=self.breadcrumbs["profile"], query=query, begin=begin, page_size=self.constants['page_size'])
+ resultsQuery = db.search(profile=self.breadcrumbs["profile"],
+ query=query, begin=begin, page_size=self.constants['page_size'])
results = [self.models.content(**result) for result in resultsQuery]
else:
results = []
29 controllers/setup.py
View
@@ -30,15 +30,23 @@ def get(self):
else:
self.constants['https_prefix'] = self.display['prefix']
- self.prefix = self.constants['https_prefix'] if self.request.protocol == 'https' else self.constants['http_prefix']
- self.request.uri = self.prefix + self.request.uri[len(tornado.escape.url_escape(self.prefix).replace('%2F', '/')):]
+ self.prefix = (self.constants['https_prefix'] if
+ self.request.protocol == 'https' else self.constants['http_prefix'])
+ self.request.uri = (self.prefix +
+ self.request.uri[len(tornado.escape.url_escape(
+ self.prefix).replace('%2F', '/')):])
self.fill_template("setup.html")
def post(self):
- connection = MySQLdb.connect(host=self.get_argument('mysql_host'), user=self.get_argument('mysql_user'), passwd=self.get_argument('mysql_password'), db=self.get_argument('mysql_database'), charset="utf8", use_unicode=True)
+ connection = MySQLdb.connect(host=self.get_argument('mysql_host'),
+ user=self.get_argument('mysql_user'),
+ passwd=self.get_argument('mysql_password'),
+ db=self.get_argument('mysql_database'),
+ charset="utf8", use_unicode=True)
cursor = connection.cursor()
- initial_sql = open(os.path.normpath(os.path.realpath(__file__) + '/../../models/helloworld.sql'))
+ initial_sql = open(os.path.normpath(os.path.realpath(__file__) +
+ '/../../models/helloworld.sql'))
cursor.execute(initial_sql.read())
cursor.close()
@@ -52,12 +60,15 @@ def post(self):
user = self.models.users.get(1)
if not user:
- user = users.create_user(self, self.get_argument('username'), self.get_argument('email'))
+ user = users.create_user(self, self.get_argument('username'),
+ self.get_argument('email'))
user.author = True
user.superuser = True
user.save()
- users.create_empty_content(self, user.username, 'main', 'main', "Hello, world.", view="This is a brand-spankin' new Hello, world site.")
+ users.create_empty_content(self, user.username, 'main', 'main',
+ "Hello, world.",
+ view="This is a brand-spankin' new Hello, world site.")
# write site.cfg
config = ConfigParser.RawConfigParser()
@@ -73,10 +84,12 @@ def post(self):
config.set('general', 'https_prefix', self.get_argument('prefix'))
config.set('general', 'http_prefix', '')
- config.set('general', 'mysql_database', self.get_argument('mysql_database'))
+ config.set('general', 'mysql_database',
+ self.get_argument('mysql_database'))
config.set('general', 'mysql_host', self.get_argument('mysql_host'))
config.set('general', 'mysql_user', self.get_argument('mysql_user'))
- config.set('general', 'mysql_password', self.get_argument('mysql_password'))
+ config.set('general', 'mysql_password',
+ self.get_argument('mysql_password'))
xsrf_secret = ''.join([choice(string.letters) for i in range(50)])
xsrf_secret = hashlib.sha256(xsrf_secret).hexdigest()
3  controllers/stats.py
View
@@ -30,7 +30,8 @@ def increase_count(handler):
content_url = url_factory.load_basic_parameters(handler, url=url)
with handler.application.settings["db_lock"]:
- content = handler.models.content.get(username=content_url["profile"], section=content_url["section"], name=content_url["name"])[0]
+ content = handler.models.content.get(username=content_url["profile"],
+ section=content_url["section"], name=content_url["name"])[0]
if content:
if not handler.is_owner_viewing(content.username):
86 controllers/tumblr.py
View
@@ -31,10 +31,12 @@ def get(self):
self.user = self.get_author_user()
access_token, tumblr_info = self.get_tumblr_info()
- count = self.models.content_remote.get(to_username=self.user.username, type='tumblr').count()
+ count = self.models.content_remote.get(to_username=self.user.username,
+ type='tumblr').count()
args = {}
if count:
- jump = self.models.content_remote.get(to_username=self.user.username, type='tumblr')[count - 1:count]
+ jump = self.models.content_remote.get(to_username=self.user.username,
+ type='tumblr')[count - 1:count]
args['since_id'] = jump[0].post_id
self.tumblr_request(
@@ -88,20 +90,26 @@ def post(self):
normal_path = os.path.join(parent_dir, basename)
if os.path.exists(normal_path):
normal_picture = normal_path
- normal_picture = normal_picture[len(self.application.settings["static_path"]) + 1:]
- normal_picture = self.static_url(normal_picture, include_host=True, include_sig=False)
+ normal_picture = normal_picture[len(
+ self.application.settings["static_path"]) + 1:]
+ normal_picture = self.static_url(normal_picture, include_host=True,
+ include_sig=False)
picture = picture[len(self.application.settings["static_path"]) + 1:]
- picture = self.static_url(picture, include_host=True, include_sig=False)
+ picture = self.static_url(picture, include_host=True,
+ include_sig=False)
else:
picture = thumb
- video = re.compile(r'<iframe[^>]*(youtube|vimeo)[^>]*>.*?</iframe>', re.M | re.S).search(body)
+ video = re.compile(r'<iframe[^>]*(youtube|vimeo)[^>]*>.*?</iframe>',
+ re.M | re.S).search(body)
if picture and normal_picture and not video:
post_args["source"] = picture
post_args["link"] = self.get_argument('url')
- post_args["caption"] = re.compile(r'(<figure>.*?<img.*?src="' + normal_picture + r'".*?>.*?</figure>)', re.M | re.U | re.S).sub('', body)
+ post_args["caption"] = re.compile(r'(<figure>.*?<img.*?src="' +
+ normal_picture + r'".*?>.*?</figure>)', re.M | re.U | re.S).sub(
+ '', body)
post_args["type"] = "photo"
if video:
@@ -122,10 +130,11 @@ def post(self):
post_args["tags"] += "," + album
self.tumblr_request(
- "http://api.tumblr.com/v2/blog/" + tumblr_info['primary_blog'] + "/post",
- self.status_update_result,
- access_token=access_token,
- post_args=post_args,)
+ "http://api.tumblr.com/v2/blog/" + tumblr_info['primary_blog'] +
+ "/post",
+ self.status_update_result,
+ access_token=access_token,
+ post_args=post_args,)
# TODO XXX favoriting busted right now, need reblog key
def favorite(self):
@@ -160,7 +169,8 @@ def favorite_result(self, response):
def timeline_result(self, response):
posts = response['response']['posts']
for post in posts:
- exists = self.models.content_remote.get(to_username=self.user.username, type='tumblr', post_id=str(post['id']))[0]
+ exists = self.models.content_remote.get(to_username=self.user.username,
+ type='tumblr', post_id=str(post['id']))[0]
if exists:
continue
@@ -175,7 +185,8 @@ def timeline_result(self, response):
parsed_date = datetime.datetime.utcfromtimestamp(post['timestamp'])
# we don't keep items that are over 30 days old
- if parsed_date < datetime.datetime.utcnow() - datetime.timedelta(days=self.constants['feed_max_days_old']):
+ if parsed_date < datetime.datetime.utcnow() - datetime.timedelta(
+ days=self.constants['feed_max_days_old']):
continue
new_post.date_created = parsed_date
@@ -187,45 +198,60 @@ def timeline_result(self, response):
new_post.link = post['post_url']
if post['type'] == 'text':
new_post.title = post['title']
- new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(post['body']))
+ new_post.view = content_remote.sanitize(
+ tornado.escape.xhtml_unescape(post['body']))
elif post['type'] == 'photo':
html = ""
for photo in post['photos']:
chosen_photo = None
for size in photo['alt_sizes']:
- if not chosen_photo or (size['width'] <= 720 and chosen_photo['width'] < size['width']):
+ if (not chosen_photo or (size['width'] <= 720 and
+ chosen_photo['width'] < size['width'])):
chosen_photo = size
- html += '<img src="' + content_remote.sanitize(tornado.escape.xhtml_unescape(chosen_photo['url'])) + '">'
- html += content_remote.sanitize(tornado.escape.xhtml_unescape(post['caption']))
+ html += '<img src="' + content_remote.sanitize(
+ tornado.escape.xhtml_unescape(chosen_photo['url'])) + '">'
+ html += content_remote.sanitize(tornado.escape.xhtml_unescape(
+ post['caption']))
new_post.view = html
elif post['type'] == 'quote':
- new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(post['text'] + '<br>' + post['source']))
+ new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(
+ post['text'] + '<br>' + post['source']))
elif post['type'] == 'link':
new_post.title = post['title']
- new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape('<a href="' + post['url'] + '">' + post['url'] + '</a><br>' + post['description']))
+ new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(
+ '<a href="' + post['url'] + '">' + post['url'] + '</a><br>' +
+ post['description']))
elif post['type'] == 'chat':
new_post.title = post['title']
- new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(post['body'].replace('\r\n', '<br>')))
+ new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(
+ post['body'].replace('\r\n', '<br>')))
elif post['type'] == 'audio':
html = ""
- html += content_remote.sanitize(tornado.escape.xhtml_unescape(post['player']))
- html += content_remote.sanitize(tornado.escape.xhtml_unescape(post['caption']))
+ html += content_remote.sanitize(tornado.escape.xhtml_unescape(
+ post['player']))
+ html += content_remote.sanitize(tornado.escape.xhtml_unescape(
+ post['caption']))
new_post.view = html
elif post['type'] == 'video':
chosen_video = None
for video in post['player']:
- if not chosen_video or (video['width'] <= 720 and chosen_video['width'] < video['width']):
+ if (not chosen_video or (video['width'] <= 720 and
+ chosen_video['width'] < video['width'])):
chosen_video = video
html = ""
- html += content_remote.sanitize(tornado.escape.xhtml_unescape(chosen_video['embed_code']))
- html += content_remote.sanitize(tornado.escape.xhtml_unescape(post['caption']))
+ html += content_remote.sanitize(tornado.escape.xhtml_unescape(
+ chosen_video['embed_code']))
+ html += content_remote.sanitize(tornado.escape.xhtml_unescape(
+ post['caption']))
new_post.view = html
elif post['type'] == 'answer':
new_post.title = post['question']
- new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(post['answer']))
+ new_post.view = content_remote.sanitize(tornado.escape.xhtml_unescape(
+ post['answer']))
new_post.save()
- count = self.models.content_remote.get(to_username=self.user.username, type='tumblr', deleted=False).count()
+ count = self.models.content_remote.get(to_username=self.user.username,
+ type='tumblr', deleted=False).count()
self.write(json.dumps({ 'count': count }))