Esempio n. 1
0
  def post(self):
    acct = self.get_argument("q").split(':')

    # remove acct: if it's there
    if len(acct) > 1:
      acct[0] = acct[1].split('@')[0]

    acct = acct[0].split('@')[0]

    self.display["acct"] = acct
    user = self.models.users.get(username=acct)[0]

    if not user:
      raise tornado.web.HTTPError(400)

    self.display["user"] = user

    env = urlparse.parse_qs(self.request.body)
    if not env['target'] or not env['source']:
      raise tornado.web.HTTPError(400)

    content_url = url_factory.load_basic_parameters(self, url=env['target'][0])
    content = self.models.content.get(username=self.display["user"].username,
                                      name=content_url['name'])[0]
    if not content:
      raise tornado.web.HTTPError(400)

    self.handle_mention(content_url, content, env['target'][0], env['source'][0])

    # Accepted
    self.set_status(202)
Esempio n. 2
0
    def post(self):
        if not self.authenticate(author=True):
            return

        content_url = url_factory.load_basic_parameters(self)
        content = self.models.content()

        if (not self.constants['single_user_site']
                and content_url["profile"] != self.current_user["username"]):
            raise tornado.web.HTTPError(400, "i call shenanigans")

        self.save_content(content, content_url, new=True)

        if content.album:
            cache.remove(
                self,
                self.nav_url(username=content.username,
                             section=content.section,
                             name=content.album))
        cache.remove(
            self,
            self.nav_url(username=content.username, section=content.section))

        if not content.hidden:
            socialize.socialize(self, content)
            self.sup_ping(content)

        self.set_header('Location', self.content_url(content))
        content.restricted = False

        content = self.ui["modules"].Content(content)

        self.write(self.ui["modules"].ContentView([content]))
        self.set_status(201)
Esempio n. 3
0
    def get(self):
        acct = self.get_argument("q").split('acct:')

        # remove acct: if it's there
        if len(acct) > 1:
            acct[0] = acct[1]

        if acct[0].find('@') != -1:
            acct = acct[0].split('@')[0]
        else:
            parsed_url = urlparse.urlparse(acct[0])
            content_url = url_factory.load_basic_parameters(
                self, url=parsed_url.path)
            acct = content_url['profile']

        self.display["acct"] = acct
        user = self.models.users.get(username=acct)[0]

        if not user:
            raise tornado.web.HTTPError(404)

        self.display["user"] = user

        self.set_header("Content-Type", "application/xrd+xml")
        self.fill_template("webfinger.html")
Esempio n. 4
0
  def get(self):
    user = self.models.users.get(username=self.breadcrumbs["profile"])[0]

    if not user:
      raise tornado.web.HTTPError(404)

    self.display["user"] = user
    self.display["push_hub"] = self.constants['push_hub']

    section = self.get_argument('category', '')
    album_feed = self.get_argument('album_feed', '')
    comments_url = self.get_argument('comments', '')
    self.display["comments_url"] = comments_url
    self.display["thread_url"] = None

    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]

      comments = content_remote.get_comments(self, 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
    else:
      common_options = {}
      if not self.is_owner_viewing(self.breadcrumbs["profile"]):
        common_options['hidden'] = False

      content_options = { 'username': user.username,
                          'redirect': 0,
                          'forum': 0,
                          'section !=': 'comments', }
      if section:
        content_options['section'] = section
      if album_feed:
        content_options['album'] = album_feed

      content_options = dict(common_options.items() + content_options.items())
      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

    self.display["section"] = section
    self.display["album_feed"] = album_feed

    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.fill_template("feed.html")
Esempio n. 5
0
  def post(self):
    if not self.authenticate(superuser=True):
      return

    content_url = url_factory.load_basic_parameters(self, prefix="/users")

    user = users.create_user(self, content_url["profile"],
        self.get_argument('email'))

    self.save_user(user)
    self.set_status(204)
Esempio n. 6
0
 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"]):
     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"]):
       raise tornado.web.HTTPError(400, "i call shenanigans")
Esempio n. 7
0
  def put(self):
    if not self.authenticate(superuser=True):
      return

    content_url = url_factory.load_basic_parameters(self, prefix="/users")

    user = self.models.users.get(username=content_url["profile"])[0]

    if not user:
      raise tornado.web.HTTPError(404)

    self.save_user(user)
    self.set_status(204)
Esempio n. 8
0
  def get(self):
    if not self.authenticate(superuser=True):
      return

    if self.get_argument('login_as', None):
      content_url = url_factory.load_basic_parameters(self, prefix="/users")
      user = self.models.users.get(username=content_url["profile"])[0]
      response = { 'email': user.email }
      self.set_secure_cookie("user", tornado.escape.json_encode(response),
          path=self.base_path, HttpOnly=True)
      self.redirect(self.nav_url(username=content_url["profile"]))
      return

    self.display["user"] = self.get_author_user()
    self.display["users"] = self.models.users.get()

    self.fill_template("users.html")
Esempio n. 9
0
  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]
    if not content:
      raise tornado.web.HTTPError(404)

    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)
    self.display['thumb_width']   = content_logic.THUMB_WIDTH
    self.display['thumb_height']  = content_logic.THUMB_HEIGHT

    self.set_header("Content-Type", "text/xml")
    self.fill_template("oembed.html")
Esempio n. 10
0
def increase_count(handler):
  is_robot = content_logic.is_viewed_by_robot(handler)
  if is_robot:
    return

  url = handler.get_argument('url', '')
  if url:
    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]

      if content:
        if not handler.is_owner_viewing(content.username):
          content.count = content.count + 1

          content.save()
Esempio n. 11
0
    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]
        if not content:
            raise tornado.web.HTTPError(404)

        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)
        self.display['thumb_width'] = content_logic.THUMB_WIDTH
        self.display['thumb_height'] = content_logic.THUMB_HEIGHT

        self.set_header("Content-Type", "text/xml")
        self.fill_template("oembed.html")
Esempio n. 12
0
def increase_count(handler):
    is_robot = content_logic.is_viewed_by_robot(handler)
    if is_robot:
        return

    url = handler.get_argument('url', '')
    if url:
        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]

            if content:
                if not handler.is_owner_viewing(content.username):
                    content.count = content.count + 1

                    content.save()
Esempio n. 13
0
    def delete(self):
        if not self.authenticate(author=True):
            return

        content_url = url_factory.load_basic_parameters(self)
        content = self.models.content.get(username=content_url["profile"],
                                          section=content_url["section"],
                                          name=content_url["name"])[0]

        if not content:
            raise tornado.web.HTTPError(404)

        if content.name == 'about':  # not allowed to delete
            raise tornado.web.HTTPError(400)

        if (not self.constants['single_user_site']
                and content.username != self.current_user["username"]):
            raise tornado.web.HTTPError(400, "i call shenanigans")

        if content.name == 'home' or content.name == 'main':
            raise tornado.web.HTTPError(400, "i call shenanigans")

        collection = []
        if content.section == 'main':
            collection = self.models.content.get(username=content.username,
                                                 section=content.name)[:]
        elif content.album == 'main':
            collection = self.models.content.get(username=content.username,
                                                 album=content.name)[:]

        for item in collection:
            item.delete()

        content.delete()

        self.set_status(204)
Esempio n. 14
0
  def delete(self):
    content_url = url_factory.load_basic_parameters(self, prefix="/users")

    if content_url["profile"] != self.current_user["username"]:
      if not self.authenticate(superuser=True):
        return
    else:
      if not self.authenticate(author=True):
        return

    user = self.models.users.get(username=content_url["profile"])[0]

    if not user:
      raise tornado.web.HTTPError(404)

    user.delete()

    shutil.rmtree(os.path.join(self.application.settings["private_path"],
                               content_url["profile"]))

    shutil.rmtree(os.path.join(self.application.settings["resource_path"],
                               content_url["profile"]))

    self.set_status(204)
Esempio n. 15
0
  def initialize(self):
    self.display = { }
    self.constants = self.application.settings["constants"]
    self.check_version()

    try:
      self.get_db_connection()
    except:
      self.models = None
      pass
    self.author_user = None
    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', '/')):
      self.prefix = prefix_constant
    else:
      self.prefix = ""
    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)
    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.breadcrumbs = url_factory.load_basic_parameters(self)
    self.template = None
    self.content = None
    self.owner_viewing = False
    self.display["is_superuser"] = False

    if self.request.protocol == 'https':
      self.include_host = True

    self.get_user_information()

    self.display["display"] = self.display
    self.display["bidi"] = content_logic.bidi
    self.display["content"] = None
    self.display["tag_date"] = "2011-09-25"
    self.display["random"] = random
    self.display["urllib"] = urllib
    self.display["content_url"] = self.content_url
    self.display["resource_url"] = url_factory.resource_url
    self.display["js_escape"] = content_logic.js_escape
    self.display["js_in_html_escape"] = content_logic.js_in_html_escape
    self.display["referrer"] = None
    self.display["nav_url"] = self.nav_url
    self.display["add_base_uris"] = self.add_base_uris
    self.display["breadcrumbs"] = self.breadcrumbs
    self.display["is_owner_viewing"] = False
    self.display["single_user_site"] = self.constants['single_user_site']
    self.display["base_uri"] = self.base_uri
    self.display["base_path"] = self.base_path
    self.display["prefix"] = self.prefix
    self.display["section_template"] = None
    self.display["has_code"] = False
    self.display["strip_html"] = content_logic.strip_html
    self.display["ellipsize"] = content_logic.ellipsize
    self.display["source_website"] = self.constants['source_website']
    self.display["licenses"] = self.constants['licenses']
    self.display["current_datetime"] = datetime.datetime.utcnow()
    self.display["is_dashboard"] = False
    self.display["external_sources"] = self.constants['external_sources']
Esempio n. 16
0
    def get(self):
        user = self.models.users.get(username=self.breadcrumbs["profile"])[0]

        if not user:
            raise tornado.web.HTTPError(404)

        self.display["user"] = user
        self.display["push_hub"] = self.constants['push_hub']

        section = self.get_argument('category', '')
        album_feed = self.get_argument('album_feed', '')
        comments_url = self.get_argument('comments', '')
        self.display["comments_url"] = comments_url
        self.display["thread_url"] = None

        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]

            comments = content_remote.get_comments(self, 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
        else:
            common_options = {}
            if not self.is_owner_viewing(self.breadcrumbs["profile"]):
                common_options['hidden'] = False

            content_options = {
                'username': user.username,
                'redirect': 0,
                'forum': 0,
                'section !=': 'comments',
            }
            if section:
                content_options['section'] = section
            if album_feed:
                content_options['album'] = album_feed

            content_options = dict(common_options.items() +
                                   content_options.items())
            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

        self.display["section"] = section
        self.display["album_feed"] = album_feed

        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.fill_template("feed.html")
Esempio n. 17
0
    def initialize(self):
        self.display = {}
        self.constants = self.application.settings["constants"]
        self.check_version()

        try:
            self.get_db_connection()
        except:
            self.models = None
            pass
        self.author_user = None
        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',
                                                                   '/')):
            self.prefix = prefix_constant
        else:
            self.prefix = ""
        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)
        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.breadcrumbs = url_factory.load_basic_parameters(self)
        self.template = None
        self.content = None
        self.owner_viewing = False
        self.display["is_superuser"] = False

        if self.request.protocol == 'https':
            self.include_host = True

        self.get_user_information()

        self.display["display"] = self.display
        self.display["bidi"] = content_logic.bidi
        self.display["content"] = None
        self.display["tag_date"] = "2011-09-25"
        self.display["random"] = random
        self.display["urllib"] = urllib
        self.display["content_url"] = self.content_url
        self.display["resource_url"] = url_factory.resource_url
        self.display["js_escape"] = content_logic.js_escape
        self.display["js_in_html_escape"] = content_logic.js_in_html_escape
        self.display["referrer"] = None
        self.display["nav_url"] = self.nav_url
        self.display["add_base_uris"] = self.add_base_uris
        self.display["breadcrumbs"] = self.breadcrumbs
        self.display["is_owner_viewing"] = False
        self.display["single_user_site"] = self.constants['single_user_site']
        self.display["base_uri"] = self.base_uri
        self.display["base_path"] = self.base_path
        self.display["prefix"] = self.prefix
        self.display["section_template"] = None
        self.display["has_code"] = False
        self.display["strip_html"] = content_logic.strip_html
        self.display["ellipsize"] = content_logic.ellipsize
        self.display["source_website"] = self.constants['source_website']
        self.display["licenses"] = self.constants['licenses']
        self.display["current_datetime"] = datetime.datetime.utcnow()
        self.display["is_dashboard"] = False
        self.display["external_sources"] = self.constants['external_sources']
Esempio n. 18
0
  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]

    if (activity_verb == 'http://activitystrea.ms/schema/1.0/follow'):
      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'):
      user_remote.follower = 0
      user_remote.save()
    elif (activity_verb == 'http://activitystrea.ms/schema/1.0/favorite'):
      activity_object = salmon_doc.find(re.compile('.+:object$'))
      atom_id = activity_object.find('atom:id').string
      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]
      if already_favorited:
        return

      content = self.models.content.get(username=self.display["user"].username,
                                        name=content_url['name'])[0]
      if not content:
        raise tornado.web.HTTPError(400)
      content.favorites += 1
      content.save()

      favorite_record = self.models.content_remote()
      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.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'):
      # TODO no activity object at least with ostatus??
      pass
    elif (activity_verb == 'http://activitystrea.ms/schema/1.0/share'):
      # TODO
      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))

      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 = ''
      if thread:
        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]
          if not content:
            raise tornado.web.HTTPError(400)
          ref = content_url['name']
          content.comments_count += 1
          content.comments_updated = datetime.datetime.utcnow()
          content.save()
        except Exception as ex:
          import logging
          logging.error("something wrong with thread")
          logging.error(ex)

      replies = salmon_doc.find('thr:replies')
      comments_count = 0
      comments_updated = None
      if replies:
        if replies.has_key('count'):
          comments_count = int(replies['count'])
        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)

      mentioned = salmon_doc.findAll('atom:link', rel='mentioned')
      if not mentioned:
        mentioned = salmon_doc.findAll('atom:link', rel='ostatus:attention')

      this_user_mentioned = False
      if mentioned:
        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)

      if existing_content:
        # possible that it's picked up via feed, before we get the salmon call
        post_remote = existing_content
      else:
        post_remote = self.models.content_remote()
      post_remote.to_username = self.display["user"].username
      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.comments_count = comments_count
      if comments_updated:
        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'
      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']
      post_remote.local_content_name = content.name if ref else ''
      post_remote.view = sanitized_atom_content
      post_remote.save()

      if ref:
        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)
      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)
Esempio n. 19
0
    def put(self):
        if not self.authenticate(author=True):
            return

        content_url = url_factory.load_basic_parameters(self)
        content = self.models.content.get(username=content_url["profile"],
                                          section=content_url["section"],
                                          name=content_url["name"])[0]

        if not content:
            raise tornado.web.HTTPError(404)

        if (not self.constants['single_user_site']
                and content.username != self.current_user["username"]):
            raise tornado.web.HTTPError(400, "i call shenanigans")

        old_section = content.section
        old_album = content.album
        old_name = content.name
        old_hidden = content.hidden

        # remove old cached content
        if content.album:
            cache.remove(
                self,
                self.nav_url(username=content.username,
                             section=content.section,
                             name=content.album))
        cache.remove(
            self,
            self.nav_url(username=content.username, section=content.section))
        cache.remove(self, self.content_url(content))

        section = (self.get_argument('section')
                   if self.get_argument('section') else content_url["section"])
        name = (self.get_argument('name')
                if self.get_argument('name', "") else content_url["name"])
        hidden = int(self.get_argument('hidden', 0))

        if content.section == 'main' and old_hidden != hidden:
            collection = self.models.content.get(username=content.username,
                                                 section=old_name)[:]
            for item in collection:
                item.hidden = hidden
                item.save()

        if content.album == 'main' and old_hidden != hidden:
            collection = self.models.content.get(username=content.username,
                                                 section=old_section,
                                                 album=old_name)[:]
            for item in collection:
                item.hidden = hidden
                item.save()

        did_redirect = False
        if content.section == 'main' and old_name != name:
            did_redirect = True
            new_section = content_logic.rename_section(self, old_name, name,
                                                       content.title)

        if content.album == 'main' and old_name != name:
            did_redirect = True
            new_album = content_logic.rename_album(self, content.section,
                                                   old_name, name,
                                                   content.title)

        try:
            self.save_content(content, content_url, new=False)
        except tornado.web.HTTPError as ex:
            if ex.status_code == 400:
                # dup
                return
            else:
                # re-raise
                raise ex

        # remove cached in possible new album and new sections
        if content.album:
            cache.remove(
                self,
                self.nav_url(username=content.username,
                             section=content.section,
                             name=content.album))
        cache.remove(
            self,
            self.nav_url(username=content.username, section=content.section))

        if content.album == 'main' and old_section != content.section:
            album_name = new_album if did_redirect else old_name
            album_items = self.models.content.get(username=content.username,
                                                  album=album_name)[:]
            for item in album_items:
                item.section = (album_name if content.section == 'main' else
                                content.section)
                if content.section == 'main':
                    item.album = ""
                item.save()

        if content.name != old_name and not did_redirect:
            content_logic.create_redirect(self, content, old_section, old_name)

        if content.name != old_name or content.section != old_section:
            self.set_header('Location', self.content_url(content))

        if not content.hidden:
            socialize.socialize(self, content)

        self.set_status(204)
Esempio n. 20
0
    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]

        if (activity_verb == 'http://activitystrea.ms/schema/1.0/follow'):
            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'):
            user_remote.follower = 0
            user_remote.save()
        elif (activity_verb == 'http://activitystrea.ms/schema/1.0/favorite'):
            activity_object = salmon_doc.find(re.compile('.+:object$'))
            atom_id = activity_object.find('atom:id').string
            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]
            if already_favorited:
                return

            content = self.models.content.get(
                username=self.display["user"].username,
                name=content_url['name'])[0]
            if not content:
                raise tornado.web.HTTPError(400)
            content.favorites += 1
            content.save()

            favorite_record = self.models.content_remote()
            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.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'):
            # TODO no activity object at least with ostatus??
            pass
        elif (activity_verb == 'http://activitystrea.ms/schema/1.0/share'):
            # TODO
            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))

            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 = ''
            if thread:
                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]
                    if not content:
                        raise tornado.web.HTTPError(400)
                    ref = content_url['name']
                    content.comments_count += 1
                    content.comments_updated = datetime.datetime.utcnow()
                    content.save()
                except Exception as ex:
                    import logging
                    logging.error("something wrong with thread")
                    logging.error(ex)

            replies = salmon_doc.find('thr:replies')
            comments_count = 0
            comments_updated = None
            if replies:
                if replies.has_key('count'):
                    comments_count = int(replies['count'])
                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)

            mentioned = salmon_doc.findAll('atom:link', rel='mentioned')
            if not mentioned:
                mentioned = salmon_doc.findAll('atom:link',
                                               rel='ostatus:attention')

            this_user_mentioned = False
            if mentioned:
                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)

            if existing_content:
                # possible that it's picked up via feed, before we get the salmon call
                post_remote = existing_content
            else:
                post_remote = self.models.content_remote()
            post_remote.to_username = self.display["user"].username
            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.comments_count = comments_count
            if comments_updated:
                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'
            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']
            post_remote.local_content_name = content.name if ref else ''
            post_remote.view = sanitized_atom_content
            post_remote.save()

            if ref:
                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)
            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)