code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import model from handlers.BaseHandler import * from google.appengine.api import users class UserLogout(BaseHandler): def execute(self): #Check if google account is in use #User registered with different user in vikuit and google user = users.get_current_user() userLocalId = self.sess.user googleAc = False if user and userLocalId: userLocal = db.get(userLocalId) if userLocal and user.email() == userLocal.email: googleAc = True redirect = '/' try: if self.auth(): self.sess.store('', 0) if self.request.referrer: redirect = self.request.referrer except KeyError: self.redirect(redirect) return if googleAc: self.redirect(users.create_logout_url(redirect)) else: self.redirect(redirect)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import re import random import model from handlers.BaseHandler import * from os import environ from recaptcha import captcha class UserRegister(BaseHandler): def execute(self): method = self.request.method if method == 'GET': self.send_form(None) else: if self.get_param('x'): # check if nickname is available nickname = self.request.get('nickname') email = self.request.get('email') message = self.validate_nickname(nickname) if message: self.render_json({'valid': False, 'message': message}) else : self.render_json({'valid': True }) return else: # Validate captcha challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') remoteip = environ['REMOTE_ADDR'] cResponse = captcha.submit( challenge, response, self.get_application().recaptcha_private_key, remoteip) if not cResponse.is_valid: # If the reCAPTCHA server can not be reached, # the error code recaptcha-not-reachable will be returned. self.send_form(cResponse.error_code) return nickname = self.request.get('nickname') email = self.request.get('email') password = self.request.get('password') re_email = self.request.get('re_email') re_password = self.request.get('re_password') if not self.get_param('terms-and-conditions'): self.show_error(nickname, email, "You must accept terms and conditions" ) return if not re.match('^[\w\.-]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}$', email): self.show_error(nickname, email, "Enter a valid mail" ) return if not re.match('^[\w\.-]+$', nickname): self.show_error(nickname, email, "Username can contain letters, numbers, dots, hyphens and underscores" ) return if not password or len(password) < 4 or len(password) > 30: self.show_error(nickname, email, "Password must contain between 4 and 30 chars" ) return message = self.validate_nickname(nickname) if message: self.show_error(nickname, email, message) return u = model.UserData.all().filter('email =', email).get() if u: self.show_error(nickname, email, "This mail already exists" ) return if email != re_email: self.show_error(nickname, email, "Mail and validation mail are not equals" ) return if password != re_password: self.show_error(nickname, email, "New password and validation password are not equal" ) return times = 5 user = model.UserData(nickname=nickname, email=email, password=self.hash_password(nickname, password), articles=0, draft_articles=0, messages=0, draft_messages=0, comments=0, rating_count=0, rating_total=0, rating_average=0, threads=0, responses=0, communities=0, favourites=0, public=False, contacts=0) user.registrationType = 0#local identifier user.put() app = model.Application.all().get() if app: app.users += 1 app.put() memcache.delete('app') #send welcome email app = self.get_application() subject = self.getLocale("Welcome to %s") % app.name bt = "Thanks for signing in %s. %s team welcome you to our social network. \n\nComplete your profile \n%s/module/user.edit\n\nPublish articles, \n\n\nBe part of the communities that interest you. Each community has a forum to share or discuss with people to whom the same interests as you.\nCommunities list %s/module/community.list\nThread list %s/forum.list\n\n\n\nFor futher information check our FAQ page\n%s/html/faq.html\n\nBest regards,\n\n%s Team." body = self.getLocale(bt) % (app.name, app.name, app.url, app.url, app.url, app.url, app.name) self.mail(subject=subject, body=body, to=[user.email]) self.sess.store(str(user.key()), 7200) rt = self.request.get('redirect_to') if not rt: rt = '/' self.redirect(rt) def show_error(self, nickname, email, error): chtml = self.get_captcha(None) self.values['captchahtml'] = chtml self.values['nickname'] = nickname self.values['email'] = email self.values['error'] = error self.render('templates/module/user/user-register.html') def match(self, pattern, value): m = re.match(pattern, value) if not m or not m.string[m.start():m.end()] == value: return None return value def send_form(self, error): chtml = self.get_captcha(error) self.values['captchahtml'] = chtml self.values['redirect_to'] = self.request.get('redirect_to') self.render('templates/module/user/user-register.html') def get_captcha(self, error): chtml = captcha.displayhtml( public_key = self.get_application().recaptcha_public_key, use_ssl = False, error = error) return chtml def validate_nickname(self, nickname): if len(nickname) < 4: return self.getLocale("Username must contain 4 chars at least") if len(nickname) > 20: return self.getLocale("Username must contain less than 20 chars") u = model.UserData.all().filter('nickname =', nickname).get() if u: return self.getLocale("User already exists") return ''
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * from google.appengine.api import users class UserContacts(BaseHandler): def execute(self): self.values['tab'] = '/module/user.list' nickname = self.request.path.split('/')[3] this_user = model.UserData.gql('WHERE nickname=:1', nickname).get() if not this_user: self.not_found() return # TODO: not show if the user profile is not public self.values['this_user'] = this_user query = model.Contact.all().filter('user_from', this_user) contacts = self.paging(query, 27, '-creation_date', this_user.contacts, ['-creation_date']) self.values['users'] = contacts self.render('templates/module/user/user-contacts.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import model from handlers.BaseHandler import * class UserResetPassword(BaseHandler): def execute(self): method = self.request.method if method == 'GET': nickname = self.request.get('nickname') token = self.request.get('token') u = model.UserData.all().filter('nickname =', nickname).filter('token =', token).get() if not u: self.render('templates/module/user/user-resetpassword-error.html') else: self.values['token'] = token self.values['nickname'] = nickname self.render('templates/module/user/user-resetpassword.html') else: token = self.request.get('token') nickname = self.request.get('nickname') password = self.request.get('password') re_password = self.request.get('re_password') if not password or len(password) < 4: self.show_error(nickname, token, "Password must contain 4 chars at least") return if password != re_password: self.show_error(nickname, token, "New password and validation password are not equal") return u = model.UserData.all().filter('nickname =', nickname).filter('token =', token).get() if not u: self.render('templates/module/user/user-resetpassword-error.html') return u.token = None u.password = self.hash_password(nickname, password) u.put() self.render('templates/module/user/user-resetpassword-login.html') def show_error(self, nickname, token, error): self.values['nickname'] = nickname self.values['token'] = token self.values['error'] = error self.render('templates/module/user/user-resetpassword.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import datetime from handlers.BaseHandler import * from google.appengine.api import users class UserList(BaseHandler): def execute(self): self.values['tab'] = '/module/user.list' app = self.get_application() query = model.UserData.all() key = '%s?%s' % (self.request.path, self.request.query) results = 10 if app.max_results: results = app.max_results users = self.paging(query, results, '-articles', app.users, ['-creation_date', '-articles'], key) if users is not None: self.values['users'] = users self.add_tag_cloud() self.render('templates/module/user/user-list.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * from google.appengine.api import users class UserForums(BaseHandler): def execute(self): self.values['tab'] = '/module/user.list' nickname = self.request.path.split('/')[3] this_user = model.UserData.gql('WHERE nickname=:1', nickname).get() if not this_user: self.not_found() return # TODO: not show if the user profile is not public self.values['this_user'] = this_user query = model.Thread.all().filter('author', this_user).filter('parent_thread', None) self.values['threads'] = self.paging(query, 10, '-creation_date', this_user.threads, ['-creation_date']) self.render('templates/module/user/user-forums.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * from google.appengine.api import users class UserDrafts(AuthenticatedHandler): def execute(self): user = self.get_current_user() query = model.Article.all().filter('author =', user).filter('draft =', True).filter('deletion_date', None) self.values['articles'] = self.paging(query, 10, '-last_update', user.draft_articles, ['-last_update']) self.render('templates/module/user/user-drafts.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * from google.appengine.api import users class UserCommunities(BaseHandler): def execute(self): self.values['tab'] = '/module/user.list' nickname = self.request.path.split('/')[3] this_user = model.UserData.gql('WHERE nickname=:1', nickname).get() if not this_user: self.not_found() return # TODO: not show if the user profile is not public self.values['this_user'] = this_user query = model.CommunityUser.all().filter('user', this_user) communities = self.paging(query, 10, '-creation_date', this_user.communities, ['-creation_date']) self.values['communities'] = communities self.render('templates/module/user/user-communities.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * from google.appengine.api import users class UserEvents(AuthenticatedHandler): def execute(self): user = self.get_current_user() query = model.Event.all().filter('followers', user.nickname) self.values['events'] = self.paging(query, 10, '-creation_date') self.render('templates/module/user/user-events.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import model import random from handlers.BaseHandler import * from google.appengine.api import mail from utilities.AppProperties import AppProperties class UserForgotPassword(BaseHandler): def execute(self): method = self.request.method if method == 'GET': self.values['redirect_to'] = self.request.get('redirect_to') self.render('templates/module/user/user-forgotpassword.html') else: email = self.request.get('email') u = model.UserData.all().filter('email =', email).get() if not u: self.show_error(email, "No user found with this mail") return # only local accounts can reset password app = self.get_application() subject = self.getLocale("Password recovery")#u"Recuperar password" if u.registrationType is None or u.registrationType == 0: u.token = self.hash(str(random.random()), email) u.put() #Haz click en el siguiente enlace para proceder a establecer tu password.\n%s/module/user.resetpassword?nickname=%s&token=%s body = self.getLocale("Click this link to set your password.\n%s/module/user.resetpassword?nickname=%s&token=%s") % (app.url, u.nickname, u.token) else: accountProvider = AppProperties().getAccountProvider(u.registrationType) body = self.getLocale("You have requested to recover password but credentials you use in %s are from %s. Review your login information.") % (app.name, accountProvider) self.mail(subject=subject, body=body, to=[u.email]) self.values['token'] = u.token self.values['email'] = email self.values['redirect_to'] = self.request.get('redirect_to') self.render('templates/module/user/user-forgotpassword-sent.html') def show_error(self, email, error): self.values['email'] = email self.values['error'] = error self.render('templates/module/user/user-forgotpassword.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import img from google.appengine.ext import db from google.appengine.api import images from google.appengine.api import memcache from handlers.AuthenticatedHandler import * class UserEdit(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] if method == 'GET': self.values['google_adsense'] = self.not_none(user.google_adsense) self.values['google_adsense_channel'] = self.not_none(user.google_adsense_channel) self.values['real_name'] = self.not_none(user.real_name) self.values['links'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in user.list_urls] self.values['im_addresses'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in user.im_addresses] self.values['country'] = self.not_none(user.country) self.values['city'] = self.not_none(user.city) self.values['about'] = self.not_none(user.about_user) self.values['personal_message'] = self.not_none(user.personal_message); if user.not_full_rss: self.values['not_full_rss'] = user.not_full_rss self.render('templates/module/user/user-edit.html') elif self.auth(): user.google_adsense = self.get_param('google_adsense') user.google_adsense_channel = self.get_param('google_adsense_channel') user.real_name = self.get_param('real_name') user.personal_message = self.get_param('personal_message') user.country = self.get_param('country') if self.get_param('not_full_rss'): user.not_full_rss = True else: user.not_full_rss = False image = self.request.get("img") if image: image = images.im_feeling_lucky(image, images.JPEG) user.avatar = img.resize(image, 128, 128) user.thumbnail = img.resize(image, 48, 48) if not user.image_version: user.image_version = 1 else: memcache.delete('/images/user/avatar/%s/%d' % (user.nickname, user.image_version)) memcache.delete('/images/user/thumbnail/%s/%d' % (user.nickname, user.image_version)) user.image_version += 1 memcache.delete('/images/user/avatar/%s' % (user.nickname)) memcache.delete('/images/user/thumbnail/%s' % (user.nickname)) user.city = self.get_param('city') user.list_urls = [] blog = self.get_param('blog') if blog: if not blog.startswith('http'): linkedin = 'http://' + blog user.list_urls.append(blog + '##blog') linkedin = self.get_param('linkedin') if linkedin: if not linkedin.startswith('http'): linkedin = 'http://' + linkedin user.list_urls.append(linkedin + '##linkedin') ohloh = self.get_param('ohloh') if ohloh: if not ohloh.startswith('http'): linkedin = 'http://' + ohloh user.list_urls.append(ohloh + '##ohloh') user.im_addresses = [] msn = self.get_param('msn') if msn: user.im_addresses.append(msn + '##msn') jabber = self.get_param('jabber') if jabber: user.im_addresses.append(jabber + '##jabber') gtalk = self.get_param('gtalk') if gtalk: user.im_addresses.append(gtalk + '##gtalk') user.about_user = self.get_param('about_user') user.put() followers = list(self.get_followers(user=user)) followers.append(user.nickname) self.create_event(event_type='user.edit', followers=followers, user=user) self.redirect('/module/user/%s' % user.nickname)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import re import model from img import * from utilities import session from google.appengine.ext import webapp from google.appengine.ext import db from handlers.AuthenticatedHandler import * class UserChangePassword(AuthenticatedHandler): def execute(self): method = self.request.method if method == 'GET': self.values['redirect_to'] = self.request.get('redirect_to') self.render('templates/module/user/user-changepassword.html') elif self.auth(): old_password = self.request.get('old_password') password = self.request.get('password') re_password = self.request.get('re_password') if not password or len(password) < 4: self.show_error( "Password must contain 4 chars at least") return if password != re_password: self.show_error("New password and validation password are not equal") return user = self.values['user'] if self.check_password(user, old_password): user.password = self.hash_password(user.nickname, password) user.put() rt = self.request.get('redirect_to') if not rt: rt = '/' self.redirect(rt) else: self.show_error("Incorrect password") return def show_error(self, error): self.values['error'] = error self.render('templates/module/user/user-changepassword.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import model import random import datetime from handlers.BaseHandler import * class UserLogin(BaseHandler): def execute(self): self.sess.valid = False method = self.request.method if method == 'GET': self.values['redirect_to'] = self.request.get('redirect_to') self.render('templates/module/user/user-login.html') else: nickname = self.request.get('nickname') password = self.request.get('password') user = model.UserData.gql('WHERE nickname=:1', nickname).get() if user: if user.registrationType is not None and user.registrationType > 0: self.show_error("", "Invalid login method") return##No es posible cambiar el pass si el user no es de vikuit if self.check_password(user, password): if user.banned_date is not None: self.show_error(nickname, "User '%s' was blocked. Contact with an administrator.") return user.last_login = datetime.datetime.now() user.password = self.hash_password(user.nickname, password) # if you want to change the way the password is hashed user.put() if self.get_param('remember') == 'remember': expires = 1209600 else: expires = 7200 self.sess.store(str(user.key()), expires) rt = self.request.get('redirect_to') if rt: if rt.find("user.login") >-1: self.redirect('/') else: self.redirect(rt) else: self.redirect('/') else: self.show_error("", "Invalid user or password") else: self.show_error("", "Invalid user or password") def show_error(self, nickname, error): self.values['nickname'] = nickname self.values['error'] = error self.render('templates/module/user/user-login.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class UserPromote(AuthenticatedHandler): def execute(self): self.values['tab'] = '/module/user.list' user = self.values['user'] app = self.get_application() self.values['user_url'] = '%s/module/user/%s' % (app.url, user.nickname) self.render('templates/module/user/user-promote.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * from google.appengine.api import users class UserFavourites(BaseHandler): def execute(self): self.values['tab'] = '/module/user.list' nickname = self.request.path.split('/')[3] this_user = model.UserData.gql('WHERE nickname=:1', nickname).get() if not this_user: self.not_found() return # TODO: not show if the user profile is not public self.values['this_user'] = this_user query = model.Favourite.all().filter('user', this_user) favs = self.paging(query, 10, '-creation_date', this_user.favourites, ['-creation_date']) self.values['favourites'] = favs self.render('templates/module/user/user-favourites.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import time import datetime import re from google.appengine.ext import db from google.appengine.api import memcache from handlers.AuthenticatedHandler import * class MBlogEdit(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] key = self.get_param('key') action = self.get_param('act') if method == 'GET': if key:#Unused - This case is to allow edit a post and add comments in a single post page # show edit form post = model.Mblog.get_by_id(key) if not post: self.not_found() return if not user.nickname == post.author.nickname and user.rol != 'admin': self.forbidden() return self.values['key'] = key self.values['content'] = post.content self.render('templates/module/mblog/mblog-edit.html') else: self.not_found() return elif self.auth(): # new post if not action: content = self.get_param('content') if not content or len(content) == 0: self.render_json({ 'saved': False, 'msg': self.getLocale('Content is empty') }) return if len(content) > 150: self.render_json({ 'saved': False, 'msg': self.getLocale('Content is too large') }) return if not re.match(u"^[A-Za-z0-9_-àáèéíòóúÀÁÈÉÍÒÓÚïü: ,=\./&¿\?!¡#\(\)]*$", content): self.render_json({ 'saved': False, 'msg': self.getLocale('Content is invalid') }) return post = model.Mblog(author=user, author_nickname=user.nickname, content=content, responses=0) post.put() self.render_json({ "saved": True, 'key' : str(post.key()) }) return elif action == 'del' and key: post = model.Mblog.get_by_id(long(key)) if not post: self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') }) return if not user.nickname == post.author.nickname and user.rol != 'admin': self.render_json({ 'saved': False, 'msg': self.getLocale('Not allowed') }) return post.deletion_date = datetime.datetime.now() post.deletion_user = user.nickname post.put() self.render_json({ 'saved': True }) return else: self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') }) return #UPDATE CACHE
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.AuthenticatedHandler import * class CommunityForumSubscribe( AuthenticatedHandler ): def execute(self): key = self.get_param('key')#TODO if key is empty app crashed thread = model.Thread.get(key) memcache.delete(str(thread.key().id()) + '_thread') user = self.values['user'] mail = user.email if not mail in thread.subscribers: if not self.auth(): return thread.subscribers.append(user.email) thread.put() self.add_user_subscription(user, 'thread', thread.key().id()) memcache.add(str(thread.key().id()) + '_thread', thread, 0) if self.get_param('x'): self.render_json({ 'action': 'subscribed' }) else: self.redirect('/module/community.forum/%s' % thread.url_path) else: auth = self.get_param('auth') if not auth: self.values['thread'] = thread self.render('templates/module/community/community-forum-subscribe.html') else: if not self.auth(): return thread.subscribers.remove(user.email) thread.put() self.remove_user_subscription(user, 'thread', thread.key().id()) if self.get_param('x'): self.render_json({ 'action': 'unsubscribed' }) else: self.redirect('/module/community.forum/%s' % thread.url_path)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class CommunityArticleDelete(AuthenticatedHandler): def execute(self): article = model.Article.get(self.get_param('article')) community = model.Community.get(self.get_param('community')) if not article or not community: self.not_found() return if not self.auth(): return gi = model.CommunityArticle.gql('WHERE community=:1 and article=:2', community, article).get() if self.values['user'].nickname == article.author.nickname: gi.delete() community.articles -= 1 if community.activity: community.activity -= 15 community.put() self.redirect('/module/article/%s' % article.url_path)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import img from google.appengine.api import images from google.appengine.ext import db from google.appengine.api import memcache from handlers.AuthenticatedHandler import * class CommunityEdit(AuthenticatedHandler): def execute(self): self.values['tab'] = '/module/community.list' method = self.request.method user = self.values['user'] key = self.get_param('key') if method == 'GET': if key: # show edit form community = model.Community.get(key) if user.nickname != community.owner.nickname and user.rol != 'admin': self.forbidden() return self.values['key'] = key self.values['title'] = community.title self.values['description'] = community.description if community.all_users is not None: self.values['all_users'] = community.all_users else: self.values['all_users'] = True if community.category: self.values['category'] = community.category self.add_categories() self.render('templates/module/community/community-edit.html') else: # show an empty form self.values['title'] = "New community..." self.values['all_users'] = True self.add_categories() self.render('templates/module/community/community-edit.html') elif self.auth(): if key: # update community community = model.Community.get(key) if user.nickname != community.owner.nickname and user.rol != 'admin': self.forbidden() return # community title is not editable since many-to-many relationships are denormalizated # community.title = self.get_param('title') community.description = self.get_param('description') image = self.request.get("img") if image: image = images.im_feeling_lucky(image, images.JPEG) community.avatar = img.resize(image, 128, 128) community.thumbnail = img.resize(image, 48, 48) if not community.image_version: community.image_version = 1 else: memcache.delete('/images/community/avatar/%s/%d' % (community.key().id(), community.image_version)) memcache.delete('/images/community/thumbnail/%s/%d' % (community.key().id(), community.image_version)) community.image_version += 1 memcache.delete('/images/community/avatar/%s' % community.key().id()) memcache.delete('/images/community/thumbnail/%s' % community.key().id()) if self.get_param('all_users'): community.all_users = True else: community.all_users = False category = model.Category.get(self.request.get('category')) prev_category = community.category community.category = category community.put() if prev_category: prev_category.communities -= 1 prev_category.put() category.communities += 1 category.put() memcache.delete('index_communities') self.redirect('/module/community/%s' % (community.url_path, )) else: # new community title = self.get_param('title') url_path = '-' all_users = False if self.get_param('all_users'): all_users = True community = model.Community(owner=user, owner_nickname=user.nickname, title=title, description=self.get_param('description'), url_path=url_path, members=1, all_users = all_users, articles=0, threads=0, responses=0, subscribers=[user.email], activity=1) category = model.Category.get(self.request.get('category')) community.category = category image = self.request.get("img") if image: image = images.im_feeling_lucky(image, images.JPEG) community.avatar = img.resize(image, 128, 128) community.thumbnail = img.resize(image, 48, 48) community.image_version = 1 community.put() self.add_user_subscription(user, 'community', community.key().id()) community.url_path = '%d/%s' % (community.key().id(), self.to_url_path(community.title)) community.put() category.communities += 1 category.put() user.communities += 1 user.put() app = model.Application.all().get() if app: if app.communities: app.communities += 1 else: app.communities =1 app.put() memcache.delete('app') community_user = model.CommunityUser(user=user, community=community, user_nickname=user.nickname, community_title=community.title, community_url_path=community.url_path) community_user.put() memcache.delete('index_communities') followers = list(self.get_followers(user=user)) followers.append(user.nickname) self.create_event(event_type='community.new', followers=followers, user=user, community=community) self.add_follower(community=community, nickname=user.nickname) # TODO: update a user counter to know how many communities is owner of? self.redirect('/module/community/%s' % (community.url_path, ))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.AuthenticatedHandler import * class CommunityMove(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] if user.rol != 'admin': self.forbidden() return if method == 'GET': action = self.get_param('action') key = self.get_param('key_orig') if key: community_orig = model.Community.get(key) self.values['key_orig'] = community_orig.key self.render('templates/module/community/community-move.html') return elif self.auth(): action = action = self.get_param('action') if not action: self.render('templates/module/community/community-move.html') return key_orig = self.get_param('key_orig') if key_orig: community_orig = model.Community.get(key_orig) key_dest = self.get_param('key_dest') if key_dest: community_dest = model.Community.get(key_dest) mesagge = '' if not community_orig: message = self.getLocale("Source community not exists") self.values['message'] = message self.render('templates/module/community/community-move.html') return elif not community_dest: message = self.getLocale("Taget community not exists") self.values['message'] = message self.render('templates/module/community/community-move.html') return elif action == 'mu': #move users message = self.move_users(community_orig, community_dest) elif action == 'mt': #move threads message = self.move_threads(community_orig, community_dest) memcache.delete('index_threads') elif action == 'mi': #move articles message = self.move_articles(community_orig, community_dest) elif action == 'delete': message = self.delete_community(community_orig) memcache.delete('index_communities') if action != 'delete': self.values['key_orig'] = community_orig.key self.values['key_dest'] = community_dest.key self.values['message'] = message self.render('templates/module/community/community-move.html') return def move_articles(self, community_orig, community_dest): community_articles = model.CommunityArticle.all().filter('community', community_orig).fetch(10) counter = 0 for community_article in community_articles: article_dest = model.CommunityArticle.all().filter('community', community_dest).filter('article', community_article.article).get() if article_dest: community_article.delete() else: community_article.community = community_dest community_article.community_title = community_dest.title community_article.community_url_path = community_dest.url_path community_article.put() community_dest.articles += 1 if community_dest.activity: community_dest.activity += 15 community_dest.put() counter +=1 community_orig.articles -= 1 if community_dest.activity: community_dest.activity -= 15 community_orig.put() return self.getLocale("%s articles moved. Source community contains %s more.") % (counter, community_orig.articles) def move_threads(self, community_orig, community_dest): counter = 0 for community_thread in model.Thread.all().filter('community', community_orig).filter('parent_thread', None).fetch(1): community_thread.community = community_dest community_thread.community_url_path = community_dest.url_path community_thread.community_title = community_dest.title responses = model.Thread.all().filter('parent_thread', community_thread) if responses: for response in responses: response.community = community_dest response.community_url_path = community_dest.url_path response.community_title = community_dest.title response.put() counter +=1 community_thread.put() community_orig.threads -= 1 community_orig.comments -= community_thread.comments value = 5 + (2 * thread.responses) if community_orig.activity: community_dest.activity -= value community_orig.put() community_dest.threads += 1 community_dest.comments += community_thread.comments if community_dest.activity: community_dest.activity += value community_dest.put() return self.getLocale("Moved thread with %s replies. %s threads remain.") % (counter, community_orig.threads) def move_users(self, community_orig, community_dest): community_users = model.CommunityUser.all().filter('community', community_orig).fetch(10) counter = 0 for community_user in community_users: user_dest = model.CommunityUser.all().filter('community', community_dest).filter('user', community_user.user).get() if user_dest: community_user.user.communities -= 1 community_user.user.put() self.remove_user_subscription(community_user.user, 'community', community_orig.key().id()) community_user.delete() else: community_user.community = community_dest community_dest.members += 1 community_dest.subscribers.append(community_user.user.email) self.add_follower(community=community_dest, nickname=community_user.user.nickname) self.add_user_subscription(community_user.user, 'community', community_dest.key().id()) if community_dest.activity: community_dest.activity += 1 community_dest.put() counter += 1 community_user.community_title = community_dest.title community_user.community_url = community_dest.url_path community_user.put() community_orig.members -= 1 if community_orig.activity: community_orig.activity -= 1 community_orig.put() return self.getLocale("Moved %s users. Source community contains %s more.") % (counter, community_orig.members) def delete_community(self, community_orig): community_orig.delete() app = model.Application.all().get() if app: app.communities -= 1 app.put() memcache.delete('app') return self.getLocale("Deleted community. %s communities remain.") % (app.communities)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseRest import * class CommunityForumVisit(BaseRest): def get(self): thread_id = self.request.get('id') memcache.delete(thread_id + '_thread') thread = model.Thread.get_by_id(int(thread_id)) thread.views += 1 thread.put() memcache.add(str(thread.key().id()) + '_thread', thread, 0) content = [] self.render_json({'views' : thread.views}) return
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import datetime from google.appengine.runtime import apiproxy_errors from google.appengine.ext import db from google.appengine.api import mail from google.appengine.api import memcache from handlers.AuthenticatedHandler import * class CommunityForumReply(AuthenticatedHandler): def execute(self): method = self.request.method if method == "GET" or not self.auth(): return user = self.values['user'] key = self.get_param('key') thread = model.Thread.get(key) memcache.delete(str(thread.key().id()) + '_thread') if not thread: self.not_found() return community = thread.community if community.all_users is not None and not self.can_write(community): self.forbidden() return content = self.get_param('content') preview = self.get_param('preview') if preview: response = model.Thread(community=community, author=user, author_nickname=user.nickname, title=thread.title, content=content, parent_thread=thread, responses=0) self.values['thread'] = response self.values['preview'] = True self.render('templates/module/community/community-thread-edit.html') return if self.check_duplicate(community, user, thread, content): self.show_error("Duplicated reply") return response = model.Thread(community=community, community_title=community.title, community_url_path=community.url_path, author=user, author_nickname=user.nickname, title=thread.title, url_path=thread.url_path, content=content, parent_thread=thread, response_number=thread.responses+1, responses=0, editions=0) response.put() results = 20 app = self.get_application() if app.max_results_sublist: results = app.max_results_sublist page = response.response_number / results if (response.response_number % results) == 1: #delete previous page from the cache if page != 1: previous_url = '/module/community.forum/%s?p=%d' % (thread.url_path, page) else: previous_url = '/module/community.forum/%s?' % (thread.url_path) memcache.delete(previous_url) if (response.response_number % results) > 0: page += 1 if page != 1: response_url = '/module/community.forum/%s?p=%d' % (thread.url_path, page) else: response_url = '/module/community.forum/%s?' % (thread.url_path) memcache.delete(response_url) response_url = response_url + '#comment-%d' % (response.response_number) self.create_community_subscribers(community) community.responses = community.responses + 1 community.put() followers = list(self.get_followers(user=user)) followers.append(user.nickname) followers.extend(self.get_followers(thread=thread)) followers = list(set(followers)) self.create_event(event_type='thread.reply', followers=followers, user=user, thread=thread, community=community, response_number=response.response_number) subscribers = thread.subscribers email_removed = False if subscribers and user.email in subscribers: email_removed = True subscribers.remove(user.email) if subscribers: subject = self.getLocale("New reply to: '%s'") % self.clean_ascii(thread.title) # "Nueva respuesta en: '%s'" body = self.getLocale("New reply to %s.\n%s%s\n\nAll replies:\n%s/module/community.forum/%s\n\nRemove this subscription:\n%s/module/community.forum.subscribe?key=%s") % (self.clean_ascii(thread.title), app.url, response_url, app.url, thread.url_path, app.url, str(thread.key())) self.mail(subject=subject, body=body, bcc=thread.subscribers) subscribe = self.get_param('subscribe') if email_removed: thread.subscribers.append(user.email) if subscribe and not user.email in thread.subscribers: thread.subscribers.append(user.email) self.add_user_subscription(user, 'thread', thread.key().id()) thread.responses += 1 thread.last_response_date = datetime.datetime.now() thread.put() memcache.add(str(thread.key().id()) + '_thread', thread, 0) community = thread.community if community.activity: community.activity += 2 community.put() memcache.delete('index_threads') self.redirect(response_url) def check_duplicate(self, community, user, parent_thread, content): last_thread = model.Thread.all().filter('community', community).filter('parent_thread', parent_thread).filter('author', user).order('-creation_date').get() if last_thread is not None: if last_thread.content == content: return True return False
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.BaseHandler import * class CommunityArticleList(BaseHandler): def execute(self): self.values['tab'] = '/module/community.list' url_path = self.request.path.split('/', 3)[3] community = model.Community.gql('WHERE url_path=:1', url_path).get() if not community: self.not_found() return self.values['community'] = community self.values['joined'] = self.joined(community) query = model.CommunityArticle.all().filter('community', community) self.values['articles'] = self.paging(query, 10, '-creation_date', community.articles, ['-creation_date']) self.render('templates/module/community/community-article-list.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.BaseHandler import * class CommunityForumList(BaseHandler): def execute(self): self.values['tab'] = '/module/community.list' url_path = self.request.path.split('/', 3)[3] community = model.Community.gql('WHERE url_path=:1', url_path).get() if not community: self.not_found() return self.values['community'] = community self.values['joined'] = self.joined(community) if community.all_users is None or community.all_users: self.values['can_write'] = True else: self.values['can_write'] = self.can_write(community) query = model.Thread.all().filter('community', community).filter('parent_thread', None) threads = self.paging(query, 20, '-last_response_date', community.threads, ['-last_response_date']) self.values['threads'] = threads self.render('templates/module/community/community-forum-list.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import logging import datetime from google.appengine.runtime import apiproxy_errors from google.appengine.ext import db from google.appengine.api import mail from google.appengine.api import memcache from handlers.AuthenticatedHandler import * class CommunityForumEdit(AuthenticatedHandler): def execute(self): method = self.request.method if method == "GET" or not self.auth(): return user = self.values['user'] key = self.get_param('key') community = model.Community.get(key) if not community: self.not_found() return if community.all_users is not None and not self.can_write(community): self.forbidden() return title = self.get_param('title') url_path = '' content = self.get_param('content') preview = self.get_param('preview') if preview: thread = model.Thread(community=community, community_url_path=community.url_path, author=user, author_nickname = user.nickname, title=title, content=content, responses=0) self.values['thread'] = thread self.values['preview'] = True self.values['is_parent_thread'] = True self.render('templates/module/community/community-thread-edit.html') return if self.check_duplicate(community, user, content, title): self.show_error("Duplicated thread") return thread = model.Thread(community=community, community_title=community.title, community_url_path=community.url_path, author=user, author_nickname=user.nickname, title=title, url_path=url_path, content=content, last_response_date = datetime.datetime.now(), responses=0, editions=0, views=0) user.threads += 1 user.put() self.create_community_subscribers(community) app = model.Application.all().get() if app: if not app.threads: app.threads = 0 app.threads += 1 app.put() memcache.delete('app') thread.put() self.add_follower(thread=thread, nickname=user.nickname) thread.url_path = ('%d/%s/%s') % (thread.key().id(), self.to_url_path(community.title), self.to_url_path(title)) subscribe = self.get_param('subscribe') if subscribe: thread.subscribers.append(user.email) self.add_user_subscription(user, 'thread', thread.key().id()) thread.put() memcache.add(str(thread.key().id()) + '_thread', thread, 0) community.threads += 1 if community.activity: community.activity += 5 community.put() followers = list(self.get_followers(community=community)) followers.extend(self.get_followers(user=user)) if not user.nickname in followers: followers.append(user.nickname) followers = list(set(followers)) self.create_event(event_type='thread.new', followers=followers, user=user, thread=thread, community=community) subscribers = community.subscribers if subscribers and user.email in subscribers: subscribers.remove(user.email) if subscribers: app = self.get_application() subject = self.getLocale("New subject: '%s'") % self.clean_ascii(thread.title) body = self.getLocale("New subject by community %s.\nSubject title: %s\nFollow forum at:\n%s/module/community.forum/%s") % (self.clean_ascii(community.title), self.clean_ascii(thread.title), app.url, thread.url_path) self.mail(subject=subject, body=body, bcc=community.subscribers) memcache.delete('index_threads') self.redirect('/module/community.forum/%s' % thread.url_path) def check_duplicate(self, community, user, content, title): last_thread = model.Thread.all().filter('community', community).filter('parent_thread', None).filter('author', user).order('-creation_date').get() if last_thread is not None: if last_thread.title == title and last_thread.content == content: return True return False
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class CommunityUserJoin(AuthenticatedHandler): def execute(self): user = self.values['user'] community = model.Community.get(self.get_param('community')) if not community: self.not_found() return if not self.auth(): return redirect = self.get_param('redirect') gu = self.joined(community) if gu == 'False': self.create_community_subscribers(community) gu = model.CommunityUser(user=user, community=community, user_nickname=user.nickname, community_title=community.title, community_url_path=community.url_path) gu.put() community.subscribers.append(user.email) community.members += 1 if community.activity: community.activity += 1 community.put() self.add_follower(community=community, nickname=user.nickname) self.add_user_subscription(user, 'community', community.key().id()) user.communities += 1 user.put() self.redirect(redirect)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.AuthenticatedHandler import * class CommunityForumView(BaseHandler): def execute(self): self.values['tab'] = '/module/community.list' user = self.values['user'] url_path = self.request.path.split('/', 3)[3] thread_id = self.request.path.split('/')[3] thread = self.cache(thread_id + '_thread', self.get_thread) #thread = model.Thread.all().filter('url_path', url_path).filter('parent_thread', None).get() if not thread: # TODO: try with the id in the url_path and redirect self.not_found() return if thread.deletion_date: self.not_found() return # migration. supposed to be finished if len(thread.url_path.split('/')) == 2: thread.url_path = '%d/%s' % (thread.key().id(), thread.url_path) thread.parent_thread = None thread.put() self.redirect('/module/community.forum/%s' % thread.url_path) return # end migration '''if thread.views is None: thread.views = 0; thread.views += 1 thread.put()''' community = thread.community self.values['community'] = community self.values['joined'] = self.joined(community) self.values['thread'] = thread query = model.Thread.all().filter('parent_thread', thread) results = 20 app = self.get_application() if app.max_results_sublist: results = app.max_results_sublist key = '%s?%s' % (self.request.path, self.request.query) responses = self.paging(query, results, 'creation_date', thread.responses, ['creation_date'], key=key, timeout=0) #responses = self.cache(url_path, self.get_responses) # migration if not thread.author_nickname: thread.author_nickname = thread.author.nickname thread.put() i = 1 for t in responses: if not t.response_number: t.response_number = i t.put() i += 1 # end migration self.values['responses'] = responses if community.all_users: self.values['can_write'] = True else: self.values['can_write'] = self.can_write(community) if user: if user.email in thread.subscribers: self.values['cansubscribe'] = False else: self.values['cansubscribe'] = True self.values['a'] = 'comments' self.render('templates/module/community/community-forum-view.html') def get_thread(self): url_path = self.request.path.split('/', 3)[3] return model.Thread.all().filter('url_path', url_path).filter('parent_thread', None).get()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.BaseHandler import * class CommunityView(BaseHandler): def execute(self): self.values['tab'] = '/module/community.list' url_path = self.request.path.split('/', 3)[3] community = model.Community.gql('WHERE url_path=:1', url_path).get() if not community: community = model.Community.gql('WHERE old_url_path=:1', url_path).get() if community: self.redirect('/module/community/%s' % community.url_path, permanent=True) return self.not_found() return self.values['community'] = community self.values['joined'] = self.joined(community) self.values['articles'] = list(model.CommunityArticle.all().filter('community', community).order('-creation_date').fetch(5)) self.values['threads'] = list(model.Thread.all().filter('community', community).filter('parent_thread', None).order('-last_response_date').fetch(5)) self.values['users'] = list(model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(27)) self.values['related'] = list(model.RelatedCommunity.all().filter('community_from', community).order('-creation_date').fetch(10)) self.render('templates/module/community/community-view.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import logging from google.appengine.api import mail from handlers.AuthenticatedHandler import * from google.appengine.runtime import apiproxy_errors class CommunityNewArticle(AuthenticatedHandler): def execute(self): article = model.Article.get(self.get_param('article')) community = model.Community.get(self.get_param('community')) if not community or not article or article.draft or article.deletion_date: self.not_found() return if not self.auth(): return user = self.values['user'] gu = self.joined(community) if gu and not article.draft: gi = model.CommunityArticle.gql('WHERE community=:1 and article=:2', community, article).get() if not gi and user.nickname == article.author.nickname: gi = model.CommunityArticle(article=article, community=community, article_author_nickname=article.author_nickname, article_title=article.title, article_url_path=article.url_path, community_title=community.title, community_url_path=community.url_path) gi.put() community.articles += 1 if community.activity: community.activity += 15 community.put() followers = list(self.get_followers(community=community)) self.create_event(event_type='community.addarticle', followers=followers, user=user, community=community, article=article) subscribers = community.subscribers if subscribers and user.email in subscribers: subscribers.remove(user.email) if subscribers: app = self.get_application() subject = self.getLocale("New article: '%s'") % self.clean_ascii(article.title) # u"Nuevo articulo: '%s'" body = self.getLocale("New article at community %s.\nArticle title: %s\nRead more at:\n%s/module/article/%s\n") % (self.clean_ascii(community.title), self.clean_ascii(article.title), app.url, article.url_path) self.mail(subject=subject, body=body, bcc=community.subscribers) self.redirect('/module/article/%s' % article.url_path)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.AuthenticatedHandler import * class CommunityForumMove(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] if user.rol != 'admin': self.forbidden() return if method == 'GET': thread_key = self.get_param('thread_key') thread = model.Thread.get(thread_key) if thread is None: self.not_found() return self.values['thread_key'] = thread.key self.render('templates/module/community/community-forum-move.html') return elif self.auth(): thread_key = self.get_param('thread_key') community_key = self.get_param('community_key') thread = model.Thread.get(thread_key) community = model.Community.get(community_key) if community is None or thread is None: self.values['thread_key'] = thread.key self.values['message'] = "Community not exists." self.render('templates/module/community/community-forum-move.html') return if community.title == thread.community.title: self.values['thread_key'] = thread.key self.values['message'] = "Source and target community are the same one." self.render('templates/module/community/community-forum-move.html') return #decrement threads in previous community community_orig = thread.community community_orig.threads -= 1 community_orig.responses= thread.responses value = 5 + (2 * thread.responses) if community_orig.activity: community_orig.activity -= value #update comments responses = model.Thread.all().filter('parent_thread', thread) for response in responses: response.community = community response.community_title = community.title response.community_url_path = community.url_path response.put() #change gorup in thread and desnormalizated fields thread.community = community thread.community_title = community.title thread.community_url_path = community.url_path #increment threads in actual community community.threads += 1 community.responses += thread.responses if community.activity: community.activity += value #save fields community_orig.put() thread.put() community.put() self.redirect('/module/community.forum/%s' % (thread.url_path)) return
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class CommunityUserUnjoin(AuthenticatedHandler): def execute(self): user = self.values['user'] community = model.Community.get(self.get_param('community')) if not community: self.not_found() return if not self.auth(): return redirect = self.get_param('redirect') gu = model.CommunityUser.gql('WHERE community=:1 and user=:2', community, user).get() if gu and user != community.owner: self.create_community_subscribers(community) gu.delete() if user.email in community.subscribers: community.subscribers.remove(user.email) community.members -= 1 if community.activity: community.activity -= 1 community.put() self.remove_user_subscription(user, 'community', community.key().id()) self.remove_follower(community=community, nickname=user.nickname) user.communities -= 1 user.put() self.redirect(redirect)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import datetime from google.appengine.ext import db from handlers.AuthenticatedHandler import * class CommunityForumDelete(AuthenticatedHandler): def execute(self): user = self.values['user'] if user.rol != 'admin': self.forbidden() return if not self.auth(): return thread = model.Thread.get(self.get_param('key')) url = '/module/community.forum.list/' + thread.community.url_path if not thread: self.not_found() return if thread.parent_thread is not None: message = self.get_param('message') #decrement number of childs in the parent thread thread.parent_thread.put() #Delete child thread thread.deletion_date = datetime.datetime.now() thread.deletion_message = message thread.put() else: #decrement threads in the community community = thread.community if community.activity: value = 5 + (2 * thread.responses) community.activity -= value community.threads -=1 community.put() #decrement thread in the app app = model.Application().all().get() app.threads -= 1 app.put() memcache.delete('app') #delete comments in this thread childs = model.Thread.all().filter('parent_thread', thread) db.delete(childs) memcache.delete('index_threads') thread.delete() memcache.delete(str(thread.key().id()) + '_thread') self.redirect(url)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.BaseHandler import * class CommunityUserList(BaseHandler): def execute(self): self.values['tab'] = '/module/community.list' url_path = self.request.path.split('/', 3)[3] community = model.Community.gql('WHERE url_path=:1', url_path).get() if not community: self.not_found() return self.values['community'] = community self.values['joined'] = self.joined(community) query = model.CommunityUser.all().filter('community', community) self.values['users'] = self.paging(query, 27, '-creation_date', community.members, ['-creation_date']) self.render('templates/module/community/community-user-list.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from google.appengine.api import memcache from handlers.AuthenticatedHandler import * class CommunityDelete(AuthenticatedHandler): def execute(self): user = self.values['user'] if user.rol != 'admin': self.forbidden() return if not self.auth(): return community=model.Community.get(self.get_param('key')) db.delete(community.communityuser_set) db.delete(community.communityarticle_set) db.delete(community.thread_set) community.delete() app = app = model.Application.all().get() if app: app.communities -=1 app.put() memcache.delete('app') # TODO: some other memcache value should be removed? most active communities? self.redirect('/')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.AuthenticatedHandler import * class CommunityThreadEdit(AuthenticatedHandler): def execute(self): self.values['tab'] = '/module/community.list' method = self.request.method user = self.values['user'] key = self.get_param('key') if method == 'GET': if key: # show edit form thread = model.Thread.get(key) if user.nickname!= thread.author_nickname and user.rol != 'admin': self.forbidden() return if thread is None: self.not_found() return #TODO Check if it's possible if thread.parent_thread is None: self.values['is_parent_thread'] = True self.values['thread'] = thread self.render('templates/module/community/community-thread-edit.html') return else: self.show_error("Thread not found") return elif self.auth(): if key: # update comment thread = model.Thread.get(key) if user.nickname!= thread.author_nickname and user.rol != 'admin': self.forbidden() return if thread is None: self.not_found() return if user.rol != 'admin': if thread.editions is None: thread.editions = 0 thread.editions +=1 thread.last_edition = datetime.datetime.now() if thread.parent_thread is None: if thread.responses <= 5: thread.title = self.get_param('title') for comment in model.Thread.all().filter('parent_thread', thread): comment.title = thread.title comment.put() thread.content = self.get_param('content') thread.put() if thread.parent_thread is None: memcache.delete(str(thread.key().id()) + '_thread') memcache.add(str(thread.key().id()) + '_thread', thread, 0) self.redirect('/module/community.forum/%s' % (thread.url_path)) else: results = 20 app = self.get_application() if app.max_results_sublist: results = app.max_results_sublist page = thread.response_number / results if (thread.response_number % results) > 0: page += 1 if page != 1: response_url = '/module/community.forum/%s?p=%d' % (thread.url_path, page) else: response_url = '/module/community.forum/%s?' % (thread.url_path) memcache.delete(response_url) response_url = response_url + '#comment-%d' % (thread.response_number) self.redirect(response_url) else: self.show_error("Comment not found") return
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * class CommunityList(BaseHandler): def execute(self): self.values['tab'] = '/module/community.list' query = model.Community.all() key = '%s?%s' % (self.request.path, self.request.query) cat = self.get_param('cat') app = self.get_application() if cat: category = model.Category.all().filter('url_path', cat).get() self.values['category'] = category self.values['cat'] = cat query = query.filter('category', category) max = category.communities else: max = app.communities results = 10 if app.max_results: results = app.max_results communities = self.paging(query, results, '-members', max, ['-creation_date', '-members', '-articles'], key) self.values['communities'] = communities # denormalization for g in communities: if not g.owner_nickname: g.owner_nickname = g.owner.nickname g.put() self.add_categories() self.add_tag_cloud() self.render('templates/module/community/community-list.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import img from google.appengine.api import images from google.appengine.api import memcache from handlers.AuthenticatedHandler import * from utilities.AppProperties import AppProperties class AdminApplication(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return if method == 'GET': app = self.get_application() self.values['m'] = self.get_param('m') if not app: app = model.Application() self.values['app'] = app self.values['appName'] = self.not_none(app.name) self.values['appSubject'] = self.not_none(app.subject) self.values['locale'] = self.not_none(app.locale) self.values['url'] = self.not_none(app.url) self.render('templates/module/admin/admin-application.html') elif self.auth(): app = self.get_application() if not app: app = model.Application() app.users = model.UserData.all().count() app.communities = model.Community.all().count() app.threads = model.Thread.all().filter('parent_thread', None).count() app.articles = model.Article.all().filter('draft =', False).filter('deletion_date', None).count() app.name = self.get_param('appName') app.subject = self.get_param("appSubject") app.locale = self.get_param("locale") app.url = self.get_param('url') app.put() memcache.delete('app') AppProperties().updateJinjaEnv() self.redirect('/module/admin.application?m='+self.getLocale('Updated'))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class AdminUsers(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return if method == 'GET': self.render('templates/module/admin/admin-users.html') elif self.auth(): nickname = self.get_param('nickname') if nickname is None or nickname == '': self.values['m'] = "Complete Nickname field" self.render('/admin-users.html') return u = model.UserData.all().filter('nickname', nickname).get() if u is None: self.values['m'] = "User '%s' doesn't exists" self.values['arg'] = nickname self.render('/admin-users.html') return action = self.get_param('action') if action == 'block_user': u.banned_date = datetime.datetime.now() u.put() self.values['m'] = "User '%s' was blocked" self.values['arg'] = nickname elif action == 'unblock_user': u.banned_date = None u.put() self.values['m'] = "User '%s' was unlocked" self.values['arg'] = nickname else: self.values['m'] = "Action '%s' not found" self.values['arg'] = action self.render('/admin-users.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class AdminCategoryEdit(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return key = self.get_param('key') self.values['parent_categories'] = list(model.Category.all().filter('parent_category', None).order('title')) self.values['parent_category'] = None if method == 'GET': if key: # show edit form category = model.Category.get(key) self.values['key'] = key self.values['title'] = category.title self.values['description'] = category.description self.values['parent_category'] = str(category.parent_category.key()) self.render('templates/module/admin/admin-category-edit.html') else: # show an empty form self.values['key'] = None self.values['title'] = "New category" self.values['description'] = "Description" self.render('templates/module/admin/admin-category-edit.html') elif self.auth(): title = self.get_param('title') desc = self.get_param('description') if title is None or len(title.strip()) == 0 or desc is None or len(desc.strip()) == 0: self.values['m'] = "Title and description are mandatory fields" self.values['key'] = key self.values['title'] = title self.values['description'] = desc self.values['parent_category'] = self.request.get('parent_category') self.render('templates/module/admin/admin-category-edit.html') return if key: # update category category = model.Category.get(key) category.title = self.get_param('title') category.description = self.get_param('description') category.url_path = self.to_url_path(category.title) parent_key = self.request.get('parent_category') if parent_key: category.parent_category = model.Category.get(parent_key) category.put() self.redirect('/module/admin.categories') else: category = model.Category(title=self.get_param('title'), description=self.get_param('description'), articles = 0, communities = 0) category.url_path = self.to_url_path(category.title) parent_key = self.request.get('parent_category') if parent_key: category.parent_category = model.Category.get(parent_key) category.put() self.redirect('/module/admin.categories')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import img from google.appengine.api import images from google.appengine.api import memcache from handlers.AuthenticatedHandler import * from utilities.AppProperties import AppProperties class AdminCache(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return if method == 'POST': memcache.flush_all() self.values['m'] = "Cache is clean" self.getRelevantCacheData() self.render('templates/module/admin/admin-cache.html') def getRelevantCacheData(self): cacheData = memcache.get_stats() self.values['cdItems'] = cacheData['items'] self.values['cdBytes'] = cacheData['bytes'] self.values['cdOldest'] = cacheData['oldest_item_age']
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import img from google.appengine.api import images from google.appengine.api import memcache from handlers.AuthenticatedHandler import * from utilities.AppProperties import AppProperties class AdminGoogle(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return if method == 'GET': app = self.get_application() self.values['m'] = self.get_param('m') if not app: app = model.Application() self.values['app'] = app self.values['recaptcha_public_key'] = self.not_none(app.recaptcha_public_key) self.values['recaptcha_private_key']= self.not_none(app.recaptcha_private_key) self.values['google_adsense'] = self.not_none(app.google_adsense) self.values['google_adsense_channel']= self.not_none(app.google_adsense_channel) self.values['google_analytics'] = self.not_none(app.google_analytics) self.render('templates/module/admin/admin-google.html') elif self.auth(): app = self.get_application() if not app: app = model.Application() app.recaptcha_public_key = self.get_param('recaptcha_public_key') app.recaptcha_private_key = self.get_param('recaptcha_private_key') app.google_adsense = self.get_param('google_adsense') app.google_adsense_channel = self.get_param('google_adsense_channel') app.google_analytics = self.get_param('google_analytics') app.put() memcache.delete('app') AppProperties().updateJinjaEnv() self.redirect('/module/admin.google?m='+self.getLocale('Updated'))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class AdminStats(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return self.render('templates/module/admin/admin-stats.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import img from google.appengine.api import images from google.appengine.api import memcache from handlers.module.admin.AdminApplication import * from handlers.AuthenticatedHandler import * from utilities.AppProperties import AppProperties class AdminLookAndFeel(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return if method == 'GET': app = self.get_application() self.values['m'] = self.get_param('m') if not app: app = model.Application() self.values['app'] = app self.values['theme'] = self.not_none(app.theme) self.values['max_results'] = self.not_none(app.max_results) self.values['max_results_sublist'] = self.not_none(app.max_results_sublist) self.render('templates/module/admin/admin-lookandfeel.html') elif self.auth(): app = self.get_application() if not app: app = model.Application() logo = self.request.get("logo") if logo: app.logo = images.im_feeling_lucky(logo, images.JPEG) memcache.delete('/images/application/logo') app.theme = self.get_param("theme") if self.get_param('max_results'): app.max_results = int(self.get_param('max_results')) if self.get_param('max_results_sublist'): app.max_results_sublist = int(self.get_param('max_results_sublist')) app.put() memcache.delete('app') AppProperties().updateJinjaEnv() self.redirect('/module/admin.lookandfeel?m='+self.getLocale('Updated'))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class AdminCommunityAddRelated(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return if method == 'GET': self.values['m'] = self.get_param('m') self.render('templates/module/admin/admin-community-add-related.html') elif self.auth(): fromId = self.request.get('community_from') toId = self.request.get('community_to') if fromId is None or len(fromId.strip()) == 0 or not fromId.isdigit(): self.values['m'] = "Enter a valid source community" self.render('templates/module/admin/admin-community-add-related.html') return if toId is None or len(toId.strip()) == 0: self.values['m'] = "Enter a valid target community" self.render('templates/module/admin/admin-community-add-related.html') return community_from = model.Community.get_by_id(int(fromId)) community_to = model.Community.get_by_id(int(toId)) related = model.RelatedCommunity.all().filter('community_from', community_from).filter('community_to', community_to).get() if related: self.redirect('/module/admin.community.add.related?m=Already_exists') return if community_from is None: self.values['m'] = "Source community not found" self.render('templates/module/admin/admin-community-add-related.html') return if community_to is None: self.values['m'] = "Target community not found" self.render('templates/module/admin/admin-community-add-related.html') return self.create_related(community_from, community_to) self.create_related(community_to, community_from) self.redirect('/module/admin.community.add.related?m=Updated') def create_related(self, community_from, community_to): related = model.RelatedCommunity(community_from = community_from, community_to = community_to, community_from_title = community_from.title, community_from_url_path = community_from.url_path, community_to_title = community_to.title, community_to_url_path = community_to.url_path) related.put()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import img from google.appengine.api import images from google.appengine.api import memcache from handlers.AuthenticatedHandler import * from utilities.AppProperties import AppProperties class AdminModules(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return if method == 'GET': app = self.get_application() self.values['m'] = self.get_param('m') if not app: app = model.Application() self.values['app'] = app self.values['appName'] = self.not_none(app.name) self.values['appSubject'] = self.not_none(app.subject) self.values['locale'] = self.not_none(app.locale) self.values['theme'] = self.not_none(app.theme) self.values['url'] = self.not_none(app.url) self.values['mail_contact'] = self.not_none(app.mail_contact) self.values['mail_subject_prefix'] = self.not_none(app.mail_subject_prefix) self.values['mail_sender'] = self.not_none(app.mail_sender) self.values['mail_footer'] = self.not_none(app.mail_footer) self.values['recaptcha_public_key'] = self.not_none(app.recaptcha_public_key) self.values['recaptcha_private_key']= self.not_none(app.recaptcha_private_key) self.values['google_adsense'] = self.not_none(app.google_adsense) self.values['google_adsense_channel']= self.not_none(app.google_adsense_channel) self.values['google_analytics'] = self.not_none(app.google_analytics) self.values['max_results'] = self.not_none(app.max_results) self.values['max_results_sublist'] = self.not_none(app.max_results_sublist) self.render('templates/module/admin/admin-modules.html') elif self.auth(): app = self.get_application() if not app: app = model.Application() app.users = model.UserData.all().count() app.communities = model.Community.all().count() app.threads = model.Thread.all().filter('parent_thread', None).count() app.articles = model.Article.all().filter('draft =', False).filter('deletion_date', None).count() app.name = self.get_param('appName') app.subject = self.get_param("appSubject") app.locale = self.get_param("locale") logo = self.request.get("logo") if logo: app.logo = images.im_feeling_lucky(logo, images.JPEG) memcache.delete('/images/application/logo') app.theme = self.get_param("theme") app.url = self.get_param('url') app.mail_subject_prefix = self.get_param('mail_subject_prefix') app.mail_contact = self.get_param('mail_contact') app.mail_sender = self.get_param('mail_sender') app.mail_footer = self.get_param('mail_footer') app.recaptcha_public_key = self.get_param('recaptcha_public_key') app.recaptcha_private_key = self.get_param('recaptcha_private_key') app.google_adsense = self.get_param('google_adsense') app.google_adsense_channel = self.get_param('google_adsense_channel') app.google_analytics = self.get_param('google_analytics') if self.get_param('max_results'): app.max_results = int(self.get_param('max_results')) if self.get_param('max_results_sublist'): app.max_results_sublist = int(self.get_param('max_results_sublist')) app.put() memcache.delete('app') AppProperties().updateJinjaEnv() self.redirect('/module/admin.application?m='+self.getLocale('Updated'))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import img from google.appengine.api import images from google.appengine.api import memcache from handlers.AuthenticatedHandler import * from utilities.AppProperties import AppProperties class AdminMail(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return if method == 'GET': app = self.get_application() self.values['m'] = self.get_param('m') if not app: app = model.Application() self.values['app'] = app self.values['mail_contact'] = self.not_none(app.mail_contact) self.values['mail_subject_prefix'] = self.not_none(app.mail_subject_prefix) self.values['mail_sender'] = self.not_none(app.mail_sender) self.values['mail_footer'] = self.not_none(app.mail_footer) self.render('templates/module/admin/admin-mail.html') elif self.auth(): app = self.get_application() if not app: app = model.Application() app.mail_subject_prefix = self.get_param('mail_subject_prefix') app.mail_contact = self.get_param('mail_contact') app.mail_sender = self.get_param('mail_sender') app.mail_footer = self.get_param('mail_footer') app.put() memcache.delete('app') AppProperties().updateJinjaEnv() self.redirect('/module/admin.mail?m='+self.getLocale('Updated'))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class Admin(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return self.redirect('/module/admin.application')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class AdminCategories(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] self.values['tab'] = '/admin' if user.rol != 'admin': self.forbidden() return self.add_categories() self.render('templates/module/admin/admin-categories.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class MessageSent(AuthenticatedHandler): def execute(self): user = self.values['user'] query = model.Message.all().filter('user_from', user).filter('from_deletion_date', None) self.values['messages'] = self.paging(query, 10, '-creation_date', user.sent_messages, ['-creation_date']) self.render('templates/module/message/message-sent.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class MessageEdit(AuthenticatedHandler): def execute(self): user = self.values['user'] user_to = model.UserData.all().filter('nickname', self.get_param('user_to')).get() if not user_to: self.not_found() return method = self.request.method if method == 'GET': self.values['user_to'] = self.get_param('user_to') title = self.get_param('title') if not title: title = "New message..." elif not title.startswith('Re:'): title = 'Re:%s' % title self.values['title'] = title self.render('templates/module/message/message-edit.html') return elif self.auth(): title = self.get_param('title') message = model.Message(user_from = user, user_from_nickname = user.nickname, user_to = user_to, user_to_nickname = user_to.nickname, content=self.get_param('content'), title=self.get_param('title'), url_path = '-', read=False) message.put() message.url_path = ('%d/%s') % (message.key().id(), self.to_url_path(title)) message.put() if not user.sent_messages: user.sent_messages = 0 if not user_to.unread_messages: user_to.unread_messages = 0 user.sent_messages += 1 user_to.unread_messages += 1 user.put() user_to.put() app = self.get_application() subject = self.getLocale("%s has send you a missage") % user.nickname # "%s te ha enviado un mensaje" # %s te ha enviado un mensaje.\nLeelo en:\n%s/message.inbox\n body = self.getLocale("%s has send you a missage.\nRead it at:\n%s/message.inbox\n") % (user.nickname, app.url) self.mail(subject=subject, body=body, to=[user_to.email]) self.redirect('/message.sent')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class MessageInbox(AuthenticatedHandler): def execute(self): user = self.values['user'] query = model.Message.all().filter('user_to', user).filter('to_deletion_date', None) self.values['messages'] = self.paging(query, 10, '-creation_date', user.messages, ['-creation_date']) self.render('templates/module/message/message-inbox.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import datetime from handlers.AuthenticatedHandler import * class MessageDelete(AuthenticatedHandler): def execute(self): user = self.values['user'] key = self.request.get('key') message = model.Message.get(key) if not message: self.not_found() return if not self.auth(): return if user.nickname == message.user_to_nickname: message.to_deletion_date = datetime.datetime.now() message.put() self.redirect('/message.inbox') elif user.nickname == message.user_from_nickname: message.from_deletion_date = datetime.datetime.now() message.put() self.redirect('/message.sent') else: self.forbidden()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class MessageRead(AuthenticatedHandler): def execute(self): user = self.values['user'] url_path = self.request.path.split('/', 2)[2] message = model.Message.gql('WHERE url_path=:1', url_path).get() if message.user_to_nickname != user.nickname and message.user_from_nickname != user.nickname: self.forbidden() return if message.user_to_nickname == user.nickname and not message.read: message.read = True message.put() user.unread_messages -= 1 user.put() self.values['message'] = message self.render('templates/module/message/message-read.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseRest import * class ArticleVisit(BaseRest): def get(self): article_id = self.request.get('id') memcache.delete(article_id + '_article') article = model.Article.get_by_id(int(article_id)) article.views += 1 article.put() memcache.add(str(article.key().id()) + '_article', article, 0) content = [] self.render_json("{\"views\" : "+str(article.views)+"}") return
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import datetime from google.appengine.ext import db from handlers.AuthenticatedHandler import * class ArticleDelete(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] article = model.Article.get(self.get_param('key')) memcache.delete(str(article.key().id())) if not article: self.not_found() return if user.rol != 'admin' and user.nickname != article.author.nickname: self.forbidden() return if method == 'GET': self.values['article'] = article self.render('templates/module/article/article-delete.html') elif self.auth(): # mark as deleted article.deletion_message = self.get_param('message') article.deletion_date = datetime.datetime.now() article.deletion_user = user article.put() # decrement tag counters self.delete_tags(article.tags) # decrement author counters if article.draft: article.author.draft_articles -= 1 else: article.author.articles -=1 article.author.rating_total -= article.rating_total article.author.rating_count -= article.rating_count if article.author.rating_count > 0: article.author.rating_average = int(article.author.rating_total / article.author.rating_count) else: article.author.rating_average = 0 article.author.put() # decrement community counters and delete relationships gi = model.CommunityArticle.all().filter('article =', article) for g in gi: g.community.articles -= 1 if g.community.activity: g.community.activity -= 15 g.community g.community.put() g.delete() # decrement favourites and delete relationships fv = model.Favourite.all().filter('article =', article) for f in fv: f.user.favourites -= 1 f.user.put() f.delete() rc = model.Recommendation.all().filter('article_from', article) for r in rc: r.delete() rc = model.Recommendation.all().filter('article_to', article) for r in rc: r.delete() # decrement votes and delete relationships # vt = model.Vote.all().filter('article =', article) # for v in vt: # v.delete() # comments? memcache.delete('index_articles') app = model.Application.all().get() if app: app.articles -= 1 app.put() memcache.delete('app') self.redirect('/module/article/%s' % article.url_path)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * class ArticleList(BaseHandler): def execute(self): self.values['tab'] = '/module/article.list' query = model.Article.all().filter('draft =', False).filter('deletion_date', None) app = self.get_application() key = '%s?%s' % (self.request.path, self.request.query) results = 10 if app.max_results: results = app.max_results self.values['articles'] = self.paging(query, results, '-creation_date', app.articles, ['-creation_date', '-rating_average', '-responses'], key) self.add_tag_cloud() self.render('templates/module/article/article-list.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.BaseHandler import * class ArticleView(BaseHandler): def execute(self): url_path = self.request.path.split('/', 3)[3] article_id = self.request.path.split('/')[3] article = self.cache(article_id + '_article', self.get_article) if not article: self.not_found() return if article.url_path != url_path: self.redirect('/module/article/%s' % article.url_path, permanent=True) return if not article.author_nickname: article.author_nickname = article.author.nickname article.put() user = self.values['user'] if article.deletion_date and (not user or (user.rol != 'admin' and article.author_nickname != user.nickname)): self.values['article'] = article self.error(404) self.render('templates/module/article/article-deleted.html') return self.values['tab'] = '/module/article.list' if article.draft and (not user or not user.nickname == article.author_nickname): self.not_found() return if user and user.nickname != article.author_nickname: vote = model.Vote.gql('WHERE user=:1 AND article=:2', user, article).get() if not vote: self.values['canvote'] = True if user: added = model.Favourite.gql('WHERE user=:1 AND article=:2',user,article).get() if not added: self.values['canadd'] = True if user: if user.email in article.subscribers: self.values['cansubscribe'] = False else: self.values['cansubscribe'] = True self.values['article'] = article results = 10 app = self.get_application() if app.max_results_sublist: results = app.max_results_sublist query = model.Comment.all().filter('article =', article) comments = self.paging(query, results, 'creation_date', article.responses, 'creation_date') # migration i = 1 for c in comments: if not c.author_nickname: c.author_nickname = c.author.nickname c.put() if not c.response_number: c.response_number = i c.put() i += 1 # end migration self.values['comments'] = comments self.values['a'] = 'comments' self.values['keywords'] = ', '.join(article.tags) communities = model.CommunityArticle.all().filter('article', article).order('community_title') # communities = self.cache(str(article.key().id()) + '_communities', self.get_communities) self.values['communities'] = list(communities) if user and article.author_nickname == user.nickname: all_communities = list(model.CommunityUser.all().filter('user', user).order('community_title')) # TODO: this could be improved for g in communities: for gr in all_communities: if gr.community_url_path == g.community_url_path: all_communities.remove(gr) if all_communities: self.values['all_communities'] = all_communities self.values['content_html'] = self.cache(str(article.key().id()) + '_html', self.to_html) self.values['related'] = list(model.Recommendation.all().filter('article_from', article).order('-value').fetch(5)) self.render('templates/module/article/article-view.html') def to_html(self): article = self.values['article'] if not article.content_html: html = model.ArticleHtml(content=self.markdown(article.content)) html = model.ArticleHtml(content=self.media_content(article.content)) html.put() article.content_html = html article.put() return article.content_html.content def get_communities(self): article = self.values['article'] return model.CommunityArticle.all().filter('article', article).order('community_title') def get_author(self): article = self.values['article'] return model.UserData.all().filter('nickname', article.author_nickname).get() def get_article(self): article_id = self.request.path.split('/')[3] return model.Article.get_by_id(int(article_id))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.AuthenticatedHandler import * class ArticleCommentEdit(AuthenticatedHandler): def execute(self): self.values['tab'] = '/module/article.list' method = self.request.method user = self.values['user'] comment_key = self.get_param('key') if method == 'GET': if comment_key: # show edit form comment = model.Comment.get(comment_key) if user.nickname != comment.author_nickname and user.rol != 'admin': self.forbidden() return if comment is None: self.not_found() return self.values['article'] = comment.article self.values['comment'] = comment self.values['comment_key'] = comment.key self.render('templates/module/article/article-comment-edit.html') return else: self.show_error("Comment not found") return elif self.auth(): if comment_key: # update comment comment = model.Comment.get(comment_key) if user.nickname != comment.author_nickname and user.rol != 'admin': self.forbidden() return if not comment: self.not_found() return content = self.get_param('content') if not content: self.values['article'] = comment.article self.values['comment'] = comment self.values['comment_key'] = comment.key self.values['m'] = "Content is mandatory" self.render('templates/module/article/article-comment-edit.html') return comment.content = content if user.rol != 'admin': if comment.editions is None: comment.editions = 0 comment.editions +=1 comment.last_edition = datetime.datetime.now() comment.put() results = 10 app = self.get_application() if app.max_results_sublist: results = app.max_results_sublist page = comment.response_number / results if (comment.response_number % results) > 0: page += 1 self.redirect('/module/article/%s?p=%d#comment-%s' % (comment.article.url_path, page, comment.response_number)) else: self.show_error("Comment not found") return
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Carrasco <jose.carrasco[at]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * from utilities.TTSUtil import * class ArticleTTS(BaseHandler): def execute(self): url_path = self.request.path.split('/', 3)[3] article_id = self.request.path.split('/')[3] article = self.cache(article_id + '_article', self.get_article) if not article: self.not_found() return if article.url_path != url_path: self.redirect('/module/article/%s' % article.url_path, permanent=True) return if not article.author_nickname: article.author_nickname = article.author.nickname article.put() user = self.values['user'] if article.deletion_date and (not user or (user.rol != 'admin' and article.author_nickname != user.nickname)): self.values['article'] = article self.error(404) self.render('templates/module/article/article-deleted.html') return self.values['tab'] = '/module/article.list' if article.draft and (not user or not user.nickname == article.author_nickname): self.not_found() return if user and user.nickname != article.author_nickname: vote = model.Vote.gql('WHERE user=:1 AND article=:2', user, article).get() if not vote: self.values['canvote'] = True if user: added = model.Favourite.gql('WHERE user=:1 AND article=:2',user,article).get() if not added: self.values['canadd'] = True if user: if user.email in article.subscribers: self.values['cansubscribe'] = False else: self.values['cansubscribe'] = True self.values['article'] = article results = 10 app = self.get_application() if app.max_results_sublist: results = app.max_results_sublist query = model.Comment.all().filter('article =', article) comments = self.paging(query, results, 'creation_date', article.responses, 'creation_date') # migration i = 1 for c in comments: if not c.author_nickname: c.author_nickname = c.author.nickname c.put() if not c.response_number: c.response_number = i c.put() i += 1 # end migration self.values['comments'] = comments self.values['a'] = 'comments' self.values['keywords'] = ', '.join(article.tags) communities = model.CommunityArticle.all().filter('article', article).order('community_title') # communities = self.cache(str(article.key().id()) + '_communities', self.get_communities) self.values['communities'] = list(communities) if user and article.author_nickname == user.nickname: all_communities = list(model.CommunityUser.all().filter('user', user).order('community_title')) # TODO: this could be improved for g in communities: for gr in all_communities: if gr.community_url_path == g.community_url_path: all_communities.remove(gr) if all_communities: self.values['all_communities'] = all_communities self.values['content_html'] = self.cache(str(article.key().id()) + '_html', self.to_html) self.values['related'] = list(model.Recommendation.all().filter('article_from', article).order('-value').fetch(5)) #self.render('templates/module/article/article-view.html') tts_util=TTSUtil() content="" tts_urls=[] # render the title tts_urls.extend(tts_util.get_tts_url_from_html(article.title)) # render the author tts_urls.extend(tts_util.get_tts_url_from_html("Escrito por " + article.author.nickname)) # render the content tts_urls.extend(tts_util.get_tts_url_from_html(article.content)) # get the stream content=tts_util.get_tts_stream_from_tts_urs(tts_urls) self.response.headers['Content-Type'] = 'audio/x-mp3' self.response.out.write(content) def to_html(self): article = self.values['article'] if not article.content_html: html = model.ArticleHtml(content=self.markdown(article.content)) html = model.ArticleHtml(content=self.media_content(article.content)) html.put() article.content_html = html article.put() return article.content_html.content def get_communities(self): article = self.values['article'] return model.CommunityArticle.all().filter('article', article).order('community_title') def get_author(self): article = self.values['article'] return model.UserData.all().filter('nickname', article.author_nickname).get() def get_article(self): article_id = self.request.path.split('/')[3] return model.Article.get_by_id(int(article_id))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.AuthenticatedHandler import * class ArticleCommentSubscribe( AuthenticatedHandler ): def execute(self): key = self.get_param('key') article = model.Article.get(key) memcache.delete(str(article.key().id()) + '_article') user = self.values['user'] mail = user.email if not mail in article.subscribers: if not self.auth(): return article.subscribers.append(mail) article.put() self.add_user_subscription(user, 'article', article.key().id()) memcache.add(str(article.key().id()) + '_article', article, 0) if self.get_param('x'): self.render_json({ 'action': 'subscribed' }) else: self.redirect('/module/article/%s' % (article.url_path, )) else: auth = self.get_param('auth') if not auth: memcache.add(str(article.key().id()) + '_article', article, 0) self.values['article'] = article self.render('templates/module/article/article-comment-subscribe.html') else: if not self.auth(): return article.subscribers.remove(mail) article.put() self.remove_user_subscription(user, 'article', article.key().id()) memcache.add(str(article.key().id()) + '_article', article, 0) if self.get_param('x'): self.render_json({ 'action': 'unsubscribed' }) else: self.redirect('/module/article/%s' % (article.url_path, ))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import time import datetime from google.appengine.ext import db from google.appengine.api import memcache from handlers.AuthenticatedHandler import * from utilities.TTSUtil import * class ArticleEdit(AuthenticatedHandler): def execute(self): self.values['tab'] = '/module/article.list' method = self.request.method user = self.values['user'] key = self.get_param('key') x = self.get_param('x') draft = False if self.get_param('save_draft'): draft = True licenses = [ { 'id': 'copyright', 'lic': '&copy; Todos los derechos reservados' }, { 'id': 'pd', 'lic': u'Dominio público' }, { 'id': 'by', 'lic': 'Creative Commons: Reconocimiento' }, { 'id': 'by-nc', 'lic': 'Creative Commons: Reconocimiento-No comercial' }, { 'id': 'by-nc-nd', 'lic': 'Creative Commons: Reconocimiento-No comercial-Sin obras derivadas' }, { 'id': 'by-nc-sa', 'lic': 'Creative Commons: Reconocimiento-No comercial-Compartir bajo la misma licencia' }, { 'id': 'by-nd', 'lic': 'Creative Commons: Reconocimiento-Sin obras derivadas' }, { 'id': 'by-sa', 'lic': 'Creative Commons: Reconocimiento-Compartir bajo la misma licencia' } ] self.values['licenses'] = licenses if method == 'GET': if key: # show edit form article = model.Article.get(key) if not article: self.not_found() return if not user.nickname == article.author.nickname and user.rol != 'admin': self.forbidden() return self.values['key'] = key self.values['title'] = article.title self.values['lic'] = article.lic self.values['tags'] = ', '.join(article.tags) self.values['description'] = article.description self.values['content'] = article.content self.values['draft'] = article.draft self.render('templates/module/article/article-edit.html') else: # show an empty form self.values['title'] = u'Título...' self.values['lic'] = 'copyright' self.values['draft'] = True self.render('templates/module/article/article-edit.html') elif self.auth(): if x and draft: # check mandatory fields if not self.get_param('title') or not self.get_param('tags') or not self.get_param('description') or not self.get_param('content'): self.render_json({ 'saved': False }) return if key: # update article article = model.Article.get(key) memcache.delete(str(article.key().id()) + '_html') if not article: self.not_found() return if not user.nickname == article.author.nickname and user.rol != 'admin': self.forbidden() return lic = self.get_param('lic') lics = [license['id'] for license in licenses] if not lic in lics: lic = 'copyright' if not article.draft: self.delete_tags(article.tags) article.lic = lic article.tags = self.parse_tags(self.get_param('tags')) article.description = ' '.join(self.get_param('description').splitlines()) article.content = self.get_param('content') if article.draft: # title and url_path can change only if the article hasn't already been published article.title = self.get_param('title') article.url_path = '%d/%s' % (article.key().id(), self.to_url_path(article.title)) add_communities = False if article.draft and not draft: article.draft = draft user.articles += 1 user.draft_articles -=1 user.put() article.creation_date = datetime.datetime.now() self.add_follower(article=article, nickname=user.nickname) followers = list(self.get_followers(user=user)) followers.append(user.nickname) self.create_event(event_type='article.new', followers=followers, user=user, article=article) app = model.Application.all().get() if app: app.articles += 1 app.put() memcache.delete('app') add_communities = True if not article.draft: self.create_recommendations(article) if not article.author_nickname: article.author_nickname = user.nickname if not article.content_html: html = model.ArticleHtml(content=article.content) html.put() article.content_html = html else: html_content = article.content html_content = self.media_content(html_content) article.content_html.content = html_content article.content_html.put() article.put() memcache.delete('index_articles') memcache.delete('tag_cloud') memcache.delete(str(article.key().id())) if not draft: self.update_tags(article.tags) if x: self.render_json({ 'saved': True, 'key' : str(article.key()), 'updated' : True, "draft_articles" : str(user.draft_articles) }) else: if add_communities: self.redirect('/module/article.add.communities?key=%s' % str(article.key())) else: self.redirect('/module/article/%s' % article.url_path) else: # new article today = datetime.date.today() title = self.get_param('title') tags = self.parse_tags(self.get_param('tags')) lic = self.get_param('lic') lics = [license['id'] for license in licenses] if not lic in lics: lic = 'copyright' article = model.Article(author=user, author_nickname=user.nickname, title=title, description=' '.join(self.get_param('description').splitlines()), content=self.get_param('content'), lic=lic, url_path='empty', tags=tags, draft=draft, article_type='article', views=0, responses=0, rating_count=0, rating_total=0, favourites=0) html_content = article.content html = model.ArticleHtml(content=self.media_content(html_content)) html.put() article.content_html = html article.subscribers = [user.email] self.set_tts(article) article.put() self.add_user_subscription(user, 'article', article.key().id()) article.url_path = '%d/%s' % (article.key().id(), self.to_url_path(article.title)) article.put() memcache.delete('index_articles') memcache.delete('tag_cloud') memcache.delete(str(article.key().id())) if not draft: self.create_recommendations(article) user.articles += 1 user.put() self.update_tags(tags) self.add_follower(article=article, nickname=user.nickname) followers = list(self.get_followers(user=user)) followers.append(user.nickname) self.create_event(event_type='article.new', followers=followers, user=user, article=article) app = model.Application.all().get() if app: app.articles += 1 app.put() memcache.delete('app') else: user.draft_articles += 1 user.put() if x: self.render_json({ 'saved': True, 'key' : str(article.key()), "updated" : False, "draft_articles" : str(user.draft_articles) }) else: if article.draft: self.redirect('/module/article/%s' % article.url_path) else: self.redirect('/module/article.add.communities?key=%s' % str(article.key())) def create_recommendations(self, article): self.create_task('article_recommendation', 1, {'article': article.key().id(), 'offset': 0}) def set_tts(self, article): tts_util=TTSUtil() content="" tts_urls=[] # render the title tts_urls.extend(tts_util.get_tts_url_from_html(article.title)) # render the author tts_urls.extend(tts_util.get_tts_url_from_html("Escrito por " + article.author.nickname)) # render the content tts_urls.extend(tts_util.get_tts_url_from_html(article.content)) # get the stream content=tts_util.get_tts_stream_from_tts_urs(tts_urls) # TODO Removed because fail ... #article.content_tts.tts_stream=content #article.content_tts.tts_urls=tts_urls
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.AuthenticatedHandler import * class ArticleAddCommunities(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] key = self.get_param('key') article = model.Article.get(key) if not article or article.draft or article.deletion_date: self.not_found() return if not user.nickname == article.author.nickname: self.forbidden() return if method == 'GET': self.values['key'] = key self.values['article'] = article communities = list(model.CommunityUser.all().filter('user', user).order('community_title')) self.values['communities'] = communities if not communities: self.redirect('/module/article/%s' % article.url_path) return self.render('templates/module/article/article-add-communities.html') elif self.auth(): arguments = self.request.arguments() for gu in model.CommunityUser.all().filter('user', user).order('community_title'): community = gu.community if self.request.get('community-%d' % community.key().id()): gi = model.CommunityArticle.all().filter('community', community).filter('article', article).count(1) if not gi: community.articles += 1 if community.activity: community.activity += 15 community.put() gi = model.CommunityArticle(community=community, article=article, article_author_nickname = article.author_nickname, article_title = article.title, article_url_path = article.url_path, community_title = community.title, community_url_path = community.url_path) gi.put() followers = list(self.get_followers(community=community)) self.create_event(event_type='community.addarticle', followers=followers, user=user, community=community, article=article) self.redirect('/module/article/%s' % article.url_path)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import datetime from google.appengine.ext import db from handlers.AuthenticatedHandler import * class ArticleCommentDelete(AuthenticatedHandler): def execute(self): user = self.values['user'] if user.rol != 'admin': self.forbidden() return if not self.auth(): return comment = model.Comment.get(self.get_param('key')) if not comment: self.not_found() return url = comment.article.url_path message = self.get_param('message') #decrement nomber of comments in the User comment.author.comments -= 1 comment.author.put() #delete comment comment.deletion_date = datetime.datetime.now() comment.deletion_message = message comment.put() self.redirect('/module/article/%s' % url)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import time import datetime from google.appengine.ext import db from google.appengine.api import mail from handlers.AuthenticatedHandler import * class ArticleComment(AuthenticatedHandler): def execute(self): user = self.values['user'] key = self.get_param('key') article = model.Article.get(key) memcache.delete(str(article.key().id()) + '_article') if not article or article.draft or article.deletion_date: self.not_found() return if not self.auth(): return content = self.get_param('content') if not content: self.show_error("Content is mandatory") return preview = self.get_param('preview') if preview: comment = model.Comment(article=article, author=user, author_nickname=user.nickname, content=content) self.values['comment'] = comment self.values['preview'] = True self.render('templates/module/article/article-comment-edit.html') return if self.check_duplicate(article, user, content): self.show_error("Duplicated comment") return # migration if not article.subscribers: com = [c.author.email for c in model.Comment.all().filter('article', article).fetch(1000) ] com.append(article.author.email) article.subscribers = list(set(com)) # end migration comment = model.Comment(article=article, author=user, author_nickname=user.nickname, content=content, editions = 0, response_number=article.responses+1) comment.put() results = 10 app = self.get_application() if app.max_results_sublist: results = app.max_results_sublist page = comment.response_number / results if (comment.response_number % results) > 0: page += 1 comment_url = '/module/article/%s?p=%d#comment-%d' % (article.url_path, page, comment.response_number) user.comments += 1 user.put() article.responses += 1 article.put() followers = list(self.get_followers(user=user)) followers.append(user.nickname) followers.extend(self.get_followers(article=article)) followers = list(set(followers)) self.create_event(event_type='article.comment', followers=followers, user=user, article=article, response_number=comment.response_number) memcache.add(str(article.key().id()) + '_article', article, 0) subscribers = article.subscribers if subscribers and user.email in subscribers: subscribers.remove(user.email) if subscribers: subject = self.getLocale("New comment in: '%s'") % self.clean_ascii(article.title) #Nuevo comentario en el artículo: '%s':\n%s%s\n\nTodos los comentarios en:\n%s/module/article/%s#comments\n\nEliminar suscripción a este artículo:\n%s/module/article.comment.subscribe?key=%s\n body = self.getLocale("New comment in article: '%s':\n%s%s\n\nAll comments at:\n%s/module/article/%s#comments\n\nUnsuscribe this article:\n%s/module/article.comment.subscribe?key=%s\n") % (self.clean_ascii(article.title), app.url, comment_url, app.url, article.url_path, app.url, str(article.key())) self.mail(subject=subject, body=body, bcc=subscribers) subscribe = self.get_param('subscribe') if subscribe and not user.email in article.subscribers: article.subscribers.append(user.email) self.redirect(comment_url) def check_duplicate(self, article, user, content): last_comment = model.Comment.all().filter('article', article).filter('author', user).order('-creation_date').get() if last_comment is not None: if last_comment.content == content: return True return False
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.AuthenticatedHandler import * class ArticleFavourite(AuthenticatedHandler): def execute(self): article = model.Article.get(self.get_param('key')) user = self.values['user'] if not article or article.draft or article.deletion_date: self.not_found() return if not self.auth(): return favourite = model.Favourite.gql('WHERE user=:1 AND article=:2', user, article).get() if not favourite: favourite = model.Favourite(article=article, user=user, article_author_nickname=article.author_nickname, article_title=article.title, article_url_path=article.url_path, user_nickname=user.nickname) favourite.put() user.favourites += 1 user.put() followers = list(self.get_followers(user=user)) followers.append(user.nickname) followers.extend(self.get_followers(article=article)) followers = list(set(followers)) self.create_event(event_type='article.favourite', followers=followers, user=user, article=article) if self.get_param('x'): self.render_json({ 'action': 'added' }) else: self.redirect('/module/article/%s' % article.url_path) else: favourite.delete() user.favourites -= 1 user.put() if self.get_param('x'): self.render_json({ 'action': 'deleted' }) else: self.redirect('/module/article/%s' % article.url_path)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from handlers.AuthenticatedHandler import * class ArticleVote(AuthenticatedHandler): def execute(self): article = model.Article.get(self.get_param('key')) if not article or article.draft or article.deletion_date: self.not_found() return if not self.auth(): return memcache.delete(str(article.key().id()) + '_article') rating = int(self.get_param('rating')) if rating < 0: rating = 0 elif rating > 5: rating = 5 user = self.values['user'] avg = article.rating_average if article and article.author.nickname != user.nickname: vote = model.Vote.gql('WHERE user=:1 and article=:2', user, article).get() if not vote: vote = model.Vote(user=user,rating=rating,article=article) vote.put() article.rating_count += 1 article.rating_total += rating article.rating_average = int(article.rating_total / article.rating_count) article.put() author = article.author author.rating_count += 1 author.rating_total += rating author.rating_average = int(author.rating_total / author.rating_count) author.put() avg = article.rating_average memcache.add(str(article.key().id()) + '_article', article, 0) if self.get_param('x'): self.render_json({ 'average': avg, 'votes': article.rating_count }) else: self.redirect('/module/article/%s' % article.url_path)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * class Dispatcher(BaseHandler): def execute(self): referer = self.request.path.split('/', 1)[1] # if referer.startswith('module'): # referer = self.request.path.split('/',2)[2] self.add_tag_cloud() self.values['tab'] = self.request.path self.render('templates/%s.html' % referer)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import re import model import datetime from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.api import memcache from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError from utilities import Constant from utilities.AppProperties import AppProperties class BaseHandler(webapp.RequestHandler): ######################### ### Handler functions ### ######################### def get(self): if self.request.url.split('/')[2] == AppProperties().getAppDic().get(Constant.domain):#'vikuit.com': self.redirect(self.get_application().url + self.request.url.split('/', 3)[3], permanent=True)# 'http://www.vikuit.com/' return try: self.common_stuff() self.pre_execute() except CapabilityDisabledError: self.values = {} self.render('templates/maintenace.html') return def post(self): self.common_stuff() self.pre_execute() def pre_execute(self): self.execute() def common_stuff(self): self.values = {} self.user = None import session #app = model.Application.all().get() app = self.get_application() if app: self.sess = session.Session(app.session_seed) if self.sess.load(): self.user = self.get_current_user() elif self.is_google_account(): #google account users.get_current_user() #user only arrives here 1 time per session self.user = self.get_current_user() if self.user: redirect, self.user = self.store_google_account() self.sess.store(str(self.user.key()), 7200) if redirect: # redirect to preferences page self.redirect("/module/user.edit") if self.user.banned_date is not None: msg = self.getLocale("User '%s' was blocked. Contact with an administrator.") % self.user.nickname() self.show_error( msg ) else: self.sess = None redirect = '%s?%s' % (self.request.path, self.request.query) self.values['sess'] = self.sess self.values['redirect'] = redirect self.values['app'] = self.get_application() self.values['activity_communities'] = self.communities_by_activity() #self.values['all_user_communities'] = self.all_user_communities() if self.user: self.values['auth'] = self.sess.auth self.values['logout'] = '/module/user.logout?redirect_to=%s&auth=%s' % (self.quote(redirect), self.sess.auth) """ user_data = model.UserData.gql('WHERE email=:1', user.email()).get() if not user_data: user_data = model.UserData(email=user.email(), nickname=user.nickname(), articles=0, draft_articles=0, messages=0, draft_messages=0, comments=0, rating_count=0, rating_total=0, rating_average=0, threads=0, responses=0, communities=0, favourites=0, public=False) user_data.put() self.values['user'] = user_data """ # TODO deprecated, use self.user instead self.values['user'] = self.user else: self.user = None self.values['user'] = None self.values['login'] = '/module/user.login?redirect_to=%s' % self.quote(redirect) # users.create_login_url(self.values['redirect']) self.values['glogin'] = users.create_login_url(self.values['redirect']) ################################################# ### Authentication and Autorization functions ### ################################################# def hash(self, login, p, times=100): import sha p = p.encode('ascii', 'ignore') p = '%s:%s' % (login, p) for i in range(0, times): p = sha.new(p).hexdigest() return p def can_write(self, community): if community.all_users is None or community.all_users: return True user = self.values['user'] if not user: return False if model.CommunityUser.all().filter('community', community).filter('user', user).get(): return True return False def check_password(self, user, password): times = 100 user_password = user.password s = user.password.split(':') if len(s) > 1: times = int(s[0]) user_password = s[1] return self.hash(user.nickname, password, times) == user_password def hash_password(self, nickname, password): times = 1 return '%d:%s' % (times, self.hash(nickname, password, times)) def auth(self): token = self.values['auth'] b = token == self.get_param('auth') if not b: self.forbidden() return b def get_current_user(self): if self.sess.user:##first return db.get(self.sess.user) user = users.get_current_user()#login with google account # if user: # user = model.UserData.gql('WHERE email=:1', user.email()).get() return user def is_google_account(self): user = users.get_current_user() if user: return True else: return False def store_google_account(self): googleAcc = users.get_current_user() user = model.UserData.gql('WHERE email=:1', googleAcc.email()).get() redirectPreferences = False if user is None: redirectPreferences = True nick = self.getNickname(googleAcc.nickname()) user = model.UserData(nickname=nick, email=googleAcc.email(), password=None,#Change to optional articles=0, draft_articles=0, messages=0, draft_messages=0, comments=0, rating_count=0, rating_total=0, rating_average=0, threads=0, responses=0, communities=0, favourites=0, public=False, contacts=0) user.registrationType = 1 #Google identifier user.last_login = datetime.datetime.now() user.put() if redirectPreferences: # Is new user app = model.Application.all().get() if app: app.users += 1 app.put() memcache.delete('app') return redirectPreferences, user def getNickname(self, nick, isMail=True): if isMail: return nick.split('@')[0] else: return nick ########################### ### Bussiness functions ### ########################### def add_user_subscription(self, user, subscription_type, subscription_id): user_subscription = model.UserSubscription(user=user, user_nickname=user.nickname, user_email=user.email, subscription_type=subscription_type, subscription_id=subscription_id, creation_date = datetime.datetime.now()) subscription = model.UserSubscription.all().filter('user', user).filter('subscription_type', subscription_type).filter('subscription_id', subscription_id).get() if subscription is None: user_subscription.put() def remove_user_subscription(self, user, subscription_type, subscription_id): user_subscription = model.UserSubscription.all().filter('user', user).filter('subscription_type', subscription_type).filter('subscription_id', subscription_id).get() if user_subscription is not None: user_subscription.delete() def add_follower(self, community=None, user=None, article=None, thread=None, nickname=None): object_type = None obj = None if user is not None: object_type = 'user' obj = user elif community is not None: object_type = 'community' obj = community elif thread is not None: object_type = 'thread' obj = thread elif article is not None: object_type = 'article' obj = article if object_type is None: return None follower = model.Follower.all().filter('object_type', object_type).filter('object_id', obj.key().id()).get() if follower: if nickname not in follower.followers: follower.followers.append(nickname) follower.put() else: follower = model.Follower(object_type=object_type, object_id=obj.key().id(), followers=[nickname]) follower.put() def remove_follower(self, community=None, user=None, article=None, thread=None, nickname=None): object_type = None obj = None if user is not None: object_type = 'user' obj = user elif community is not None: object_type = 'community' obj = community elif thread is not None: object_type = 'thread' obj = thread elif article is not None: object_type = 'article' obj = article if object_type is None: return None follower = model.Follower.all().filter('object_type', object_type).filter('object_id', obj.key().id()).get() if follower: if nickname in follower.followers: follower.followers.remove(nickname) follower.put() def create_event(self, event_type, followers, user, user_to=None, community=None, article=None, thread=None, creation_date=None, response_number=0): event = model.Event(event_type=event_type, followers=followers, user=user, user_nickname=user.nickname, response_number=response_number) if user_to is not None: event.user_to = user_to event.user_to_nickname = user_to.nickname if community is not None: event.community = community event.community_title = community.title event.community_url_path = community.url_path if article is not None: event.article = article event.article_title = article.title event.article_author_nickname = article.author_nickname event.article_url_path = article.url_path if thread is not None: event.thread = thread event.thread_title = thread.title event.thread_url_path = thread.url_path if creation_date is None: event.creation_date = datetime.datetime.now() else: event.creation_date = creation_date event.put() def get_followers(self, user=None, community=None, thread=None, article=None): object_type = None obj = None if user is not None: object_type = 'user' obj = user elif community is not None: object_type = 'community' obj = community elif thread is not None: object_type = 'thread' obj = thread elif article is not None: object_type = 'article' obj = article if object_type is None: return None object_id = obj.key().id() follower = model.Follower.all().filter('object_type', object_type).filter('object_id', object_id).get() if not follower: follower = model.Follower(object_type=object_type, object_id=object_id, followers=[]) follower.put() return follower.followers def create_task(self, task_type, priority, data): import simplejson t = model.Task(task_type=task_type, priority=priority, data=simplejson.dumps(data)) t.put() def is_contact(self, this_user): user = self.values['user'] if not user: return False if model.Contact.all().filter('user_from', user).filter('user_to', this_user).get(): return True return False def create_community_subscribers(self, community): if not community.subscribers: com = [g.user.email for g in model.CommunityUser.all().filter('community', community).fetch(1000) ] community.subscribers = list(set(com)) # I use strings in order to distinguish three values into the templates # 'True', 'False', and None def joined(self, community): gu = model.CommunityUser.gql('WHERE community=:1 and user=:2', community, self.values['user']).get() if gu is not None: return 'True' return 'False' def communities_by_activity(self): key = 'activity_communities' g = memcache.get(key) if g is not None: return g else: communities = model.Community.all().order('-activity').fetch(15) memcache.add(key, communities, 3600) return communities def all_user_communities(self): key = 'all_user_communities' g = memcache.get(key) if g is not None: return g else: all_user_communities = model.Community.all() memcache.add(key, all_user_communities, 3600) return all_user_communities def add_categories(self): cats = model.Category.all().order('title').fetch(50) categories = {} for category in cats: # legacy code if not category.url_path: category.url_path = self.to_url_path(category.title) category.put() # end if category.parent_category is None: categories[str(category.key())] = category for category in cats: if category.parent_category is not None: parent_category = categories[str(category.parent_category.key())] if not parent_category.subcategories: parent_category.subcategories = [] parent_category.subcategories.append(category) ret = [categories[key] for key in categories] ret.sort() self.values['categories'] = ret def add_tag_cloud(self): self.values['tag_cloud'] = self.cache('tag_cloud', self.get_tag_cloud) def get_tag_cloud(self): return self.tag_list(model.Tag.all().order('-count').fetch(30)) def parse_tags(self, tag_string): tags = [self.to_url_path(t) for t in tag_string.split(',')] return list(set(tags)) def delete_tags(self, tags): tags=set(tags) for tag in tags: t = model.Tag.gql('WHERE tag=:1', tag).get() if t: if t.count == 1: t.delete() else: t.count = t.count - 1 t.put() def update_tags(self, tags): tags=set(tags) for tag in tags: t = model.Tag.gql('WHERE tag=:1', tag).get() if not t: tg = model.Tag(tag=tag,count=1) tg.put() else: t.count = t.count + 1 t.put() def tag_list(self, tags): tagdict={} for t in tags: tagdict[t.tag] = t.count if not tagdict: return [] maxcount = max(t.count for t in tags) taglist = [(tag, 6*tagdict[tag]/maxcount, tagdict[tag]) for tag in tagdict.keys()] taglist.sort() return taglist ############################### ### Evnironment And Renders ### ############################### def create_jinja_environment(self): env = AppProperties().getJinjaEnv() env.filters['relativize'] = self.relativize env.filters['markdown'] = self.markdown env.filters['smiley'] = self.smiley env.filters['pagination'] = self.pagination env.filters['media'] = self.media_content env.filters['quote'] = self.quote return env def get_template(self, env, f): p = f.split('/') if p[0] == 'templates': f = '/'.join(p[1:]) t = env.get_template(f) return t def render_chunk(self, f, params): env = self.create_jinja_environment() t = self.get_template(env, f) return t.render(params) def render(self, f): self.response.headers['Content-Type'] = 'text/html;charset=UTF-8' self.response.headers['Pragma'] = 'no-cache' self.response.headers['Cache-Control'] = 'no-cache' self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT' self.response.out.write(self.render_chunk(f, self.values)) def render_json(self, data): import simplejson self.response.headers['Content-Type'] = 'application/json;charset=UTF-8' self.response.headers['Pragma'] = 'no-cache' self.response.headers['Cache-Control'] = 'no-cache' self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT' self.response.out.write(simplejson.dumps(data)) def relativize(self, value): now = datetime.datetime.now() try: diff = now - value except TypeError: return '' days = diff.days seconds = diff.seconds if days > 365: return self.getLocale("%d years") % (days / 365, ) #u"%d años" % (days / 365, ) if days > 30: return self.getLocale("%d months") % (days / 30, ) #u"%d meses" % (days / 30, ) if days > 0: return self.getLocale("%d days") % (days, ) # u"%d días" % (days, ) if seconds > 3600: return self.getLocale("%d hours") % (seconds / 3600, ) # u"%d horas" % (seconds / 3600, ) if seconds > 60: return self.getLocale("%d minutes") % (seconds / 60, ) # u"%d minutos" % (seconds / 60, ) return self.getLocale("%d seconds") % (seconds, ) # u"%d segundos" % (seconds, ) def smiley(self, value): return value def markdown(self, value): try: import markdown except ImportError: return "error" else: return markdown.markdown(value, [], safe_mode='escape') def quote(self, value): import urllib value = self.get_unicode(value) return urllib.quote((value).encode('UTF-8')) def media_content(self,value): import MediaContentFilters as contents value=contents.media_content(value) return value ########################### ### Utilities functions ### ########################### def mail(self, subject, body, to=[], bcc=[]): app = self.get_application() subject = "%s %s" % (app.mail_subject_prefix, subject) body = """ %s %s """ % (body,app.mail_footer) queue = model.MailQueue(subject=subject, body=body, to=to, bcc=bcc) queue.put() def show_error(self, message): self.values['message'] = message self.render('templates/error.html') """ def handle_exception(self, exception): self.response.clear() self.response.set_status(500) self.render('templates/error500.html') """ def not_found(self): self.response.clear() self.response.set_status(404) self.render('templates/error404.html') def forbidden(self): self.response.clear() self.response.set_status(403) self.render('templates/error403.html') def getLocale(self, label): return self.render_chunk("/translator-util.html", {"label": label}) def get_application(self): return self.cache('app', self.fetch_application) def fetch_application(self): return model.Application.all().get() def value(self, key): try: return self.values[key] except KeyError: return None def not_none(self, value): if not value: return '' return value def get_param(self, key): return self.get_unicode(self.request.get(key)) def get_unicode(self, value): try: value = unicode(value, "utf-8") except TypeError: return value return value def cache(self, key, function, timeout=0): # import logging # logging.debug('looking for %s in the cache' % key) data = memcache.get(key) if data is not None: # logging.debug('%s is already in the cache' % key) return data else: data = function.__call__() # logging.debug('inserting %s in the cache' % key) memcache.add(key, data, timeout) return data """ def cache_this(self, function, timeout=600): key = '%s?%s' % (self.request.path, self.request.query) return self.cache(key, function, timeout) def pre_pag(self, query, max, default_order=None): try: p = int(self.get_param('p')) except ValueError: p = 1 offset = (p-1)*max o = self.get_param('o') if o: query = query.order(o) self.values['o'] = o elif default_order: query = query.order(default_order) return [obj for obj in query.fetch(max+1, offset)] def post_pag(self, a, max): try: p = int(self.get_param('p')) except ValueError: p = 1 self.values['p'] = p if p > 1: self.values['prev'] = p-1 l = len(a) if l > max: self.values['len'] = max self.values['next'] = p+1 return a[:max] self.values['len'] = l o = self.get_param('o') if o: self.values['o'] = o return a """ def paging(self, query, max, default_order=None, total=-1, accepted_orderings=[], key=None, timeout=300): if total > 0: pages = total / max if total % max > 0: pages += 1 self.values['pages'] = pages i = 1 pagesList = [] while i <= pages: pagesList.append(i) i += 1 self.values['pagesList'] = pagesList try: p = int(self.get_param('p')) if p < 1: p = 1 except ValueError: p = 1 self.values['p'] = p offset = (p-1)*max #if offset > 1000: # return None o = self.get_param('o') if o and o in accepted_orderings: query = query.order(o) self.values['o'] = o elif default_order: query = query.order(default_order) # caching if not key is None: a = memcache.get(key) if a is None: a = [obj for obj in query.fetch(max+1, offset)] memcache.add(key, a, timeout) else: a = [obj for obj in query.fetch(max+1, offset)] # if p > 1: self.values['prev'] = p-1 l = len(a) if l > max: self.values['len'] = max self.values['next'] = p+1 return a[:max] self.values['len'] = l return a def pagination(self, value): ##Pagination if self.value('prev') or self.value('next'): params = [] p = self.value('p') q = self.value('q') a = self.value('a') t = self.value('t') o = self.value('o') cat = self.value('cat') pages = self.value('pages') # order if cat: params.append('cat=%s' % cat) # query string if q: params.append('q=%s' % q) # type if t: params.append('t=%s' % t) # order if o: params.append('o=%s' % o) # anchor if a: a = '#%s' % str(a) else: a = '' self.values['p'] = p self.values['common'] = '%s%s' % ('&amp;'.join(params), a) return '' def to_url_path(self, value): value = value.lower() # table = maketrans(u'áéíóúÁÉÍÓÚñÑ', u'aeiouAEIOUnN') # value = value.translate(table) value = value.replace(u'á', 'a') value = value.replace(u'é', 'e') value = value.replace(u'í', 'i') value = value.replace(u'ó', 'o') value = value.replace(u'ú', 'u') value = value.replace(u'Á', 'A') value = value.replace(u'É', 'E') value = value.replace(u'Í', 'I') value = value.replace(u'Ó', 'O') value = value.replace(u'Ú', 'U') value = value.replace(u'ñ', 'n') value = value.replace(u'Ñ', 'N') # TODO improve + review URL path allowed chars value = '-'.join(re.findall('[a-zA-Z0-9]+', value)) return value def clean_ascii(self, value): # table = maketrans(u'áéíóúÁÉÍÓÚñÑ', u'aeiouAEIOUnN') # value = value.translate(table) value = value.replace(u'á', 'a') value = value.replace(u'é', 'e') value = value.replace(u'í', 'i') value = value.replace(u'ó', 'o') value = value.replace(u'ú', 'u') value = value.replace(u'Á', 'A') value = value.replace(u'É', 'E') value = value.replace(u'Í', 'I') value = value.replace(u'Ó', 'O') value = value.replace(u'Ú', 'U') value = value.replace(u'ñ', 'n') value = value.replace(u'Ñ', 'N') # TODO improve + review URL path allowed chars value = ' '.join(re.findall('[a-zA-Z0-9()_\.:;-]+', value)) return value def unique_url_path(self, model, url_path): c = 1 url_path_base = url_path while True: query = db.Query(model) query.filter('url_path =', url_path) count = query.count(1) if count > 0: url_path = '%s-%d' % (url_path_base, c) c = c + 1 continue break return url_path
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.MainPage import * ### MODULES ### # Admin from handlers.module.admin.Admin import * from handlers.module.admin.AdminCategories import * from handlers.module.admin.AdminCategoryEdit import * from handlers.module.admin.AdminApplication import * from handlers.module.admin.AdminCommunityAddRelated import * from handlers.module.admin.AdminUsers import * from handlers.module.admin.AdminModules import * from handlers.module.admin.AdminLookAndFeel import * from handlers.module.admin.AdminGoogle import * from handlers.module.admin.AdminMail import * from handlers.module.admin.AdminCache import * from handlers.module.admin.AdminStats import * # Articles from handlers.module.article.ArticleList import * from handlers.module.article.ArticleEdit import * from handlers.module.article.ArticleView import * from handlers.module.article.ArticleTTS import * from handlers.module.article.ArticleVote import * from handlers.module.article.ArticleDelete import * from handlers.module.article.ArticleComment import * from handlers.module.article.ArticleFavourite import * from handlers.module.article.ArticleCommentSubscribe import * from handlers.module.article.ArticleCommentDelete import * from handlers.module.article.ArticleAddCommunities import * from handlers.module.article.ArticleCommentEdit import * from handlers.module.article.ArticleVisit import * # Communities from handlers.module.community.CommunityList import * from handlers.module.community.CommunityEdit import * from handlers.module.community.CommunityView import * from handlers.module.community.CommunityMove import * from handlers.module.community.CommunityDelete import * # community forums from handlers.module.community.CommunityForumList import * from handlers.module.community.CommunityForumEdit import * from handlers.module.community.CommunityForumView import * from handlers.module.community.CommunityForumReply import * from handlers.module.community.CommunityForumSubscribe import * from handlers.module.community.CommunityForumDelete import * from handlers.module.community.CommunityThreadEdit import * from handlers.module.community.CommunityForumMove import * from handlers.module.community.CommunityForumVisit import * # community articles from handlers.module.community.CommunityArticleList import * from handlers.module.community.CommunityNewArticle import * from handlers.module.community.CommunityArticleDelete import * # community users from handlers.module.community.CommunityUserList import * from handlers.module.community.CommunityUserUnjoin import * from handlers.module.community.CommunityUserJoin import * # Users from handlers.module.user.UserList import * from handlers.module.user.UserView import * from handlers.module.user.UserEdit import * from handlers.module.user.UserArticles import * from handlers.module.user.UserLogin import * from handlers.module.user.UserCommunities import * from handlers.module.user.UserLogout import * from handlers.module.user.UserRegister import * from handlers.module.user.UserChangePassword import * from handlers.module.user.UserForgotPassword import * from handlers.module.user.UserResetPassword import * from handlers.module.user.UserDrafts import * from handlers.module.user.UserContact import * from handlers.module.user.UserFavourites import * from handlers.module.user.UserContacts import * from handlers.module.user.UserPromote import * from handlers.module.user.UserEvents import * from handlers.module.user.UserForums import * # Blogging from handlers.module.mblog.MBlogEdit import * # Messages from handlers.module.message.MessageEdit import * from handlers.module.message.MessageSent import * from handlers.module.message.MessageInbox import * from handlers.module.message.MessageRead import * from handlers.module.message.MessageDelete import * ### Common handlers / Other Handlers ### # forums from handlers.ForumList import * #search from handlers.SearchResult import * # inviting contacts from handlers.Invite import * # feed RSS from handlers.Feed import * # images from handlers.ImageDisplayer import * from handlers.editor.ImageBrowser import * from handlers.editor.ImageUploader import * #Queue from handlers.MailQueue import * from handlers.TaskQueue import * from handlers.Tag import * from handlers.Search import * from handlers.Dispatcher import * from handlers.Initialization import * from handlers.NotFound import * from handlers.BaseRest import * from handlers.Static import *
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * class MainPage(BaseHandler): def execute(self): self.values['tab'] = '/' # memcache.delete('index_articles') # memcache.delete('index_communities') # memcache.delete('index_threads') self.values['articles'] = self.cache('index_articles', self.get_articles) # self.values['communities'] = self.cache('index_communities', self.get_communities) self.values['threads'] = self.cache('index_threads', self.get_threads) self.add_tag_cloud() # self.add_categories() self.render('templates/index.html') def get_articles(self): return model.Article.all().filter('draft', False).filter('deletion_date', None).order('-creation_date').fetch(5) # return self.render_chunk('templates/index-articles.html', {'articles': articles}) def get_communities(self): return model.Community.all().order('-members').fetch(5) # return self.render_chunk('templates/index-communities.html', {'communities': communities}) def get_threads(self): return model.Thread.all().filter('parent_thread', None).order('-last_response_date').fetch(5) # return self.render_chunk('templates/index-threads.html', {'threads': threads})
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com> # (C) Copyright 2008 Ignacio Andreu <plunchete at gmail dot com> # (C) Copyright 2008 Néstor Salceda <nestor.salceda at gmail dot com> # # This file is part of "debug_mode_on". # # "debug_mode_on" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "debug_mode_on" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>. # from handlers.BaseHandler import * class Search(BaseHandler): def execute(self): q = self.get_param('q') typ = self.get_param('t') if typ == 'articles': query = model.Article.all().filter('draft', False).filter('deletion_date', None).search(q) self.values['articles'] = self.paging(query, 10) self.add_tag_cloud() elif typ == 'forums': query = model.Thread.all().search(q) threads = self.paging(query, 10) # migration for t in threads: if not t.url_path: t.url_path = t.parent_thread.url_path t.put() # end migration self.values['threads'] = threads else: query = model.Community.all().search(q) self.values['communities'] = self.paging(query, 10) self.values['q'] = q self.values['t'] = typ self.render('templates/search.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Copyright 2008 Juan Luis Belmonte <jlbelmonte at gmail dot com> # # This file is part of "debug_mode_on". # # "debug_mode_on" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "debug_mode_on" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>. # import re #main method to apply all filters def media_content(value): if re.search('youtube',value): value=youtube(value) if re.search('vimeo', value): value=vimeo(value) # if re.search('slideshare', value): # value=slideshare(value) if re.search('veoh', value): value=veoh(value) if re.search('metacafe', value): value=metacafe(value) if re.search('video\.yahoo', value): value=yahoovideo(value) # if re.search('show\.zoho', value): # value=sohoshow(value) # if re.search('teachertube', value): # value=teachertube(value) return value # specific methods for the different services def youtube(text): targets = re.findall('media=http://\S+.youtube.com/watch\?v=\S+;', text) for i in targets: match= re.match('(.*)watch\?v=(\S+);',i) html = '<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s"&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s"=es&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>' % ( match.community(2), match.community(2)) text=text.replace(i,html) return text def vimeo(text): targets = re.findall('media=\S*vimeo.com/\S+;',text) for i in targets: match = re.match('(\S*)vimeo.com/(\S+)',i) html='<p><object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=%s&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=%s&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object></p>' % ( match.community(2), match.community(2)) text=text.replace(i,html) return text def slideshare(text): targets = re.findall('(media=\[.*\];)', text) for i in targets: match = re.search('id=(.*)&doc=(.*)&w=(.*)',i) html = '<p><div style="width:425px;text-align:left" id="__ss_%s"><object style="margin:0px" width="%s" height="355"><param name="movie" value="http://static.slideshare.net/swf/ssplayer2.swf?doc=%s"/><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slideshare.net/swf/ssplayer2.swf?doc=%s" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="%s" height="355"/></object></div></p>' %(match.community(1),match.community(3),match.community(2),match.community(2),match.community(3)) text=text.replace(i,html) return text def metacafe(text): targets = re.findall('media=\S+/watch/\d+/\S+/;', text) for i in targets: match = re.search('http://www.metacafe.com/watch/(\d+)/(\S+)/', i) html = '<p><embed src="http://www.metacafe.com/fplayer/%s/%s.swf" width="400" height="345" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"> </embed></p>' %(match.community(1), match.community(2)) text=text.replace(i,html) return text def veoh(text): targets = re.findall('media=\S+veoh.com/videos/\S+;', text) for i in targets: match = re.search('http://www.veoh.com/videos/(\S+);',i) html = '<p><embed src="http://www.veoh.com/veohplayer.swf?permalinkId=%s&id=anonymous&player=videodetailsembedded&videoAutoPlay=0" allowFullScreen="true" width="410" height="341" bgcolor="#FFFFFF" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></p>' % match.community(1) text = text.replace(i, html) return text def yahoovideo(text): targets = re.findall('media=\S+video.yahoo.com/\S+/\d+\S+\d+;', text) for i in targets: match = re.search('video.yahoo.com/\S+/(\d+)/(\d+);', i) html='<p><div><object width="512" height="322"><param name="movie" value="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.30" /><param name="allowFullScreen" value="true" /><param name="AllowScriptAccess" VALUE="always" /><param name="bgcolor" value="#000000" /><param name="flashVars" value="id=%s&vid=%s&lang=en-us&intl=us&embed=1" /><embed src="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.30" type="application/x-shockwave-flash" width="512" height="322" allowFullScreen="true" AllowScriptAccess="always" bgcolor="#000000" flashVars="id=%s&vid=%s&lang=en-us&intl=us&embed=1" ></embed></object></div></p>' % (match.community(2),match.community(1),match.community(2),match.community(2)) text = text.replace(i, html) return text def teachertube(text): targets = re.findall('media=\S+/view_video.php\?viewkey=\S+;', text) for i in targets: match = re.search('viewkey=(\S+)',i) url_atom='%3' html='<embed src="http://www.teachertube.com/skin-p/mediaplayer.swf" width="425" height="350" type="application/x-shockwave-flash" allowfullscreen="true" menu="false" flashvars="height=350&width=425&file=http://www.teachertube.com/flvideo/64252.flv&location=http://www.teachertube.com/skin-p/mediaplayer.swf&logo=http://www.teachertube.com/images/greylogo.swf&searchlink=http://teachertube.com/search_result.php%sFsearch_id%sD&frontcolor=0xffffff&backcolor=0x000000&lightcolor=0xFF0000&screencolor=0xffffff&autostart=false&volume=80&overstretch=fit&link=http://www.teachertube.com/view_video.php?viewkey=%s&linkfromdisplay=true></embed>' % (url_atom, url_atom, match.community(1)) text = text.replace(i, text) return text def sohoshow(text): targets = re.findall('media=\S+show.zoho.com/public/\S+;', text) for i in targets: match = re.search('show.zoho.com/public/(\S+)/(\S+);',i) html='<p><embed height="335" width="450" name="Welcome3" style="border:1px solid #AABBCC" scrolling="no" src="http://show.zoho.com/embed?USER=%s&DOC=%s&IFRAME=yes" frameBorder="0"></embed></p>' % (match.community(1), match.community(2)) text = text.replace(i, text) return text def dummy(text): return text ### skeleton #def teacherstube(text): # targets = re.findall('', text) # for i in targets: # match = re.search('',text) # html= # text = text.replace(i, text) # return text
Python
"""Beautiful Soup Elixir and Tonic "The Screen-Scraper's Friend" http://www.crummy.com/software/BeautifulSoup/ Beautiful Soup parses a (possibly invalid) XML or HTML document into a tree representation. It provides methods and Pythonic idioms that make it easy to navigate, search, and modify the tree. A well-formed XML/HTML document yields a well-formed data structure. An ill-formed XML/HTML document yields a correspondingly ill-formed data structure. If your document is only locally well-formed, you can use this library to find and process the well-formed part of it. Beautiful Soup works with Python 2.2 and up. It has no external dependencies, but you'll have more success at converting data to UTF-8 if you also install these three packages: * chardet, for auto-detecting character encodings http://chardet.feedparser.org/ * cjkcodecs and iconv_codec, which add more encodings to the ones supported by stock Python. http://cjkpython.i18n.org/ Beautiful Soup defines classes for two main parsing strategies: * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific language that kind of looks like XML. * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid or invalid. This class has web browser-like heuristics for obtaining a sensible parse tree in the face of common HTML errors. Beautiful Soup also defines a class (UnicodeDammit) for autodetecting the encoding of an HTML or XML document, and converting it to Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser. For more than you ever wanted to know about Beautiful Soup, see the documentation: http://www.crummy.com/software/BeautifulSoup/documentation.html Here, have some legalese: Copyright (c) 2004-2010, Leonard Richardson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the the Beautiful Soup Consortium and All Night Kosher Bakery nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT. """ from __future__ import generators __author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.2.0" __copyright__ = "Copyright (c) 2004-2010 Leonard Richardson" __license__ = "New-style BSD" from sgmllib import SGMLParser, SGMLParseError import codecs import markupbase import types import re import sgmllib try: from htmlentitydefs import name2codepoint except ImportError: name2codepoint = {} try: set except NameError: from sets import Set as set #These hacks make Beautiful Soup able to parse XML with namespaces sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*') markupbase._declname_match = re.compile(r'[a-zA-Z][-_.:a-zA-Z0-9]*\s*').match DEFAULT_OUTPUT_ENCODING = "utf-8" def _match_css_class(str): """Build a RE to match the given CSS class.""" return re.compile(r"(^|.*\s)%s($|\s)" % str) # First, the classes that represent markup elements. class PageElement(object): """Contains the navigational information for some part of the page (either a tag or a piece of text)""" def setup(self, parent=None, previous=None): """Sets up the initial relations between this element and other elements.""" self.parent = parent self.previous = previous self.next = None self.previousSibling = None self.nextSibling = None if self.parent and self.parent.contents: self.previousSibling = self.parent.contents[-1] self.previousSibling.nextSibling = self def replaceWith(self, replaceWith): oldParent = self.parent myIndex = self.parent.index(self) if hasattr(replaceWith, "parent")\ and replaceWith.parent is self.parent: # We're replacing this element with one of its siblings. index = replaceWith.parent.index(replaceWith) if index and index < myIndex: # Furthermore, it comes before this element. That # means that when we extract it, the index of this # element will change. myIndex = myIndex - 1 self.extract() oldParent.insert(myIndex, replaceWith) def replaceWithChildren(self): myParent = self.parent myIndex = self.parent.index(self) self.extract() reversedChildren = list(self.contents) reversedChildren.reverse() for child in reversedChildren: myParent.insert(myIndex, child) def extract(self): """Destructively rips this element out of the tree.""" if self.parent: try: del self.parent.contents[self.parent.index(self)] except ValueError: pass #Find the two elements that would be next to each other if #this element (and any children) hadn't been parsed. Connect #the two. lastChild = self._lastRecursiveChild() nextElement = lastChild.next if self.previous: self.previous.next = nextElement if nextElement: nextElement.previous = self.previous self.previous = None lastChild.next = None self.parent = None if self.previousSibling: self.previousSibling.nextSibling = self.nextSibling if self.nextSibling: self.nextSibling.previousSibling = self.previousSibling self.previousSibling = self.nextSibling = None return self def _lastRecursiveChild(self): "Finds the last element beneath this object to be parsed." lastChild = self while hasattr(lastChild, 'contents') and lastChild.contents: lastChild = lastChild.contents[-1] return lastChild def insert(self, position, newChild): if isinstance(newChild, basestring) \ and not isinstance(newChild, NavigableString): newChild = NavigableString(newChild) position = min(position, len(self.contents)) if hasattr(newChild, 'parent') and newChild.parent is not None: # We're 'inserting' an element that's already one # of this object's children. if newChild.parent is self: index = self.index(newChild) if index > position: # Furthermore we're moving it further down the # list of this object's children. That means that # when we extract this element, our target index # will jump down one. position = position - 1 newChild.extract() newChild.parent = self previousChild = None if position == 0: newChild.previousSibling = None newChild.previous = self else: previousChild = self.contents[position-1] newChild.previousSibling = previousChild newChild.previousSibling.nextSibling = newChild newChild.previous = previousChild._lastRecursiveChild() if newChild.previous: newChild.previous.next = newChild newChildsLastElement = newChild._lastRecursiveChild() if position >= len(self.contents): newChild.nextSibling = None parent = self parentsNextSibling = None while not parentsNextSibling: parentsNextSibling = parent.nextSibling parent = parent.parent if not parent: # This is the last element in the document. break if parentsNextSibling: newChildsLastElement.next = parentsNextSibling else: newChildsLastElement.next = None else: nextChild = self.contents[position] newChild.nextSibling = nextChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild newChildsLastElement.next = nextChild if newChildsLastElement.next: newChildsLastElement.next.previous = newChildsLastElement self.contents.insert(position, newChild) def append(self, tag): """Appends the given tag to the contents of this tag.""" self.insert(len(self.contents), tag) def findNext(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findAllNext, name, attrs, text, **kwargs) def findAllNext(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextGenerator, **kwargs) def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findNextSiblings, name, attrs, text, **kwargs) def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextSiblingGenerator, **kwargs) fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x def findPrevious(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs) def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousGenerator, **kwargs) fetchPrevious = findAllPrevious # Compatibility with pre-3.x def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findPreviousSiblings, name, attrs, text, **kwargs) def findPreviousSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousSiblingGenerator, **kwargs) fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x def findParent(self, name=None, attrs={}, **kwargs): """Returns the closest parent of this Tag that matches the given criteria.""" # NOTE: We can't use _findOne because findParents takes a different # set of arguments. r = None l = self.findParents(name, attrs, 1) if l: r = l[0] return r def findParents(self, name=None, attrs={}, limit=None, **kwargs): """Returns the parents of this Tag that match the given criteria.""" return self._findAll(name, attrs, None, limit, self.parentGenerator, **kwargs) fetchParents = findParents # Compatibility with pre-3.x #These methods do the real heavy lifting. def _findOne(self, method, name, attrs, text, **kwargs): r = None l = method(name, attrs, text, 1, **kwargs) if l: r = l[0] return r def _findAll(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name # (Possibly) special case some findAll*(...) searches elif text is None and not limit and not attrs and not kwargs: # findAll*(True) if name is True: return [element for element in generator() if isinstance(element, Tag)] # findAll*('tag-name') elif isinstance(name, basestring): return [element for element in generator() if isinstance(element, Tag) and element.name == name] else: strainer = SoupStrainer(name, attrs, text, **kwargs) # Build a SoupStrainer else: strainer = SoupStrainer(name, attrs, text, **kwargs) results = ResultSet(strainer) g = generator() while True: try: i = g.next() except StopIteration: break if i: found = strainer.search(i) if found: results.append(found) if limit and len(results) >= limit: break return results #These Generators can be used to navigate starting from both #NavigableStrings and Tags. def nextGenerator(self): i = self while i is not None: i = i.next yield i def nextSiblingGenerator(self): i = self while i is not None: i = i.nextSibling yield i def previousGenerator(self): i = self while i is not None: i = i.previous yield i def previousSiblingGenerator(self): i = self while i is not None: i = i.previousSibling yield i def parentGenerator(self): i = self while i is not None: i = i.parent yield i # Utility methods def substituteEncoding(self, str, encoding=None): encoding = encoding or "utf-8" return str.replace("%SOUP-ENCODING%", encoding) def toEncoding(self, s, encoding=None): """Encodes an object to a string in some encoding, or to Unicode. .""" if isinstance(s, unicode): if encoding: s = s.encode(encoding) elif isinstance(s, str): if encoding: s = s.encode(encoding) else: s = unicode(s) else: if encoding: s = self.toEncoding(str(s), encoding) else: s = unicode(s) return s class NavigableString(unicode, PageElement): def __new__(cls, value): """Create a new NavigableString. When unpickling a NavigableString, this method is called with the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be passed in to the superclass's __new__ or the superclass won't know how to handle non-ASCII characters. """ if isinstance(value, unicode): return unicode.__new__(cls, value) return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING) def __getnewargs__(self): return (NavigableString.__str__(self),) def __getattr__(self, attr): """text.string gives you text. This is for backwards compatibility for Navigable*String, but for CData* it lets you get the string without the CData wrapper.""" if attr == 'string': return self else: raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr) def __unicode__(self): return str(self).decode(DEFAULT_OUTPUT_ENCODING) def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): if encoding: return self.encode(encoding) else: return self class CData(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): return "<![CDATA[%s]]>" % NavigableString.__str__(self, encoding) class ProcessingInstruction(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): output = self if "%SOUP-ENCODING%" in output: output = self.substituteEncoding(output, encoding) return "<?%s?>" % self.toEncoding(output, encoding) class Comment(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): return "<!--%s-->" % NavigableString.__str__(self, encoding) class Declaration(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): return "<!%s>" % NavigableString.__str__(self, encoding) class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" def _invert(h): "Cheap function to invert a hash." i = {} for k,v in h.items(): i[v] = k return i XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'", "quot" : '"', "amp" : "&", "lt" : "<", "gt" : ">" } XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS) def _convertEntities(self, match): """Used in a call to re.sub to replace HTML, XML, and numeric entities with the appropriate Unicode characters. If HTML entities are being converted, any unrecognized entities are escaped.""" x = match.group(1) if self.convertHTMLEntities and x in name2codepoint: return unichr(name2codepoint[x]) elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS: if self.convertXMLEntities: return self.XML_ENTITIES_TO_SPECIAL_CHARS[x] else: return u'&%s;' % x elif len(x) > 0 and x[0] == '#': # Handle numeric entities if len(x) > 1 and x[1] == 'x': return unichr(int(x[2:], 16)) else: return unichr(int(x[1:])) elif self.escapeUnrecognizedEntities: return u'&amp;%s;' % x else: return u'&%s;' % x def __init__(self, parser, name, attrs=None, parent=None, previous=None): "Basic constructor." # We don't actually store the parser object: that lets extracted # chunks be garbage-collected self.parserClass = parser.__class__ self.isSelfClosing = parser.isSelfClosingTag(name) self.name = name if attrs is None: attrs = [] elif isinstance(attrs, dict): attrs = attrs.items() self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = False self.containsSubstitutions = False self.convertHTMLEntities = parser.convertHTMLEntities self.convertXMLEntities = parser.convertXMLEntities self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities # Convert any HTML, XML, or numeric entities in the attribute values. convert = lambda(k, val): (k, re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);", self._convertEntities, val)) self.attrs = map(convert, self.attrs) def getString(self): if (len(self.contents) == 1 and isinstance(self.contents[0], NavigableString)): return self.contents[0] def setString(self, string): """Replace the contents of the tag with a string""" self.clear() self.append(string) string = property(getString, setString) def getText(self, separator=u""): if not len(self.contents): return u"" stopNode = self._lastRecursiveChild().next strings = [] current = self.contents[0] while current is not stopNode: if isinstance(current, NavigableString): strings.append(current.strip()) current = current.next return separator.join(strings) text = property(getText) def get(self, key, default=None): """Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.""" return self._getAttrMap().get(key, default) def clear(self): """Extract all children.""" for child in self.contents[:]: child.extract() def index(self, element): for i, child in enumerate(self.contents): if child is element: return i raise ValueError("Tag.index: element not in tag") def has_key(self, key): return self._getAttrMap().has_key(key) def __getitem__(self, key): """tag[key] returns the value of the 'key' attribute for the tag, and throws an exception if it's not there.""" return self._getAttrMap()[key] def __iter__(self): "Iterating over a tag iterates over its contents." return iter(self.contents) def __len__(self): "The length of a tag is the length of its list of contents." return len(self.contents) def __contains__(self, x): return x in self.contents def __nonzero__(self): "A tag is non-None even if it has no contents." return True def __setitem__(self, key, value): """Setting tag[key] sets the value of the 'key' attribute for the tag.""" self._getAttrMap() self.attrMap[key] = value found = False for i in range(0, len(self.attrs)): if self.attrs[i][0] == key: self.attrs[i] = (key, value) found = True if not found: self.attrs.append((key, value)) self._getAttrMap()[key] = value def __delitem__(self, key): "Deleting tag[key] deletes all 'key' attributes for the tag." for item in self.attrs: if item[0] == key: self.attrs.remove(item) #We don't break because bad HTML can define the same #attribute multiple times. self._getAttrMap() if self.attrMap.has_key(key): del self.attrMap[key] def __call__(self, *args, **kwargs): """Calling a tag like a function is the same as calling its findAll() method. Eg. tag('a') returns a list of all the A tags found within this tag.""" return apply(self.findAll, args, kwargs) def __getattr__(self, tag): #print "Getattr %s.%s" % (self.__class__, tag) if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3: return self.find(tag[:-3]) elif tag.find('__') != 0: return self.find(tag) raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag) def __eq__(self, other): """Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag. NOTE: right now this will return false if two tags have the same attributes in a different order. Should this be fixed?""" if other is self: return True if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other): return False for i in range(0, len(self.contents)): if self.contents[i] != other.contents[i]: return False return True def __ne__(self, other): """Returns true iff this tag is not identical to the other tag, as defined in __eq__.""" return not self == other def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): """Renders this tag as a string.""" return self.__str__(encoding) def __unicode__(self): return self.__str__(None) BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|" + "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)" + ")") def _sub_entity(self, x): """Used with a regular expression to substitute the appropriate XML entity for an XML special character.""" return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";" def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): """Returns a string or Unicode representation of this tag and its contents. To get Unicode, pass None for encoding. NOTE: since Python's HTML parser consumes whitespace, this method is not certain to reproduce the whitespace present in the original string.""" encodedName = self.toEncoding(self.name, encoding) attrs = [] if self.attrs: for key, val in self.attrs: fmt = '%s="%s"' if isinstance(val, basestring): if self.containsSubstitutions and '%SOUP-ENCODING%' in val: val = self.substituteEncoding(val, encoding) # The attribute value either: # # * Contains no embedded double quotes or single quotes. # No problem: we enclose it in double quotes. # * Contains embedded single quotes. No problem: # double quotes work here too. # * Contains embedded double quotes. No problem: # we enclose it in single quotes. # * Embeds both single _and_ double quotes. This # can't happen naturally, but it can happen if # you modify an attribute value after parsing # the document. Now we have a bit of a # problem. We solve it by enclosing the # attribute in single quotes, and escaping any # embedded single quotes to XML entities. if '"' in val: fmt = "%s='%s'" if "'" in val: # TODO: replace with apos when # appropriate. val = val.replace("'", "&squot;") # Now we're okay w/r/t quotes. But the attribute # value might also contain angle brackets, or # ampersands that aren't part of entities. We need # to escape those to XML entities too. val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val) attrs.append(fmt % (self.toEncoding(key, encoding), self.toEncoding(val, encoding))) close = '' closeTag = '' if self.isSelfClosing: close = ' /' else: closeTag = '</%s>' % encodedName indentTag, indentContents = 0, 0 if prettyPrint: indentTag = indentLevel space = (' ' * (indentTag-1)) indentContents = indentTag + 1 contents = self.renderContents(encoding, prettyPrint, indentContents) if self.hidden: s = contents else: s = [] attributeString = '' if attrs: attributeString = ' ' + ' '.join(attrs) if prettyPrint: s.append(space) s.append('<%s%s%s>' % (encodedName, attributeString, close)) if prettyPrint: s.append("\n") s.append(contents) if prettyPrint and contents and contents[-1] != "\n": s.append("\n") if prettyPrint and closeTag: s.append(space) s.append(closeTag) if prettyPrint and closeTag and self.nextSibling: s.append("\n") s = ''.join(s) return s def decompose(self): """Recursively destroys the contents of this tree.""" self.extract() if len(self.contents) == 0: return current = self.contents[0] while current is not None: next = current.next if isinstance(current, Tag): del current.contents[:] current.parent = None current.previous = None current.previousSibling = None current.next = None current.nextSibling = None current = next def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING): return self.__str__(encoding, True) def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): """Renders the contents of this tag as a string in the given encoding. If encoding is None, returns a Unicode string..""" s=[] for c in self: text = None if isinstance(c, NavigableString): text = c.__str__(encoding) elif isinstance(c, Tag): s.append(c.__str__(encoding, prettyPrint, indentLevel)) if text and prettyPrint: text = text.strip() if text: if prettyPrint: s.append(" " * (indentLevel-1)) s.append(text) if prettyPrint: s.append("\n") return ''.join(s) #Soup methods def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): """Return only the first child of this Tag matching the given criteria.""" r = None l = self.findAll(name, attrs, recursive, text, 1, **kwargs) if l: r = l[0] return r findChild = find def findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): """Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the 'attrs' map can be a string, a list of strings, a regular expression object, or a callable that takes a string and returns whether or not the string matches for some custom definition of 'matches'. The same is true of the tag name.""" generator = self.recursiveChildGenerator if not recursive: generator = self.childGenerator return self._findAll(name, attrs, text, limit, generator, **kwargs) findChildren = findAll # Pre-3.x compatibility methods first = find fetch = findAll def fetchText(self, text=None, recursive=True, limit=None): return self.findAll(text=text, recursive=recursive, limit=limit) def firstText(self, text=None, recursive=True): return self.find(text=text, recursive=recursive) #Private methods def _getAttrMap(self): """Initializes a map representation of this tag's attributes, if not already initialized.""" if not getattr(self, 'attrMap'): self.attrMap = {} for (key, value) in self.attrs: self.attrMap[key] = value return self.attrMap #Generator methods def childGenerator(self): # Just use the iterator from the contents return iter(self.contents) def recursiveChildGenerator(self): if not len(self.contents): raise StopIteration stopNode = self._lastRecursiveChild().next current = self.contents[0] while current is not stopNode: yield current current = current.next # Next, a couple classes to represent queries and their results. class SoupStrainer: """Encapsulates a number of ways of matching a markup element (tag or text).""" def __init__(self, name=None, attrs={}, text=None, **kwargs): self.name = name if isinstance(attrs, basestring): kwargs['class'] = _match_css_class(attrs) attrs = None if kwargs: if attrs: attrs = attrs.copy() attrs.update(kwargs) else: attrs = kwargs self.attrs = attrs self.text = text def __str__(self): if self.text: return self.text else: return "%s|%s" % (self.name, self.attrs) def searchTag(self, markupName=None, markupAttrs={}): found = None markup = None if isinstance(markupName, Tag): markup = markupName markupAttrs = markup callFunctionWithTagData = callable(self.name) \ and not isinstance(markupName, Tag) if (not self.name) \ or callFunctionWithTagData \ or (markup and self._matches(markup, self.name)) \ or (not markup and self._matches(markupName, self.name)): if callFunctionWithTagData: match = self.name(markupName, markupAttrs) else: match = True markupAttrMap = None for attr, matchAgainst in self.attrs.items(): if not markupAttrMap: if hasattr(markupAttrs, 'get'): markupAttrMap = markupAttrs else: markupAttrMap = {} for k,v in markupAttrs: markupAttrMap[k] = v attrValue = markupAttrMap.get(attr) if not self._matches(attrValue, matchAgainst): match = False break if match: if markup: found = markup else: found = markupName return found def search(self, markup): #print 'looking for %s in %s' % (self, markup) found = None # If given a list of items, scan it for a text element that # matches. if hasattr(markup, "__iter__") \ and not isinstance(markup, Tag): for element in markup: if isinstance(element, NavigableString) \ and self.search(element): found = element break # If it's a Tag, make sure its name or attributes match. # Don't bother with Tags if we're searching for text. elif isinstance(markup, Tag): if not self.text: found = self.searchTag(markup) # If it's text, make sure the text matches. elif isinstance(markup, NavigableString) or \ isinstance(markup, basestring): if self._matches(markup, self.text): found = markup else: raise Exception, "I don't know how to match against a %s" \ % markup.__class__ return found def _matches(self, markup, matchAgainst): #print "Matching %s against %s" % (markup, matchAgainst) result = False if matchAgainst is True: result = markup is not None elif callable(matchAgainst): result = matchAgainst(markup) else: #Custom match methods take the tag as an argument, but all #other ways of matching match the tag name as a string. if isinstance(markup, Tag): markup = markup.name if markup and not isinstance(markup, basestring): markup = unicode(markup) #Now we know that chunk is either a string, or None. if hasattr(matchAgainst, 'match'): # It's a regexp object. result = markup and matchAgainst.search(markup) elif hasattr(matchAgainst, '__iter__'): # list-like result = markup in matchAgainst elif hasattr(matchAgainst, 'items'): result = markup.has_key(matchAgainst) elif matchAgainst and isinstance(markup, basestring): if isinstance(markup, unicode): matchAgainst = unicode(matchAgainst) else: matchAgainst = str(matchAgainst) if not result: result = matchAgainst == markup return result class ResultSet(list): """A ResultSet is just a list that keeps track of the SoupStrainer that created it.""" def __init__(self, source): list.__init__([]) self.source = source # Now, some helper functions. def buildTagMap(default, *args): """Turns a list of maps, lists, or scalars into a single map. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and NESTING_RESET_TAGS maps out of lists and partial maps.""" built = {} for portion in args: if hasattr(portion, 'items'): #It's a map. Merge it. for k,v in portion.items(): built[k] = v elif hasattr(portion, '__iter__'): # is a list #It's a list. Map each item to the default. for k in portion: built[k] = default else: #It's a scalar. Map it to the default. built[portion] = default return built # Now, the parser classes. class BeautifulStoneSoup(Tag, SGMLParser): """This class contains the basic parser and search code. It defines a parser that knows nothing about tag behavior except for the following: You can't close a tag without closing all the tags it encloses. That is, "<foo><bar></foo>" actually means "<foo><bar></bar></foo>". [Another possible explanation is "<foo><bar /></foo>", but since this class defines no SELF_CLOSING_TAGS, it will never use that explanation.] This class is useful for parsing XML or made-up markup languages, or when BeautifulSoup makes an assumption counter to what you were expecting.""" SELF_CLOSING_TAGS = {} NESTABLE_TAGS = {} RESET_NESTING_TAGS = {} QUOTE_TAGS = {} PRESERVE_WHITESPACE_TAGS = [] MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'), lambda x: x.group(1) + ' />'), (re.compile('<!\s+([^<>]*)>'), lambda x: '<!' + x.group(1) + '>') ] ROOT_TAG_NAME = u'[document]' HTML_ENTITIES = "html" XML_ENTITIES = "xml" XHTML_ENTITIES = "xhtml" # TODO: This only exists for backwards-compatibility ALL_ENTITIES = XHTML_ENTITIES # Used when determining whether a text node is all whitespace and # can be replaced with a single space. A text node that contains # fancy Unicode spaces (usually non-breaking) should be left # alone. STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, } def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo=XML_ENTITIES, convertEntities=None, selfClosingTags=None, isHTML=False): """The Soup object is initialized as the 'root tag', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser. sgmllib will process most bad HTML, and the BeautifulSoup class has some tricks for dealing with some HTML that kills sgmllib, but Beautiful Soup can nonetheless choke or lose data if your data uses self-closing tags or declarations incorrectly. By default, Beautiful Soup uses regexes to sanitize input, avoiding the vast majority of these problems. If the problems don't apply to you, pass in False for markupMassage, and you'll get better performance. The default parser massage techniques fix the two most common instances of invalid HTML that choke sgmllib: <br/> (No space between name of closing tag and tag close) <! --Comment--> (Extraneous whitespace in declaration) You can pass in a custom list of (RE object, replace method) tuples to get Beautiful Soup to scrub your input the way you want.""" self.parseOnlyThese = parseOnlyThese self.fromEncoding = fromEncoding self.smartQuotesTo = smartQuotesTo self.convertEntities = convertEntities # Set the rules for how we'll deal with the entities we # encounter if self.convertEntities: # It doesn't make sense to convert encoded characters to # entities even while you're converting entities to Unicode. # Just convert it all to Unicode. self.smartQuotesTo = None if convertEntities == self.HTML_ENTITIES: self.convertXMLEntities = False self.convertHTMLEntities = True self.escapeUnrecognizedEntities = True elif convertEntities == self.XHTML_ENTITIES: self.convertXMLEntities = True self.convertHTMLEntities = True self.escapeUnrecognizedEntities = False elif convertEntities == self.XML_ENTITIES: self.convertXMLEntities = True self.convertHTMLEntities = False self.escapeUnrecognizedEntities = False else: self.convertXMLEntities = False self.convertHTMLEntities = False self.escapeUnrecognizedEntities = False self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags) SGMLParser.__init__(self) if hasattr(markup, 'read'): # It's a file-type object. markup = markup.read() self.markup = markup self.markupMassage = markupMassage try: self._feed(isHTML=isHTML) except StopParsing: pass self.markup = None # The markup can now be GCed def convert_charref(self, name): """This method fixes a bug in Python's SGMLParser.""" try: n = int(name) except ValueError: return if not 0 <= n <= 127 : # ASCII ends at 127, not 255 return return self.convert_codepoint(n) def _feed(self, inDocumentEncoding=None, isHTML=False): # Convert the document to Unicode. markup = self.markup if isinstance(markup, unicode): if not hasattr(self, 'originalEncoding'): self.originalEncoding = None else: dammit = UnicodeDammit\ (markup, [self.fromEncoding, inDocumentEncoding], smartQuotesTo=self.smartQuotesTo, isHTML=isHTML) markup = dammit.unicode self.originalEncoding = dammit.originalEncoding self.declaredHTMLEncoding = dammit.declaredHTMLEncoding if markup: if self.markupMassage: if not hasattr(self.markupMassage, "__iter__"): self.markupMassage = self.MARKUP_MASSAGE for fix, m in self.markupMassage: markup = fix.sub(m, markup) # TODO: We get rid of markupMassage so that the # soup object can be deepcopied later on. Some # Python installations can't copy regexes. If anyone # was relying on the existence of markupMassage, this # might cause problems. del(self.markupMassage) self.reset() SGMLParser.feed(self, markup) # Close out any unfinished strings and close all the open tags. self.endData() while self.currentTag.name != self.ROOT_TAG_NAME: self.popTag() def __getattr__(self, methodName): """This method routes method call requests to either the SGMLParser superclass or the Tag superclass, depending on the method name.""" #print "__getattr__ called on %s.%s" % (self.__class__, methodName) if methodName.startswith('start_') or methodName.startswith('end_') \ or methodName.startswith('do_'): return SGMLParser.__getattr__(self, methodName) elif not methodName.startswith('__'): return Tag.__getattr__(self, methodName) else: raise AttributeError def isSelfClosingTag(self, name): """Returns true iff the given string is the name of a self-closing tag according to this parser.""" return self.SELF_CLOSING_TAGS.has_key(name) \ or self.instanceSelfClosingTags.has_key(name) def reset(self): Tag.__init__(self, self, self.ROOT_TAG_NAME) self.hidden = 1 SGMLParser.reset(self) self.currentData = [] self.currentTag = None self.tagStack = [] self.quoteStack = [] self.pushTag(self) def popTag(self): tag = self.tagStack.pop() #print "Pop", tag.name if self.tagStack: self.currentTag = self.tagStack[-1] return self.currentTag def pushTag(self, tag): #print "Push", tag.name if self.currentTag: self.currentTag.contents.append(tag) self.tagStack.append(tag) self.currentTag = self.tagStack[-1] def endData(self, containerClass=NavigableString): if self.currentData: currentData = u''.join(self.currentData) if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and not set([tag.name for tag in self.tagStack]).intersection( self.PRESERVE_WHITESPACE_TAGS)): if '\n' in currentData: currentData = '\n' else: currentData = ' ' self.currentData = [] if self.parseOnlyThese and len(self.tagStack) <= 1 and \ (not self.parseOnlyThese.text or \ not self.parseOnlyThese.search(currentData)): return o = containerClass(currentData) o.setup(self.currentTag, self.previous) if self.previous: self.previous.next = o self.previous = o self.currentTag.contents.append(o) def _popToTag(self, name, inclusivePop=True): """Pops the tag stack up to and including the most recent instance of the given tag. If inclusivePop is false, pops the tag stack up to but *not* including the most recent instqance of the given tag.""" #print "Popping to %s" % name if name == self.ROOT_TAG_NAME: return numPops = 0 mostRecentTag = None for i in range(len(self.tagStack)-1, 0, -1): if name == self.tagStack[i].name: numPops = len(self.tagStack)-i break if not inclusivePop: numPops = numPops - 1 for i in range(0, numPops): mostRecentTag = self.popTag() return mostRecentTag def _smartPop(self, name): """We need to pop up to the previous tag of this type, unless one of this tag's nesting reset triggers comes between this tag and the previous tag of this type, OR unless this tag is a generic nesting trigger and another generic nesting trigger comes between this tag and the previous tag of this type. Examples: <p>Foo<b>Bar *<p>* should pop to 'p', not 'b'. <p>Foo<table>Bar *<p>* should pop to 'table', not 'p'. <p>Foo<table><tr>Bar *<p>* should pop to 'tr', not 'p'. <li><ul><li> *<li>* should pop to 'ul', not the first 'li'. <tr><table><tr> *<tr>* should pop to 'table', not the first 'tr' <td><tr><td> *<td>* should pop to 'tr', not the first 'td' """ nestingResetTriggers = self.NESTABLE_TAGS.get(name) isNestable = nestingResetTriggers != None isResetNesting = self.RESET_NESTING_TAGS.has_key(name) popTo = None inclusive = True for i in range(len(self.tagStack)-1, 0, -1): p = self.tagStack[i] if (not p or p.name == name) and not isNestable: #Non-nestable tags get popped to the top or to their #last occurance. popTo = name break if (nestingResetTriggers is not None and p.name in nestingResetTriggers) \ or (nestingResetTriggers is None and isResetNesting and self.RESET_NESTING_TAGS.has_key(p.name)): #If we encounter one of the nesting reset triggers #peculiar to this tag, or we encounter another tag #that causes nesting to reset, pop up to but not #including that tag. popTo = p.name inclusive = False break p = p.parent if popTo: self._popToTag(popTo, inclusive) def unknown_starttag(self, name, attrs, selfClosing=0): #print "Start tag %s: %s" % (name, attrs) if self.quoteStack: #This is not a real tag. #print "<%s> is not real!" % name attrs = ''.join([' %s="%s"' % (x, y) for x, y in attrs]) self.handle_data('<%s%s>' % (name, attrs)) return self.endData() if not self.isSelfClosingTag(name) and not selfClosing: self._smartPop(name) if self.parseOnlyThese and len(self.tagStack) <= 1 \ and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)): return tag = Tag(self, name, attrs, self.currentTag, self.previous) if self.previous: self.previous.next = tag self.previous = tag self.pushTag(tag) if selfClosing or self.isSelfClosingTag(name): self.popTag() if name in self.QUOTE_TAGS: #print "Beginning quote (%s)" % name self.quoteStack.append(name) self.literal = 1 return tag def unknown_endtag(self, name): #print "End tag %s" % name if self.quoteStack and self.quoteStack[-1] != name: #This is not a real end tag. #print "</%s> is not real!" % name self.handle_data('</%s>' % name) return self.endData() self._popToTag(name) if self.quoteStack and self.quoteStack[-1] == name: self.quoteStack.pop() self.literal = (len(self.quoteStack) > 0) def handle_data(self, data): self.currentData.append(data) def _toStringSubclass(self, text, subclass): """Adds a certain piece of text to the tree as a NavigableString subclass.""" self.endData() self.handle_data(text) self.endData(subclass) def handle_pi(self, text): """Handle a processing instruction as a ProcessingInstruction object, possibly one with a %SOUP-ENCODING% slot into which an encoding will be plugged later.""" if text[:3] == "xml": text = u"xml version='1.0' encoding='%SOUP-ENCODING%'" self._toStringSubclass(text, ProcessingInstruction) def handle_comment(self, text): "Handle comments as Comment objects." self._toStringSubclass(text, Comment) def handle_charref(self, ref): "Handle character references as data." if self.convertEntities: data = unichr(int(ref)) else: data = '&#%s;' % ref self.handle_data(data) def handle_entityref(self, ref): """Handle entity references as data, possibly converting known HTML and/or XML entity references to the corresponding Unicode characters.""" data = None if self.convertHTMLEntities: try: data = unichr(name2codepoint[ref]) except KeyError: pass if not data and self.convertXMLEntities: data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref) if not data and self.convertHTMLEntities and \ not self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref): # TODO: We've got a problem here. We're told this is # an entity reference, but it's not an XML entity # reference or an HTML entity reference. Nonetheless, # the logical thing to do is to pass it through as an # unrecognized entity reference. # # Except: when the input is "&carol;" this function # will be called with input "carol". When the input is # "AT&T", this function will be called with input # "T". We have no way of knowing whether a semicolon # was present originally, so we don't know whether # this is an unknown entity or just a misplaced # ampersand. # # The more common case is a misplaced ampersand, so I # escape the ampersand and omit the trailing semicolon. data = "&amp;%s" % ref if not data: # This case is different from the one above, because we # haven't already gone through a supposedly comprehensive # mapping of entities to Unicode characters. We might not # have gone through any mapping at all. So the chances are # very high that this is a real entity, and not a # misplaced ampersand. data = "&%s;" % ref self.handle_data(data) def handle_decl(self, data): "Handle DOCTYPEs and the like as Declaration objects." self._toStringSubclass(data, Declaration) def parse_declaration(self, i): """Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.""" j = None if self.rawdata[i:i+9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: k = len(self.rawdata) data = self.rawdata[i+9:k] j = k+3 self._toStringSubclass(data, CData) else: try: j = SGMLParser.parse_declaration(self, i) except SGMLParseError: toHandle = self.rawdata[i:] self.handle_data(toHandle) j = i + len(toHandle) return j class BeautifulSoup(BeautifulStoneSoup): """This parser knows the following facts about HTML: * Some tags have no closing tag and should be interpreted as being closed as soon as they are encountered. * The text inside some tags (ie. 'script') may contain tags which are not really part of the document and which should be parsed as text, not tags. If you want to parse the text as tags, you can always fetch it and parse it explicitly. * Tag nesting rules: Most tags can't be nested at all. For instance, the occurance of a <p> tag should implicitly close the previous <p> tag. <p>Para1<p>Para2 should be transformed into: <p>Para1</p><p>Para2 Some tags can be nested arbitrarily. For instance, the occurance of a <blockquote> tag should _not_ implicitly close the previous <blockquote> tag. Alice said: <blockquote>Bob said: <blockquote>Blah should NOT be transformed into: Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah Some tags can be nested, but the nesting is reset by the interposition of other tags. For instance, a <tr> tag should implicitly close the previous <tr> tag within the same <table>, but not close a <tr> tag in another table. <table><tr>Blah<tr>Blah should be transformed into: <table><tr>Blah</tr><tr>Blah but, <tr>Blah<table><tr>Blah should NOT be transformed into <tr>Blah<table></tr><tr>Blah Differing assumptions about tag nesting rules are a major source of problems with the BeautifulSoup class. If BeautifulSoup is not treating as nestable a tag your page author treats as nestable, try ICantBelieveItsBeautifulSoup, MinimalSoup, or BeautifulStoneSoup before writing your own subclass.""" def __init__(self, *args, **kwargs): if not kwargs.has_key('smartQuotesTo'): kwargs['smartQuotesTo'] = self.HTML_ENTITIES kwargs['isHTML'] = True BeautifulStoneSoup.__init__(self, *args, **kwargs) SELF_CLOSING_TAGS = buildTagMap(None, ('br' , 'hr', 'input', 'img', 'meta', 'spacer', 'link', 'frame', 'base', 'col')) PRESERVE_WHITESPACE_TAGS = set(['pre', 'textarea']) QUOTE_TAGS = {'script' : None, 'textarea' : None} #According to the HTML standard, each of these inline tags can #contain another tag of the same type. Furthermore, it's common #to actually use these tags this way. NESTABLE_INLINE_TAGS = ('span', 'font', 'q', 'object', 'bdo', 'sub', 'sup', 'center') #According to the HTML standard, these block tags can contain #another tag of the same type. Furthermore, it's common #to actually use these tags this way. NESTABLE_BLOCK_TAGS = ('blockquote', 'div', 'fieldset', 'ins', 'del') #Lists can contain other lists, but there are restrictions. NESTABLE_LIST_TAGS = { 'ol' : [], 'ul' : [], 'li' : ['ul', 'ol'], 'dl' : [], 'dd' : ['dl'], 'dt' : ['dl'] } #Tables can contain other tables, but there are restrictions. NESTABLE_TABLE_TAGS = {'table' : [], 'tr' : ['table', 'tbody', 'tfoot', 'thead'], 'td' : ['tr'], 'th' : ['tr'], 'thead' : ['table'], 'tbody' : ['table'], 'tfoot' : ['table'], } NON_NESTABLE_BLOCK_TAGS = ('address', 'form', 'p', 'pre') #If one of these tags is encountered, all tags up to the next tag of #this type are popped. RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript', NON_NESTABLE_BLOCK_TAGS, NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS, NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) # Used to detect the charset in a META tag; see start_meta CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M) def start_meta(self, attrs): """Beautiful Soup can detect a charset included in a META tag, try to convert the document to that charset, and re-parse the document from the beginning.""" httpEquiv = None contentType = None contentTypeIndex = None tagNeedsEncodingSubstitution = False for i in range(0, len(attrs)): key, value = attrs[i] key = key.lower() if key == 'http-equiv': httpEquiv = value elif key == 'content': contentType = value contentTypeIndex = i if httpEquiv and contentType: # It's an interesting meta tag. match = self.CHARSET_RE.search(contentType) if match: if (self.declaredHTMLEncoding is not None or self.originalEncoding == self.fromEncoding): # An HTML encoding was sniffed while converting # the document to Unicode, or an HTML encoding was # sniffed during a previous pass through the # document, or an encoding was specified # explicitly and it worked. Rewrite the meta tag. def rewrite(match): return match.group(1) + "%SOUP-ENCODING%" newAttr = self.CHARSET_RE.sub(rewrite, contentType) attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], newAttr) tagNeedsEncodingSubstitution = True else: # This is our first pass through the document. # Go through it again with the encoding information. newCharset = match.group(3) if newCharset and newCharset != self.originalEncoding: self.declaredHTMLEncoding = newCharset self._feed(self.declaredHTMLEncoding) raise StopParsing pass tag = self.unknown_starttag("meta", attrs) if tag and tagNeedsEncodingSubstitution: tag.containsSubstitutions = True class StopParsing(Exception): pass class ICantBelieveItsBeautifulSoup(BeautifulSoup): """The BeautifulSoup class is oriented towards skipping over common HTML errors like unclosed tags. However, sometimes it makes errors of its own. For instance, consider this fragment: <b>Foo<b>Bar</b></b> This is perfectly valid (if bizarre) HTML. However, the BeautifulSoup class will implicitly close the first b tag when it encounters the second 'b'. It will think the author wrote "<b>Foo<b>Bar", and didn't close the first 'b' tag, because there's no real-world reason to bold something that's already bold. When it encounters '</b></b>' it will close two more 'b' tags, for a grand total of three tags closed instead of two. This can throw off the rest of your document structure. The same is true of a number of other tags, listed below. It's much more common for someone to forget to close a 'b' tag than to actually use nested 'b' tags, and the BeautifulSoup class handles the common case. This class handles the not-co-common case: where you can't believe someone wrote what they did, but it's valid HTML and BeautifulSoup screwed up by assuming it wouldn't be.""" I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \ ('em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong', 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b', 'big') I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ('noscript',) NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS, I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS, I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS) class MinimalSoup(BeautifulSoup): """The MinimalSoup class is for parsing HTML that contains pathologically bad markup. It makes no assumptions about tag nesting, but it does know which tags are self-closing, that <script> tags contain Javascript and should not be parsed, that META tags may contain encoding information, and so on. This also makes it better for subclassing than BeautifulStoneSoup or BeautifulSoup.""" RESET_NESTING_TAGS = buildTagMap('noscript') NESTABLE_TAGS = {} class BeautifulSOAP(BeautifulStoneSoup): """This class will push a tag with only a single string child into the tag's parent as an attribute. The attribute's name is the tag name, and the value is the string child. An example should give the flavor of the change: <foo><bar>baz</bar></foo> => <foo bar="baz"><bar>baz</bar></foo> You can then access fooTag['bar'] instead of fooTag.barTag.string. This is, of course, useful for scraping structures that tend to use subelements instead of attributes, such as SOAP messages. Note that it modifies its input, so don't print the modified version out. I'm not sure how many people really want to use this class; let me know if you do. Mainly I like the name.""" def popTag(self): if len(self.tagStack) > 1: tag = self.tagStack[-1] parent = self.tagStack[-2] parent._getAttrMap() if (isinstance(tag, Tag) and len(tag.contents) == 1 and isinstance(tag.contents[0], NavigableString) and not parent.attrMap.has_key(tag.name)): parent[tag.name] = tag.contents[0] BeautifulStoneSoup.popTag(self) #Enterprise class names! It has come to our attention that some people #think the names of the Beautiful Soup parser classes are too silly #and "unprofessional" for use in enterprise screen-scraping. We feel #your pain! For such-minded folk, the Beautiful Soup Consortium And #All-Night Kosher Bakery recommends renaming this file to #"RobustParser.py" (or, in cases of extreme enterprisiness, #"RobustParserBeanInterface.class") and using the following #enterprise-friendly class aliases: class RobustXMLParser(BeautifulStoneSoup): pass class RobustHTMLParser(BeautifulSoup): pass class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup): pass class RobustInsanelyWackAssHTMLParser(MinimalSoup): pass class SimplifyingSOAPParser(BeautifulSOAP): pass ###################################################### # # Bonus library: Unicode, Dammit # # This class forces XML data into a standard format (usually to UTF-8 # or Unicode). It is heavily based on code from Mark Pilgrim's # Universal Feed Parser. It does not rewrite the XML or HTML to # reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi # (XML) and BeautifulSoup.start_meta (HTML). # Autodetects character encodings. # Download from http://chardet.feedparser.org/ try: import chardet # import chardet.constants # chardet.constants._debug = 1 except ImportError: chardet = None # cjkcodecs and iconv_codec make Python know about more character encodings. # Both are available from http://cjkpython.i18n.org/ # They're built in if you use Python 2.4. try: import cjkcodecs.aliases except ImportError: pass try: import iconv_codec except ImportError: pass class UnicodeDammit: """A class for detecting the encoding of a *ML document and converting it to a Unicode string. If the source encoding is windows-1252, can replace MS smart quotes with their HTML or XML equivalents.""" # This dictionary maps commonly seen values for "charset" in HTML # meta tags to the corresponding Python codec names. It only covers # values that aren't in Python's aliases and can't be determined # by the heuristics in find_codec. CHARSET_ALIASES = { "macintosh" : "mac-roman", "x-sjis" : "shift-jis" } def __init__(self, markup, overrideEncodings=[], smartQuotesTo='xml', isHTML=False): self.declaredHTMLEncoding = None self.markup, documentEncoding, sniffedEncoding = \ self._detectEncoding(markup, isHTML) self.smartQuotesTo = smartQuotesTo self.triedEncodings = [] if markup == '' or isinstance(markup, unicode): self.originalEncoding = None self.unicode = unicode(markup) return u = None for proposedEncoding in overrideEncodings: u = self._convertFrom(proposedEncoding) if u: break if not u: for proposedEncoding in (documentEncoding, sniffedEncoding): u = self._convertFrom(proposedEncoding) if u: break # If no luck and we have auto-detection library, try that: if not u and chardet and not isinstance(self.markup, unicode): u = self._convertFrom(chardet.detect(self.markup)['encoding']) # As a last resort, try utf-8 and windows-1252: if not u: for proposed_encoding in ("utf-8", "windows-1252"): u = self._convertFrom(proposed_encoding) if u: break self.unicode = u if not u: self.originalEncoding = None def _subMSChar(self, orig): """Changes a MS smart quote character to an XML or HTML entity.""" sub = self.MS_CHARS.get(orig) if isinstance(sub, tuple): if self.smartQuotesTo == 'xml': sub = '&#x%s;' % sub[1] else: sub = '&%s;' % sub[0] return sub def _convertFrom(self, proposed): proposed = self.find_codec(proposed) if not proposed or proposed in self.triedEncodings: return None self.triedEncodings.append(proposed) markup = self.markup # Convert smart quotes to HTML if coming from an encoding # that might have them. if self.smartQuotesTo and proposed.lower() in("windows-1252", "iso-8859-1", "iso-8859-2"): markup = re.compile("([\x80-\x9f])").sub \ (lambda(x): self._subMSChar(x.group(1)), markup) try: # print "Trying to convert document to %s" % proposed u = self._toUnicode(markup, proposed) self.markup = u self.originalEncoding = proposed except Exception, e: # print "That didn't work!" # print e return None #print "Correct encoding: %s" % proposed return self.markup def _toUnicode(self, data, encoding): '''Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == '\xfe\xff') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16be' data = data[2:] elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16le' data = data[2:] elif data[:3] == '\xef\xbb\xbf': encoding = 'utf-8' data = data[3:] elif data[:4] == '\x00\x00\xfe\xff': encoding = 'utf-32be' data = data[4:] elif data[:4] == '\xff\xfe\x00\x00': encoding = 'utf-32le' data = data[4:] newdata = unicode(data, encoding) return newdata def _detectEncoding(self, xml_data, isHTML=False): """Given a document, tries to detect its XML encoding.""" xml_encoding = sniffed_xml_encoding = None try: if xml_data[:4] == '\x4c\x6f\xa7\x94': # EBCDIC xml_data = self._ebcdic_to_ascii(xml_data) elif xml_data[:4] == '\x00\x3c\x00\x3f': # UTF-16BE sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \ and (xml_data[2:4] != '\x00\x00'): # UTF-16BE with BOM sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x3f\x00': # UTF-16LE sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data, 'utf-16le').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \ (xml_data[2:4] != '\x00\x00'): # UTF-16LE with BOM sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8') elif xml_data[:4] == '\x00\x00\x00\x3c': # UTF-32BE sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data, 'utf-32be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x00\x00': # UTF-32LE sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data, 'utf-32le').encode('utf-8') elif xml_data[:4] == '\x00\x00\xfe\xff': # UTF-32BE with BOM sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8') elif xml_data[:4] == '\xff\xfe\x00\x00': # UTF-32LE with BOM sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8') elif xml_data[:3] == '\xef\xbb\xbf': # UTF-8 with BOM sniffed_xml_encoding = 'utf-8' xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8') else: sniffed_xml_encoding = 'ascii' pass except: xml_encoding_match = None xml_encoding_match = re.compile( '^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data) if not xml_encoding_match and isHTML: regexp = re.compile('<\s*meta[^>]+charset=([^>]*?)[;\'">]', re.I) xml_encoding_match = regexp.search(xml_data) if xml_encoding_match is not None: xml_encoding = xml_encoding_match.groups()[0].lower() if isHTML: self.declaredHTMLEncoding = xml_encoding if sniffed_xml_encoding and \ (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16')): xml_encoding = sniffed_xml_encoding return xml_data, xml_encoding, sniffed_xml_encoding def find_codec(self, charset): return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \ or (charset and self._codec(charset.replace("-", ""))) \ or (charset and self._codec(charset.replace("-", "_"))) \ or charset def _codec(self, charset): if not charset: return charset codec = None try: codecs.lookup(charset) codec = charset except (LookupError, ValueError): pass return codec EBCDIC_TO_ASCII_MAP = None def _ebcdic_to_ascii(self, s): c = self.__class__ if not c.EBCDIC_TO_ASCII_MAP: emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15, 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31, 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7, 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26, 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33, 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94, 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63, 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34, 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200, 201,202,106,107,108,109,110,111,112,113,114,203,204,205, 206,207,208,209,126,115,116,117,118,119,120,121,122,210, 211,212,213,214,215,216,217,218,219,220,221,222,223,224, 225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72, 73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81, 82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89, 90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57, 250,251,252,253,254,255) import string c.EBCDIC_TO_ASCII_MAP = string.maketrans( \ ''.join(map(chr, range(256))), ''.join(map(chr, emap))) return s.translate(c.EBCDIC_TO_ASCII_MAP) MS_CHARS = { '\x80' : ('euro', '20AC'), '\x81' : ' ', '\x82' : ('sbquo', '201A'), '\x83' : ('fnof', '192'), '\x84' : ('bdquo', '201E'), '\x85' : ('hellip', '2026'), '\x86' : ('dagger', '2020'), '\x87' : ('Dagger', '2021'), '\x88' : ('circ', '2C6'), '\x89' : ('permil', '2030'), '\x8A' : ('Scaron', '160'), '\x8B' : ('lsaquo', '2039'), '\x8C' : ('OElig', '152'), '\x8D' : '?', '\x8E' : ('#x17D', '17D'), '\x8F' : '?', '\x90' : '?', '\x91' : ('lsquo', '2018'), '\x92' : ('rsquo', '2019'), '\x93' : ('ldquo', '201C'), '\x94' : ('rdquo', '201D'), '\x95' : ('bull', '2022'), '\x96' : ('ndash', '2013'), '\x97' : ('mdash', '2014'), '\x98' : ('tilde', '2DC'), '\x99' : ('trade', '2122'), '\x9a' : ('scaron', '161'), '\x9b' : ('rsaquo', '203A'), '\x9c' : ('oelig', '153'), '\x9d' : '?', '\x9e' : ('#x17E', '17E'), '\x9f' : ('Yuml', ''),} ####################################################################### #By default, act as an HTML pretty-printer. if __name__ == '__main__': import sys soup = BeautifulSoup(sys.stdin) print soup.prettify()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import model import PropertiesUtil import Constant from google.appengine.api import memcache class AppProperties (object): __instance = None __appDic = None __env = None def __new__(cls, *args, **kargs): if cls.__instance is None: cls.__instance = object.__new__(cls, *args, **kargs) return cls.__instance ''' Gets application properties ''' def getAppDic(self): if self.__appDic is None: self.__appDic = PropertiesUtil.loadProperties(r"conf/application.properties") return self.__appDic ''' Gets Jinja Environment ''' def getJinjaEnv(self): import os import jinja2 import gettext if self.__env is None: self.__env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '..', 'templates' )), extensions=['jinja2.ext.i18n'])##MOD '''self.__env.filters['relativize'] = self.relativize self.__env.filters['markdown'] = self.markdown self.__env.filters['smiley'] = self.smiley self.__env.filters['pagination'] = self.pagination self.__env.filters['media'] = self.media_content self.__env.filters['quote'] = self.quote''' ###################################################################################### # i18n configuration # Added: mo and po files # Mdofied: handlers and templates ###################################################################################### locale = '' try : locale = self.get_application().locale if locale is None or locale == "" : locale = Constant.DEFAULT_LOCALE except: locale = Constant.DEFAULT_LOCALE domain = 'django' localeDir = 'conf/locale' localeCodeset = 'UTF-8' langs=[locale]#, 'ca_ES', 'es']#'es', #os.environ["LANGUAGE"] = "en" translations = gettext.translation(domain, localeDir, languages=langs) #GNUTranslations #env = Environment(extensions=['jinja2.ext.i18n']) self.__env.install_gettext_translations(translations) gettext.textdomain(domain) gettext.bindtextdomain(gettext._current_domain, localeDir) gettext.bind_textdomain_codeset(gettext._current_domain, localeCodeset) #self.__env.shared = True return self.__env def updateJinjaEnv(self): self.__env = None self.getJinjaEnv() def getAccountProvider(self, regType = 0): if regType is None or regType == 0:# Local return self.get_application().name elif regType == 1: return "Google" return "" #Dup def get_application(self): app = memcache.get('app') if app is not None: # logging.debug('%s is already in the cache' % key) return app else: app = model.Application.all().get() # logging.debug('inserting %s in the cache' % key) memcache.add('app', app, 0) return app
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # main python imports import os import time import datetime import random import sha import Cookie import pickle # google appengine imports from google.appengine.ext import db from google.appengine.api import memcache # settings, if you have these set elsewhere, such as your django settings file, # you'll need to adjust the values to pull from there. COOKIE_NAME = 'appengine-utilities-session-sid' DEFAULT_COOKIE_PATH = '/' SESSION_EXPIRE_TIME = 7200 # sessions are valid for 7200 seconds (2 hours) CLEAN_CHECK_PERCENT = 15 # 15% of all requests will clean the database INTEGRATE_FLASH = True # integrate functionality from flash module? CHECK_IP = True # validate sessions by IP CHECK_USER_AGENT = True # validate sessions by user agent SET_COOKIE_EXPIRES = True # Set to True to add expiration field to cookie SESSION_TOKEN_TTL = 5 # Number of seconds a session token is valid for. class _AppEngineUtilities_Session(db.Model): """ Model for the sessions in the datastore. This contains the identifier and validation information for the session. """ sid = db.StringListProperty() ip = db.StringProperty() ua = db.StringProperty() last_activity = db.DateTimeProperty(auto_now=True) class _AppEngineUtilities_SessionData(db.Model): """ Model for the session data in the datastore. """ session = db.ReferenceProperty(_AppEngineUtilities_Session) keyname = db.StringProperty() content = db.BlobProperty() class Session(object): """ Sessions used to maintain user presence between requests. Sessions store a unique id as a cookie in the browser and referenced in a datastore object. This maintains user presence by validating requests as visits from the same browser. You can add extra data to the session object by using it as a dictionary object. Values can be any python object that can be pickled. For extra performance, session objects are also store in memcache and kept consistent with the datastore. This increases the performance of read requests to session data. """ def __init__(self, cookie_path=DEFAULT_COOKIE_PATH, cookie_name=COOKIE_NAME, session_expire_time=SESSION_EXPIRE_TIME, clean_check_percent=CLEAN_CHECK_PERCENT, integrate_flash=INTEGRATE_FLASH, check_ip=CHECK_IP, check_user_agent=CHECK_USER_AGENT, set_cookie_expires=SET_COOKIE_EXPIRES, session_token_ttl=SESSION_TOKEN_TTL): """ Initializer Args: cookie_name: The name for the session cookie stored in the browser. session_expire_time: The amount of time between requests before the session expires. clean_check_percent: The percentage of requests the will fire off a cleaning routine that deletes stale session data. integrate_flash: If appengine-utilities flash utility should be integrated into the session object. check_ip: If browser IP should be used for session validation check_user_agent: If the browser user agent should be used for sessoin validation. set_cookie_expires: True adds an expires field to the cookie so it saves even if the browser is closed. session_token_ttl: Number of sessions a session token is valid for before it should be regenerated. """ self.cookie_path = cookie_path self.cookie_name = cookie_name self.session_expire_time = session_expire_time self.clean_check_percent = clean_check_percent self.integrate_flash = integrate_flash self.check_user_agent = check_user_agent self.check_ip = check_ip self.set_cookie_expires = set_cookie_expires self.session_token_ttl = session_token_ttl """ Check the cookie and, if necessary, create a new one. """ self.cache = {} self.sid = None string_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) # check for existing cookie if self.cookie.get(cookie_name): self.sid = self.cookie[cookie_name].value # If there isn't a valid session for the cookie sid, # start a new session. self.session = self._get_session() if self.session is None: self.sid = self.new_sid() self.session = _AppEngineUtilities_Session() self.session.ua = os.environ['HTTP_USER_AGENT'] self.session.ip = os.environ['REMOTE_ADDR'] self.session.sid = [self.sid] self.cookie[cookie_name] = self.sid self.cookie[cookie_name]['path'] = cookie_path if set_cookie_expires: self.cookie[cookie_name]['expires'] = \ self.session_expire_time else: # check the age of the token to determine if a new one # is required duration = datetime.timedelta(seconds=self.session_token_ttl) session_age_limit = datetime.datetime.now() - duration if self.session.last_activity < session_age_limit: self.sid = self.new_sid() if len(self.session.sid) > 2: self.session.sid.remove(self.session.sid[0]) self.session.sid.append(self.sid) else: self.sid = self.session.sid[-1] self.cookie[cookie_name] = self.sid self.cookie[cookie_name]['path'] = cookie_path if set_cookie_expires: self.cookie[cookie_name]['expires'] = \ self.session_expire_time else: self.sid = self.new_sid() self.session = _AppEngineUtilities_Session() self.session.ua = os.environ['HTTP_USER_AGENT'] self.session.ip = os.environ['REMOTE_ADDR'] self.session.sid = [self.sid] self.cookie[cookie_name] = self.sid self.cookie[cookie_name]['path'] = cookie_path if set_cookie_expires: self.cookie[cookie_name]['expires'] = self.session_expire_time self.cache['sid'] = pickle.dumps(self.sid) # update the last_activity field in the datastore every time that # the session is accessed. This also handles the write for all # session data above. self.session.put() print self.cookie # fire up a Flash object if integration is enabled if self.integrate_flash: import flash self.flash = flash.Flash(cookie=self.cookie) # randomly delete old stale sessions in the datastore (see # CLEAN_CHECK_PERCENT variable) if random.randint(1, 100) < CLEAN_CHECK_PERCENT: self._clean_old_sessions() def new_sid(self): """ Create a new session id. """ sid = sha.new(repr(time.time()) + os.environ['REMOTE_ADDR'] + \ str(random.random())).hexdigest() return sid def _get_session(self): """ Get the user's session from the datastore """ query = _AppEngineUtilities_Session.all() query.filter('sid', self.sid) if self.check_user_agent: query.filter('ua', os.environ['HTTP_USER_AGENT']) if self.check_ip: query.filter('ip', os.environ['REMOTE_ADDR']) results = query.fetch(1) if len(results) is 0: return None else: sessionAge = datetime.datetime.now() - results[0].last_activity if sessionAge.seconds > self.session_expire_time: results[0].delete() return None return results[0] def _get(self, keyname=None): """ Return all of the SessionData object unless keyname is specified, in which case only that instance of SessionData is returned. Important: This does not interact with memcache and pulls directly from the datastore. Args: keyname: The keyname of the value you are trying to retrieve. """ query = _AppEngineUtilities_SessionData.all() query.filter('session', self.session) if keyname != None: query.filter('keyname =', keyname) results = query.fetch(1000) if len(results) is 0: return None if keyname != None: return results[0] return results def _validate_key(self, keyname): """ Validate the keyname, making sure it is set and not a reserved name. """ if keyname is None: raise ValueError('You must pass a keyname for the session' + \ ' data content.') elif keyname in ('sid', 'flash'): raise ValueError(keyname + ' is a reserved keyname.') if type(keyname) != type([str, unicode]): return str(keyname) return keyname def _put(self, keyname, value): """ Insert a keyname/value pair into the datastore for the session. Args: keyname: The keyname of the mapping. value: The value of the mapping. """ keyname = self._validate_key(keyname) if value is None: raise ValueError('You must pass a value to put.') sessdata = self._get(keyname=keyname) if sessdata is None: sessdata = _AppEngineUtilities_SessionData() sessdata.session = self.session sessdata.keyname = keyname sessdata.content = pickle.dumps(value) self.cache[keyname] = pickle.dumps(value) sessdata.put() self._set_memcache() def _delete_session(self): """ Delete the session and all session data for the sid passed. """ sessiondata = self._get() # delete from datastore if sessiondata is not None: for sd in sessiondata: sd.delete() # delete from memcache memcache.delete('sid-'+str(self.session.key())) # delete the session now that all items that reference it are deleted. self.session.delete() # if the event class has been loaded, fire off the sessionDeleted event if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('sessionDelete') def delete(self): """ Delete the current session and start a new one. This is useful for when you need to get rid of all data tied to a current session, such as when you are logging out a user. """ self._delete_session() def delete_all_sessions(self): """ Deletes all sessions and session data from the data store and memcache. """ all_sessions_deleted = False all_data_deleted = False while not all_sessions_deleted: query = _AppEngineUtilities_Session.all() results = query.fetch(1000) if len(results) is 0: all_sessions_deleted = True else: for result in results: result.delete() while not all_data_deleted: query = _AppEngineUtilities_SessionData.all() results = query.fetch(1000) if len(results) is 0: all_data_deleted = True else: for result in results: result.delete() def _clean_old_sessions(self): """ Delete expired sessions from the datastore. This is only called for CLEAN_CHECK_PERCENT percent of requests because it could be rather intensive. """ duration = datetime.timedelta(seconds=self.session_expire_time) session_age = datetime.datetime.now() - duration query = _AppEngineUtilities_Session.all() query.filter('last_activity <', session_age) results = query.fetch(1000) for result in results: data_query = _AppEngineUtilities_SessionData.all() query.filter('session', result) data_results = data_query.fetch(1000) for data_result in data_results: data_result.delete() memcache.delete('sid-'+str(result.key())) result.delete() # Implement Python container methods def __getitem__(self, keyname): """ Get item from session data. keyname: The keyname of the mapping. """ # flash messages don't go in the datastore if self.integrate_flash and (keyname == 'flash'): return self.flash.msg if keyname in self.cache: return pickle.loads(str(self.cache[keyname])) mc = memcache.get('sid-'+str(self.session.key())) if mc is not None: if keyname in mc: return mc[keyname] data = self._get(keyname) if data: self.cache[keyname] = data.content self._set_memcache() return pickle.loads(data.content) else: raise KeyError(str(keyname)) def __setitem__(self, keyname, value): """ Set item in session data. Args: keyname: They keyname of the mapping. value: The value of mapping. """ # if type(keyname) is type(''): # flash messages don't go in the datastore if self.integrate_flash and (keyname == 'flash'): self.flash.msg = value else: keyname = self._validate_key(keyname) self.cache[keyname] = value self._set_memcache() return self._put(keyname, value) # else: # raise TypeError('Session data objects are only accessible by' + \ # ' string keys, not numerical indexes.') def __delitem__(self, keyname): """ Delete item from session data. Args: keyname: The keyname of the object to delete. """ sessdata = self._get(keyname = keyname) if sessdata is None: raise KeyError(str(keyname)) sessdata.delete() if keyname in self.cache: del self.cache[keyname] self._set_memcache() def __len__(self): """ Return size of session. """ # check memcache first mc = memcache.get('sid-'+str(self.session.key())) if mc is not None: return len(mc) results = self._get() return len(results) def __contains__(self, keyname): """ Check if an item is in the session data. Args: keyname: The keyname being searched. """ try: r = self.__getitem__(keyname) except KeyError: return False return True def __iter__(self): """ Iterate over the keys in the session data. """ # try memcache first mc = memcache.get('sid-'+str(self.session.key())) if mc is not None: for k in mc: yield k else: for k in self._get(): yield k.keyname def __str__(self): """ Return string representation. """ return ', '.join(['("%s" = "%s")' % (k, self[k]) for k in self]) def _set_memcache(self): """ Set a memcache object with all the session date. Optionally you can add a key and value to the memcache for put operations. """ # Pull directly from the datastore in order to ensure that the # information is as up to date as possible. data = {} sessiondata = self._get() if sessiondata is not None: for sd in sessiondata: data[sd.keyname] = pickle.loads(sd.content) memcache.set('sid-'+str(self.session.key()), data, \ self.session_expire_time)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 John Cube <jonh.cube[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.api import urlfetch from utilities.BeautifulSoup import * import urllib import sys class TTSUtil (object): __instance = None __appDic = None __env = None def get_tts_stream_from_tts_urs(self,tts_urls): content="" for tts_url in tts_urls: url = "http://translate.google.com/translate_tts?tl=es&q=" + tts_url user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' try: result = urlfetch.fetch(url, payload=' ', method=urlfetch.GET, headers={'Content-Type': 'text/xml;charset=UTF-8', 'User-Agent' : user_agent}) if result.status_code == 200: content=content+result.content except: sys.__stdout__.write("Unexpected error:"+ str(sys.exc_info()[0])) #return the content return content def get_tts_url_from_html(self,html=None): # Constants (moove up) TTS_MAX_CHARACTERS=130 # TTS mp3 urls tts_urls=[]; # convert HTML to parsed text hexentityMassage = [(re.compile('&#x([^;]+);'), lambda m: '&#%d;' % int(m.group(1), 16))] soup=BeautifulSoup(html,convertEntities=BeautifulSoup.HTML_ENTITIES,markupMassage=hexentityMassage) # remove all tags text=''.join(soup.findAll(text=True)) # remove %0A characters tokens=text.strip('%0A').split('.') # iterate over the tokens (base on dot) for token in tokens: commatokens=token.split(',') # iterate over the tokens (base on comma) for commatoken in commatokens: # encode as url params params=urllib.quote(commatoken.encode('utf-8'),'') previous_index=0 while (previous_index<len(params)): last_index=params.rfind('%20',previous_index,previous_index+TTS_MAX_CHARACTERS) if (len(params)-previous_index)<=TTS_MAX_CHARACTERS: last_index=len(params) tts_urls.append(params[previous_index:last_index]) previous_index=last_index return tts_urls
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import __main__ class Event(object): """ Event is a simple publish/subscribe based event dispatcher It sets itself to the __main__ function. In order to use it, you must import it and __main__ """ def __init__(self): self.events = [] def subscribe(self, event, callback, args = None): """ This method will subscribe a callback function to an event name. """ if not {"event": event, "callback": callback, "args": args, } \ in self.events: self.events.append({"event": event, "callback": callback, \ "args": args, }) def unsubscribe(self, event, callback, args = None): """ This method will unsubscribe a callback from an event. """ if {"event": event, "callback": callback, "args": args, }\ in self.events: self.events.remove({"event": event, "callback": callback,\ "args": args, }) def fire_event(self, event = None): """ This method is what a method uses to fire an event, initiating all registered callbacks """ for e in self.events: if e["event"] == event: if type(e["args"]) == type([]): e["callback"](*e["args"]) elif type(e["args"]) == type({}): e["callback"](**e["args"]) elif e["args"] == None: e["callback"]() else: e["callback"](e["args"]) """ Assign to the event class to __main__ """ __main__.AEU_Events = Event()
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import os import Cookie import pickle COOKIE_NAME = 'appengine-utilities-flash' class Flash(object): """ Send messages to the user between pages. When you instantiate the class, the attribute 'msg' will be set from the cookie, and the cookie will be deleted. If there is no flash cookie, 'msg' will default to None. To set a flash message for the next page, simply set the 'msg' attribute. Example psuedocode: if new_entity.put(): flash = Flash() flash.msg = 'Your new entity has been created!' return redirect_to_entity_list() Then in the template on the next page: {% if flash.msg %} <div class="flash-msg">{{ flash.msg }}</div> {% endif %} """ def __init__(self, cookie=None): """ Load the flash message and clear the cookie. """ # load cookie if cookie is None: browser_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(browser_cookie) else: self.cookie = cookie # check for flash data if self.cookie.get(COOKIE_NAME): # set 'msg' attribute cookie_val = self.cookie[COOKIE_NAME].value # we don't want to trigger __setattr__(), which creates a cookie self.__dict__['msg'] = pickle.loads(cookie_val) # clear the cookie self.cookie[COOKIE_NAME] = '' self.cookie[COOKIE_NAME]['path'] = '/' self.cookie[COOKIE_NAME]['expires'] = 0 print self.cookie else: # default 'msg' attribute to None self.__dict__['msg'] = None def __setattr__(self, name, value): """ Create a cookie when setting the 'msg' attribute. """ if name == 'cookie': self.__dict__['cookie'] = value elif name == 'msg': self.__dict__['msg'] = value self.__dict__['cookie'][COOKIE_NAME] = pickle.dumps(value) self.__dict__['cookie'][COOKIE_NAME]['path'] = '/' print self.cookie else: raise ValueError('You can only set the "msg" attribute.')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## def loadProperties(fileName): propFile = file(fileName, "rU" ) propDict = dict() for propLine in propFile: propDef = propLine.strip() if len(propDef) == 0: continue if propDef[0] in ( '!', '#' ): continue punctuation = [ propDef.find(c) for c in ':= ' ] + [ len(propDef) ] found = min( [ pos for pos in punctuation if pos != -1 ] ) name = propDef[:found].rstrip() value = propDef[found:].lstrip(":= ").rstrip() propDict[name] = value propFile.close() return propDict
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## # Global properties DEFAULT_LOCALE = "en" locale = "locale" appName = "app_name" appSubject = "app_subject" domain = "domain"
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # main python imports import datetime import pickle import random import __main__ # google appengine import from google.appengine.ext import db from google.appengine.api import memcache # settings DEFAULT_TIMEOUT = 3600 # cache expires after one hour (3600 sec) CLEAN_CHECK_PERCENT = 15 # 15% of all requests will clean the database MAX_HITS_TO_CLEAN = 1000 # the maximum number of cache hits to clean on attempt class _AppEngineUtilities_Cache(db.Model): # It's up to the application to determine the format of their keys cachekey = db.StringProperty() createTime = db.DateTimeProperty(auto_now_add=True) timeout = db.DateTimeProperty() value = db.BlobProperty() class Cache(object): """ Cache is used for storing pregenerated output and/or objects in the Big Table datastore to minimize the amount of queries needed for page displays. The idea is that complex queries that generate the same results really should only be run once. Cache can be used to store pregenerated value made from queries (or other calls such as urlFetch()), or the query objects themselves. """ def __init__(self, clean_check_percent = CLEAN_CHECK_PERCENT, max_hits_to_clean = MAX_HITS_TO_CLEAN, default_timeout = DEFAULT_TIMEOUT): """ Initializer Args: clean_check_percent: how often cache initialization should run the cache cleanup max_hits_to_clean: maximum number of stale hits to clean default_timeout: default length a cache article is good for """ self.clean_check_percent = clean_check_percent self.max_hits_to_clean = max_hits_to_clean self.default_timeout = default_timeout if random.randint(1, 100) < self.clean_check_percent: self._clean_cache() if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheInitialized') def _clean_cache(self): """ _clean_cache is a routine that is run to find and delete cache articles that are old. This helps keep the size of your over all datastore down. """ query = _AppEngineUtilities_Cache.all() query.filter('expires < ', datetime.datetime.now()) results = query.fetch(self.max_hits_to_clean) for result in results: result.delete() def _validate_key(self, key): if key == None: raise KeyError def _validate_value(self, value): if value == None: raise ValueError def _validate_timeout(self, timeout): if timeout == None: timeout = datetime.datetime.now() +\ datetime.timedelta(seconds=DEFAULT_TIMEOUT) if type(timeout) == type(1): timeout = datetime.datetime.now() + \ datetime.timedelta(seconds = timeout) if type(timeout) != datetime.datetime: raise TypeError if timeout < datetime.datetime.now(): raise ValueError return timeout def add(self, key = None, value = None, timeout = None): """ add adds an entry to the cache, if one does not already exist. """ self._validate_key(key) self._validate_value(value) timeout = self._validate_timeout(timeout) if key in self: raise KeyError cacheEntry = _AppEngineUtilities_Cache() cacheEntry.cachekey = key cacheEntry.value = pickle.dumps(value) cacheEntry.timeout = timeout cacheEntry.put() memcache_timeout = timeout - datetime.datetime.now() memcache.set('cache-'+key, value, int(memcache_timeout.seconds)) if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheAdded') def set(self, key = None, value = None, timeout = None): """ add adds an entry to the cache, overwriting an existing value if one already exists. """ self._validate_key(key) self._validate_value(value) timeout = self._validate_timeout(timeout) cacheEntry = self._read(key) if not cacheEntry: cacheEntry = _AppEngineUtilities_Cache() cacheEntry.cachekey = key cacheEntry.value = pickle.dumps(value) cacheEntry.timeout = timeout cacheEntry.put() memcache_timeout = timeout - datetime.datetime.now() memcache.set('cache-'+key, value, int(memcache_timeout.seconds)) if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheSet') def _read(self, key = None): """ _read returns a cache object determined by the key. It's set to private because it returns a db.Model object, and also does not handle the unpickling of objects making it not the best candidate for use. The special method __getarticle__ is the preferred access method for cache data. """ query = _AppEngineUtilities_Cache.all() query.filter('cachekey', key) query.filter('timeout > ', datetime.datetime.now()) results = query.fetch(1) if len(results) is 0: return None return results[0] if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheReadFromDatastore') if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheRead') def delete(self, key = None): """ Deletes a cache object determined by the key. """ memcache.delete('cache-'+key) result = self._read(key) if result: if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheDeleted') result.delete() def get(self, key): """ get is used to return the cache value associated with the key passed. """ mc = memcache.get('cache-'+key) if mc: if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheReadFromMemcache') if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheRead') return mc result = self._read(key) if result: timeout = result.timeout - datetime.datetime.now() # print timeout.seconds memcache.set('cache-'+key, pickle.loads(result.value), int(timeout.seconds)) return pickle.loads(result.value) else: raise KeyError def get_many(self, keys): """ Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict. """ dict = {} for key in keys: value = self.get(key) if value is not None: dict[key] = val return dict def __getarticle__(self, key): """ __getarticle__ is necessary for this object to emulate a container. """ return self.get(key) def __setarticle__(self, key, value): """ __setarticle__ is necessary for this object to emulate a container. """ return self.set(key, value) def __delarticle__(self, key): """ Implement the 'del' keyword """ return self.delete(key) def __contains__(self, key): """ Implements "in" operator """ try: r = self.__getarticle__(key) except KeyError: return False return True
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import search class UserData(search.SearchableModel): nickname = db.StringProperty(required=True) personal_message = db.StringProperty() email = db.StringProperty(required=True) avatar = db.BlobProperty() thumbnail = db.BlobProperty() image_version = db.IntegerProperty() list_urls = db.StringListProperty() im_addresses = db.StringListProperty() about_user = db.TextProperty() password = db.StringProperty(required=False)#mod to accept Google account registrationType = db.IntegerProperty()#0 -local, 1 - google rol = db.StringProperty() google_adsense = db.StringProperty() google_adsense_channel = db.StringProperty() token = db.StringProperty() checked = db.BooleanProperty() # articles articles = db.IntegerProperty(required=True) draft_articles = db.IntegerProperty(required=True) # messages messages = db.IntegerProperty(required=True) draft_messages = db.IntegerProperty(required=True) unread_messages = db.IntegerProperty() sent_messages = db.IntegerProperty() # comments comments = db.IntegerProperty(required=True) # rating rating_count = db.IntegerProperty(required=True) rating_total = db.IntegerProperty(required=True) rating_average = db.IntegerProperty(required=True) # forums threads = db.IntegerProperty(required=True) responses = db.IntegerProperty(required=True) # communities communities = db.IntegerProperty(required=True) # favourites favourites = db.IntegerProperty(required=True) # others real_name = db.StringProperty() country = db.StringProperty() city = db.StringProperty() public = db.BooleanProperty(required=True) contacts = db.IntegerProperty() last_update = db.DateTimeProperty(auto_now=True) creation_date = db.DateTimeProperty(auto_now_add=True) deletion_date = db.DateTimeProperty() last_login = db.DateTimeProperty() banned_date = db.DateTimeProperty() not_full_rss = db.BooleanProperty() class ArticleHtml(db.Model): content = db.TextProperty(required=True) class ArticleTTS(db.Model): tts_stream = db.TextProperty(required=True) tts_urls = db.StringListProperty() class Article(search.SearchableModel): author = db.ReferenceProperty(UserData,required=True) author_nickname = db.StringProperty() title = db.StringProperty(required=True) description = db.StringProperty(required=True) content = db.TextProperty(required=True) content_html = db.ReferenceProperty(ArticleHtml) content_tts = db.ReferenceProperty(ArticleTTS) lic = db.StringProperty(required=True) views = db.IntegerProperty(required=True) rating_count = db.IntegerProperty(required=True) rating_total = db.IntegerProperty(required=True) rating_average = db.IntegerProperty() url_path = db.StringProperty(required=True) responses = db.IntegerProperty(required=True) tags = db.StringListProperty() favourites = db.IntegerProperty(required=True) draft = db.BooleanProperty(required=True) article_type = db.StringProperty(required=True) subscribers = db.StringListProperty() last_update = db.DateTimeProperty(auto_now=True) creation_date = db.DateTimeProperty(auto_now_add=True) deletion_date = db.DateTimeProperty() deletion_message = db.StringProperty() deletion_user = db.ReferenceProperty(UserData,collection_name='du') class Mblog(search.SearchableModel): author = db.ReferenceProperty(UserData,required=True) author_nickname = db.StringProperty() content = db.TextProperty(required=True) responses = db.IntegerProperty(required=True) creation_date = db.DateTimeProperty(auto_now_add=True) deletion_date = db.DateTimeProperty() deletion_user_nick = db.StringProperty() class Module(db.Model): name = db.TextProperty(required=True) active = db.BooleanProperty() class Comment(db.Model): content = db.TextProperty(required=True) article = db.ReferenceProperty(Article,required=True) author = db.ReferenceProperty(UserData,required=True) author_nickname = db.StringProperty() response_number = db.IntegerProperty() last_update = db.DateTimeProperty(auto_now=True) creation_date = db.DateTimeProperty(auto_now_add=True) deletion_date = db.DateTimeProperty() editions = db.IntegerProperty() last_edition = db.DateTimeProperty() class Vote(db.Model): user = db.ReferenceProperty(UserData,required=True) article = db.ReferenceProperty(Article,required=True) rating = db.IntegerProperty(required=True) class Tag(db.Model): tag = db.StringProperty(required=True) count = db.IntegerProperty(required=True) class Category(db.Model): parent_category = db.SelfReferenceProperty() title = db.StringProperty(required=True) url_path = db.StringProperty() description = db.StringProperty(required=True) communities = db.IntegerProperty(required=True) articles = db.IntegerProperty(required=True) subcategories = None class Community(search.SearchableModel): owner = db.ReferenceProperty(UserData,required=True) owner_nickname = db.StringProperty() title = db.StringProperty(required=True) description = db.StringProperty(required=True, multiline=True) url_path = db.StringProperty(required=True) old_url_path = db.StringProperty() subscribers = db.StringListProperty() members = db.IntegerProperty(required=True) articles = db.IntegerProperty(required=True) threads = db.IntegerProperty(required=True) responses = db.IntegerProperty(required=True) last_update = db.DateTimeProperty(auto_now=True) creation_date = db.DateTimeProperty(auto_now_add=True) deletion_date = db.DateTimeProperty() avatar = db.BlobProperty() thumbnail = db.BlobProperty() image_version = db.IntegerProperty() all_users = db.BooleanProperty() category = db.ReferenceProperty(Category, collection_name='communities_set') activity = db.IntegerProperty() class CommunityUser(db.Model): user = db.ReferenceProperty(UserData,required=True) community = db.ReferenceProperty(Community,required=True) creation_date = db.DateTimeProperty(auto_now_add=True) # denormalizationzation user_nickname = db.StringProperty() community_title = db.StringProperty() community_url_path = db.StringProperty() class CommunityArticle(db.Model): article = db.ReferenceProperty(Article,required=True) community = db.ReferenceProperty(Community,required=True) creation_date = db.DateTimeProperty(auto_now_add=True) # denormalization article_author_nickname = db.StringProperty() article_title = db.StringProperty() article_url_path = db.StringProperty() community_title = db.StringProperty() community_url_path = db.StringProperty() class Thread(search.SearchableModel): community = db.ReferenceProperty(Community,required=True) community_title = db.StringProperty() community_url_path = db.StringProperty() author = db.ReferenceProperty(UserData,required=True) author_nickname = db.StringProperty() title = db.StringProperty(required=True) url_path = db.StringProperty() content = db.TextProperty(required=True) subscribers = db.StringListProperty() last_response_date = db.DateTimeProperty() response_number = db.IntegerProperty() editions = db.IntegerProperty() last_edition = db.DateTimeProperty() # responses parent_thread = db.SelfReferenceProperty() responses = db.IntegerProperty(required=True) latest_response = db.DateTimeProperty() last_update = db.DateTimeProperty(auto_now=True) creation_date = db.DateTimeProperty(auto_now_add=True) deletion_date = db.DateTimeProperty() deletion_message = db.StringProperty() views = db.IntegerProperty() class Favourite(db.Model): article = db.ReferenceProperty(Article,required=True) user = db.ReferenceProperty(UserData,required=True) creation_date = db.DateTimeProperty(auto_now_add=True) # denormalize article_author_nickname = db.StringProperty() article_title = db.StringProperty() article_url_path = db.StringProperty() user_nickname = db.StringProperty() class Contact(db.Model): user_from = db.ReferenceProperty(UserData,required=True,collection_name='cf') user_to = db.ReferenceProperty(UserData,required=True,collection_name='ct') creation_date = db.DateTimeProperty(auto_now_add=True) # denormalize user_from_nickname = db.StringProperty() user_to_nickname = db.StringProperty() class Application(db.Model): name = db.StringProperty() logo = db.BlobProperty() theme = db.StringProperty() subject = db.StringProperty() locale = db.StringProperty() users = db.IntegerProperty() communities = db.IntegerProperty() articles = db.IntegerProperty() threads = db.IntegerProperty() url = db.StringProperty() mail_contact = db.StringProperty() mail_subject_prefix = db.StringProperty() mail_sender = db.StringProperty() mail_footer = db.StringProperty() recaptcha_public_key = db.StringProperty() recaptcha_private_key = db.StringProperty() google_adsense = db.StringProperty() google_adsense_channel = db.StringProperty() google_analytics = db.StringProperty() max_results = db.IntegerProperty() max_results_sublist = db.IntegerProperty() session_seed = db.StringProperty() version = db.StringProperty() class Message(db.Model): user_from = db.ReferenceProperty(UserData,required=True,collection_name='mf') user_to = db.ReferenceProperty(UserData,required=True,collection_name='mt') creation_date = db.DateTimeProperty(auto_now_add=True) title = db.StringProperty(required=True) url_path = db.StringProperty(required=True) content = db.TextProperty(required=True) read = db.BooleanProperty(required=True) from_deletion_date = db.DateTimeProperty() to_deletion_date = db.DateTimeProperty() user_from_nickname = db.StringProperty() user_to_nickname = db.StringProperty() class RelatedCommunity(db.Model): community_from = db.ReferenceProperty(Community,required=True,collection_name='gf') community_to = db.ReferenceProperty(Community,required=True,collection_name='gt') creation_date = db.DateTimeProperty(auto_now_add=True) # denormalization community_from_title = db.StringProperty(required=True) community_from_url_path = db.StringProperty(required=True) community_to_title = db.StringProperty(required=True) community_to_url_path = db.StringProperty(required=True) class UserSubscription(db.Model): user = db.ReferenceProperty(UserData,required=True) user_email = db.StringProperty(required=True) user_nickname = db.StringProperty(required=True) subscription_type = db.StringProperty(required=True) subscription_id = db.IntegerProperty(required=True) creation_date = db.DateTimeProperty() class Follower(db.Model): object_type = db.StringProperty(required=True) object_id = db.IntegerProperty(required=True) followers = db.StringListProperty() class Event(db.Model): event_type = db.StringProperty(required=True) followers = db.StringListProperty() user = db.ReferenceProperty(UserData,required=True) user_nickname = db.StringProperty(required=True) user_to = db.ReferenceProperty(UserData,collection_name='events_user_to') user_to_nickname = db.StringProperty() community = db.ReferenceProperty(Community) community_title = db.StringProperty() community_url_path = db.StringProperty() article = db.ReferenceProperty(Article) article_author_nickname = db.StringProperty() article_title = db.StringProperty() article_url_path = db.StringProperty() thread = db.ReferenceProperty(Thread) thread_title = db.StringProperty() thread_url_path = db.StringProperty() response_number = db.IntegerProperty() creation_date = db.DateTimeProperty(auto_now_add=True) class MailQueue(db.Model): subject = db.StringProperty(required=True) body = db.TextProperty(required=True) to = db.StringListProperty() bcc = db.StringListProperty() class Recommendation(db.Model): article_from = db.ReferenceProperty(Article,collection_name='recommendations_from') article_to = db.ReferenceProperty(Article,collection_name='recommendations_to') value = db.FloatProperty() article_from_title = db.StringProperty(required=True) article_to_title = db.StringProperty(required=True) article_from_author_nickname = db.StringProperty(required=True) article_to_author_nickname = db.StringProperty(required=True) article_from_url_path = db.StringProperty(required=True) article_to_url_path = db.StringProperty(required=True) class Task(db.Model): task_type = db.StringProperty(required=True) priority = db.IntegerProperty(required=True) data = db.StringProperty(required=True, multiline=True) creation_date = db.DateTimeProperty(auto_now_add=True) class Image(db.Model): # No restrictions by community or user # All files are public, but only owner or admin can browse them # Due image size, those must be deleted. author = db.ReferenceProperty(UserData,required=True) author_nickname = db.StringProperty(required=True) thumbnail = db.BlobProperty(required=True) url_path = db.StringProperty(required=True)#Unique image_version = db.IntegerProperty() creation_date = db.DateTimeProperty(auto_now_add=True)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from django import template from google.appengine.ext import webapp from utilities.AppProperties import AppProperties register = webapp.template.create_template_register() import datetime def relativize(value): now = datetime.datetime.now() diff = now - value days = diff.days seconds = diff.seconds if days > 365: return getLocale("%d years") % (days / 365, ) if days > 30: return getLocale("%d months") % (days / 30, ) if days > 0: return getLocale("%d days") % (days, ) if seconds > 3600: return getLocale("%d hours") % (seconds / 3600, ) if seconds > 60: return getLocale("%d minutes") % (seconds / 60, ) return getLocale("%d seconds") % (seconds, ) register.filter(relativize) def nolinebreaks(value): return ' '.join(str(value).splitlines()) register.filter(nolinebreaks) def markdown(value, arg=''): try: import markdown except ImportError: return "error" else: extensions=arg.split(",") return markdown.markdown(value, extensions, safe_mode=True) register.filter(markdown) def smiley(value): value = value.replace(' :)', ' <img src="/static/images/smileys/smile.png" class="icon" alt=":)" />') value = value.replace(' :-)', ' <img src="/static/images/smileys/smile.png" class="icon" alt=":-)" />') value = value.replace(' :D', ' <img src="/static/images/smileys/jokingly.png" class="icon" alt=":D" />') value = value.replace(' :-D', ' <img src="/static/images/smileys/jokingly.png" class="icon" alt=":-D" />') value = value.replace(' :(', ' <img src="/static/images/smileys/sad.png" class="icon" alt=":(" />') value = value.replace(' :-(', ' <img src="/static/images/smileys/sad.png" class="icon" alt=":-(" />') value = value.replace(' :|', ' <img src="/static/images/smileys/indifference.png" class="icon" alt=":|" />') value = value.replace(' :-|', ' <img src="/static/images/smileys/indifference.png" class="icon" alt=":-|" />') value = value.replace(' :O', ' <img src="/static/images/smileys/surprised.png" class="icon" alt=":O" />') value = value.replace(' :/', ' <img src="/static/images/smileys/think.png" class="icon" alt=":/" />') value = value.replace(' :P', ' <img src="/static/images/smileys/tongue.png" class="icon" alt=":P" />') value = value.replace(' :-P', ' <img src="/static/images/smileys/tongue.png" class="icon" alt=":-P" />') value = value.replace(' ;)', ' <img src="/static/images/smileys/wink.png" class="icon" alt=";)" />') value = value.replace(' ;-)', ' <img src="/static/images/smileys/wink.png" class="icon" alt=";-)" />') value = value.replace(' :*)', ' <img src="/static/images/smileys/embarrassed.png" class="icon" alt=":*)" />') value = value.replace(' 8-)', ' <img src="/static/images/smileys/cool.png" class="icon" alt="8-)" />') # value = value.replace(' :'(', ' <img src="/static/images/smileys/cry.png" class="icon" alt=":'(" />') value = value.replace(' :_(', ' <img src="/static/images/smileys/cry.png" class="icon" alt=":_(" />') value = value.replace(' :-X', ' <img src="/static/images/smileys/crossedlips.png" class="icon" alt=":-X" />') return value register.filter(smiley) #This Pagination is deprecated class Pagination(template.Node): def render(self,context): prev = self.get('prev', context) next = self.get('next', context) params = [] p = self.get('p', context) q = self.get('q', context) a = self.get('a', context) t = self.get('article_type', context) if a: a = '#%s' % str(a) else: a = '' if t: t = '&amp;article_type=%s' % str(t) else: t = '' s = '' if prev or next: s = '<p class="paginator">' if prev: if prev == 1: if q: qp = 'q=%s' % str(q) else: qp = '' s = '%s<a href="?%s%s%s">« %s</a> |' % (s, qp, t, a, getLocale("Previous")) else: if q: qp = '&amp;q=%s' % str(q) else: qp = '' s = '%s<a href="?p=%d%s%s%s">« %s</a> |' % (s, prev, qp, t, a, getLocale("Previous")) s = '%s '+getLocale("Page")+' %d ' % (s, p) if next: if q: q = '&amp;q=%s' % str(q) else: q = '' s = '%s| <a href="?p=%d%s%s%s">%s »</a>' % (s, next, q, t, a, getLocale("Next")) s = '%s</p>' % s return s def get(self, key, context): try: return template.resolve_variable(key, context) except template.VariableDoesNotExist: return None ### i18n def getLocale(label): env = AppProperties().getJinjaEnv() t = env.get_template("/translator-util.html") return t.render({"label": label}) @register.tag def pagination(parser, token): return Pagination()
Python
""" Implementation of JSONEncoder """ import re try: from simplejson import _speedups except ImportError: _speedups = None ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"/]|[^\ -~])') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } for i in range(0x20): ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) # assume this produces an infinity on all machines (probably not guaranteed) INFINITY = float('1e66666') FLOAT_REPR = repr def floatstr(o, allow_nan=True): # Check for specials. Note that this type of test is processor- and/or # platform-specific, so do tests which don't depend on the internals. if o != o: text = 'NaN' elif o == INFINITY: text = 'Infinity' elif o == -INFINITY: text = '-Infinity' else: return FLOAT_REPR(o) if not allow_nan: raise ValueError("Out of range float values are not JSON compliant: %r" % (o,)) return text def encode_basestring(s): """ Return a JSON representation of a Python string """ def replace(match): return ESCAPE_DCT[match.group(0)] return '"' + ESCAPE.sub(replace, s) + '"' def encode_basestring_ascii(s): def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' try: encode_basestring_ascii = _speedups.encode_basestring_ascii _need_utf8 = True except AttributeError: _need_utf8 = False class JSONEncoder(object): """ Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ __all__ = ['__init__', 'default', 'encode', 'iterencode'] item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None): """ Constructor for JSONEncoder, with sensible defaults. If skipkeys is False, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is True, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is True, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is True, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is True, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.indent = indent self.current_indent_level = 0 if separators is not None: self.item_separator, self.key_separator = separators if default is not None: self.default = default self.encoding = encoding def _newline_indent(self): return '\n' + (' ' * (self.indent * self.current_indent_level)) def _iterencode_list(self, lst, markers=None): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst yield '[' if self.indent is not None: self.current_indent_level += 1 newline_indent = self._newline_indent() separator = self.item_separator + newline_indent yield newline_indent else: newline_indent = None separator = self.item_separator first = True for value in lst: if first: first = False else: yield separator for chunk in self._iterencode(value, markers): yield chunk if newline_indent is not None: self.current_indent_level -= 1 yield self._newline_indent() yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(self, dct, markers=None): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' key_separator = self.key_separator if self.indent is not None: self.current_indent_level += 1 newline_indent = self._newline_indent() item_separator = self.item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = self.item_separator first = True if self.ensure_ascii: encoder = encode_basestring_ascii else: encoder = encode_basestring allow_nan = self.allow_nan if self.sort_keys: keys = dct.keys() keys.sort() items = [(k, dct[k]) for k in keys] else: items = dct.iteritems() _encoding = self.encoding _do_decode = (_encoding is not None and not (_need_utf8 and _encoding == 'utf-8')) for key, value in items: if isinstance(key, str): if _do_decode: key = key.decode(_encoding) elif isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = floatstr(key, allow_nan) elif isinstance(key, (int, long)): key = str(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif self.skipkeys: continue else: raise TypeError("key %r is not a string" % (key,)) if first: first = False else: yield item_separator yield encoder(key) yield key_separator for chunk in self._iterencode(value, markers): yield chunk if newline_indent is not None: self.current_indent_level -= 1 yield self._newline_indent() yield '}' if markers is not None: del markers[markerid] def _iterencode(self, o, markers=None): if isinstance(o, basestring): if self.ensure_ascii: encoder = encode_basestring_ascii else: encoder = encode_basestring _encoding = self.encoding if (_encoding is not None and isinstance(o, str) and not (_need_utf8 and _encoding == 'utf-8')): o = o.decode(_encoding) yield encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield floatstr(o, self.allow_nan) elif isinstance(o, (list, tuple)): for chunk in self._iterencode_list(o, markers): yield chunk elif isinstance(o, dict): for chunk in self._iterencode_dict(o, markers): yield chunk else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o for chunk in self._iterencode_default(o, markers): yield chunk if markers is not None: del markers[markerid] def _iterencode_default(self, o, markers=None): newobj = self.default(o) return self._iterencode(newobj, markers) def default(self, o): """ Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError("%r is not JSON serializable" % (o,)) def encode(self, o): """ Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks... if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8' and _need_utf8)): o = o.decode(_encoding) return encode_basestring_ascii(o) # This doesn't pass the iterator directly to ''.join() because it # sucks at reporting exceptions. It's going to do this internally # anyway because it uses PySequence_Fast or similar. chunks = list(self.iterencode(o)) return ''.join(chunks) def iterencode(self, o): """ Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None return self._iterencode(o, markers) __all__ = ['JSONEncoder']
Python
import simplejson import cgi class JSONFilter(object): def __init__(self, app, mime_type='text/x-json'): self.app = app self.mime_type = mime_type def __call__(self, environ, start_response): # Read JSON POST input to jsonfilter.json if matching mime type response = {'status': '200 OK', 'headers': []} def json_start_response(status, headers): response['status'] = status response['headers'].extend(headers) environ['jsonfilter.mime_type'] = self.mime_type if environ.get('REQUEST_METHOD', '') == 'POST': if environ.get('CONTENT_TYPE', '') == self.mime_type: args = [_ for _ in [environ.get('CONTENT_LENGTH')] if _] data = environ['wsgi.input'].read(*map(int, args)) environ['jsonfilter.json'] = simplejson.loads(data) res = simplejson.dumps(self.app(environ, json_start_response)) jsonp = cgi.parse_qs(environ.get('QUERY_STRING', '')).get('jsonp') if jsonp: content_type = 'text/javascript' res = ''.join(jsonp + ['(', res, ')']) elif 'Opera' in environ.get('HTTP_USER_AGENT', ''): # Opera has bunk XMLHttpRequest support for most mime types content_type = 'text/plain' else: content_type = self.mime_type headers = [ ('Content-type', content_type), ('Content-length', len(res)), ] headers.extend(response['headers']) start_response(response['status'], headers) return [res] def factory(app, global_conf, **kw): return JSONFilter(app, **kw)
Python
""" Implementation of JSONDecoder """ import re import sys from simplejson.scanner import Scanner, pattern try: from simplejson import _speedups except: _speedups = None FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): import struct import sys _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') if sys.byteorder != 'big': _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): lineno, colno = linecol(doc, pos) if end is None: return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) return '%s: line %d column %d - line %d column %d (char %d - %d)' % ( msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, 'true': True, 'false': False, 'null': None, } def JSONConstant(match, context, c=_CONSTANTS): s = match.group(0) fn = getattr(context, 'parse_constant', None) if fn is None: rval = c[s] else: rval = fn(s) return rval, None pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant) def JSONNumber(match, context): match = JSONNumber.regex.match(match.string, *match.span()) integer, frac, exp = match.groups() if frac or exp: fn = getattr(context, 'parse_float', None) or float res = fn(integer + (frac or '') + (exp or '')) else: fn = getattr(context, 'parse_int', None) or int res = fn(integer) return res, None pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber) STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise ValueError( errmsg("Unterminated string starting at", s, begin)) end = chunk.end() content, terminator = chunk.groups() if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) if terminator == '"': break elif terminator != '\\': if strict: raise ValueError(errmsg("Invalid control character %r at", s, end)) else: _append(terminator) continue try: esc = s[end] except IndexError: raise ValueError( errmsg("Unterminated string starting at", s, begin)) if esc != 'u': try: m = _b[esc] except KeyError: raise ValueError( errmsg("Invalid \\escape: %r" % (esc,), s, end)) end += 1 else: esc = s[end + 1:end + 5] next_end = end + 5 msg = "Invalid \\uXXXX escape" try: if len(esc) != 4: raise ValueError uni = int(esc, 16) if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: msg = "Invalid \\uXXXX\\uXXXX surrogate pair" if not s[end + 5:end + 7] == '\\u': raise ValueError esc2 = s[end + 7:end + 11] if len(esc2) != 4: raise ValueError uni2 = int(esc2, 16) uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) next_end += 6 m = unichr(uni) except ValueError: raise ValueError(errmsg(msg, s, end)) end = next_end _append(m) return u''.join(chunks), end # Use speedup if _speedups is not None: scanstring = _speedups.scanstring def JSONString(match, context): encoding = getattr(context, 'encoding', None) strict = getattr(context, 'strict', True) return scanstring(match.string, match.end(), encoding, strict) pattern(r'"')(JSONString) WHITESPACE = re.compile(r'\s*', FLAGS) def JSONObject(match, context, _w=WHITESPACE.match): pairs = {} s = match.string end = _w(s, match.end()).end() nextchar = s[end:end + 1] # trivial empty object if nextchar == '}': return pairs, end + 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end)) end += 1 encoding = getattr(context, 'encoding', None) strict = getattr(context, 'strict', True) iterscan = JSONScanner.iterscan while True: key, end = scanstring(s, end, encoding, strict) end = _w(s, end).end() if s[end:end + 1] != ':': raise ValueError(errmsg("Expecting : delimiter", s, end)) end = _w(s, end + 1).end() try: value, end = iterscan(s, idx=end, context=context).next() except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs[key] = value end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar == '}': break if nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end - 1)) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end - 1)) object_hook = getattr(context, 'object_hook', None) if object_hook is not None: pairs = object_hook(pairs) return pairs, end pattern(r'{')(JSONObject) def JSONArray(match, context, _w=WHITESPACE.match): values = [] s = match.string end = _w(s, match.end()).end() # look-ahead for trivial empty array nextchar = s[end:end + 1] if nextchar == ']': return values, end + 1 iterscan = JSONScanner.iterscan while True: try: value, end = iterscan(s, idx=end, context=context).next() except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) values.append(value) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break if nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end)) end = _w(s, end).end() return values, end pattern(r'\[')(JSONArray) ANYTHING = [ JSONObject, JSONArray, JSONString, JSONConstant, JSONNumber, ] JSONScanner = Scanner(ANYTHING) class JSONDecoder(object): """ Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ _scanner = Scanner(ANYTHING) __all__ = ['__init__', 'decode', 'raw_decode'] def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True): """ ``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. """ self.encoding = encoding self.object_hook = object_hook self.parse_float = parse_float self.parse_int = parse_int self.parse_constant = parse_constant self.strict = strict def decode(self, s, _w=WHITESPACE.match): """ Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj def raw_decode(self, s, **kw): """ Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ kw.setdefault('context', self) try: obj, end = self._scanner.iterscan(s, **kw).next() except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end __all__ = ['JSONDecoder']
Python
r""" A simple, fast, extensible JSON encoder and decoder JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. simplejson exposes an API familiar to uses of the standard library marshal and pickle modules. Encoding basic Python object hierarchies:: >>> import simplejson >>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print simplejson.dumps("\"foo\bar") "\"foo\bar" >>> print simplejson.dumps(u'\u1234') "\u1234" >>> print simplejson.dumps('\\') "\\" >>> print simplejson.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> simplejson.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson >>> simplejson.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson >>> print simplejson.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson >>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> simplejson.loads('"\\"foo\\bar"') u'"foo\x08ar' >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> simplejson.load(io) [u'streaming API'] Specializing JSON object decoding:: >>> import simplejson >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> import decimal >>> simplejson.loads('1.1', parse_float=decimal.Decimal) decimal.Decimal(1.1) Extending JSONEncoder:: >>> import simplejson >>> class ComplexEncoder(simplejson.JSONEncoder): ... def default(self, obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... return simplejson.JSONEncoder.default(self, obj) ... >>> dumps(2 + 1j, cls=ComplexEncoder) '[2.0, 1.0]' >>> ComplexEncoder().encode(2 + 1j) '[2.0, 1.0]' >>> list(ComplexEncoder().iterencode(2 + 1j)) ['[', '2.0', ', ', '1.0', ']'] Using simplejson from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson Expecting property name: line 1 column 2 (char 2) Note that the JSON produced by this module's default settings is a subset of YAML, so it may be used as a serializer for that as well. """ __version__ = '1.8.2' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONEncoder', ] if __name__ == '__main__': from simplejson.decoder import JSONDecoder from simplejson.encoder import JSONEncoder else: from decoder import JSONDecoder from encoder import JSONEncoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """ Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """ Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """ Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. If the contents of ``fp`` is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` object and passed to ``loads()`` ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """ Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(encoding=encoding, **kw).decode(s) # # Compatibility cruft from other libraries # def decode(s): """ demjson, python-cjson API compatibility hook. Use loads(s) instead. """ import warnings warnings.warn("simplejson.loads(s) should be used instead of decode(s)", DeprecationWarning) return loads(s) def encode(obj): """ demjson, python-cjson compatibility hook. Use dumps(s) instead. """ import warnings warnings.warn("simplejson.dumps(s) should be used instead of encode(s)", DeprecationWarning) return dumps(obj) def read(s): """ jsonlib, JsonUtils, python-json, json-py API compatibility hook. Use loads(s) instead. """ import warnings warnings.warn("simplejson.loads(s) should be used instead of read(s)", DeprecationWarning) return loads(s) def write(obj): """ jsonlib, JsonUtils, python-json, json-py API compatibility hook. Use dumps(s) instead. """ import warnings warnings.warn("simplejson.dumps(s) should be used instead of write(s)", DeprecationWarning) return dumps(obj) # # Pretty printer: # curl http://mochikit.com/examples/ajax_tables/domains.json | python -msimplejson # def main(): import sys if len(sys.argv) == 1: infile = sys.stdin outfile = sys.stdout elif len(sys.argv) == 2: infile = open(sys.argv[1], 'rb') outfile = sys.stdout elif len(sys.argv) == 3: infile = open(sys.argv[1], 'rb') outfile = open(sys.argv[2], 'wb') else: raise SystemExit("%s [infile [outfile]]" % (sys.argv[0],)) try: obj = load(infile) except ValueError, e: raise SystemExit(e) dump(obj, outfile, sort_keys=True, indent=4) outfile.write('\n') if __name__ == '__main__': main()
Python
""" Iterator based sre token scanner """ import sre_parse, sre_compile, sre_constants from sre_constants import BRANCH, SUBPATTERN from re import VERBOSE, MULTILINE, DOTALL import re __all__ = ['Scanner', 'pattern'] FLAGS = (VERBOSE | MULTILINE | DOTALL) class Scanner(object): def __init__(self, lexicon, flags=FLAGS): self.actions = [None] # combine phrases into a compound pattern s = sre_parse.Pattern() s.flags = flags p = [] for idx, token in enumerate(lexicon): phrase = token.pattern try: subpattern = sre_parse.SubPattern(s, [(SUBPATTERN, (idx + 1, sre_parse.parse(phrase, flags)))]) except sre_constants.error: raise p.append(subpattern) self.actions.append(token) s.groups = len(p)+1 # NOTE(guido): Added to make SRE validation work p = sre_parse.SubPattern(s, [(BRANCH, (None, p))]) self.scanner = sre_compile.compile(p) def iterscan(self, string, idx=0, context=None): """ Yield match, end_idx for each match """ match = self.scanner.scanner(string, idx).match actions = self.actions lastend = idx end = len(string) while True: m = match() if m is None: break matchbegin, matchend = m.span() if lastend == matchend: break action = actions[m.lastindex] if action is not None: rval, next_pos = action(m, context) if next_pos is not None and next_pos != matchend: # "fast forward" the scanner matchend = next_pos match = self.scanner.scanner(string, matchend).match yield rval, matchend lastend = matchend def pattern(pattern, flags=FLAGS): def decorator(fn): fn.pattern = pattern fn.regex = re.compile(pattern, flags) return fn return decorator
Python
#!/usr/bin/env python import struct from StringIO import StringIO from google.appengine.api import images def resize(image, maxwidth, maxheight): imageinfo = getimageinfo(image) width = float(imageinfo[1]) height = float(imageinfo[2]) ratio = width / height dwidth = maxheight * ratio dheight = maxheight if dwidth > maxwidth: dwidth = maxwidth dheight = maxwidth / ratio return images.resize(image, int(dwidth), int(dheight)) def getimageinfo(data): data = str(data) size = len(data) height = -1 width = -1 content_type = '' # handle GIFs if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'): # Check to see if content_type is correct content_type = 'image/gif' w, h = struct.unpack("<HH", data[6:10]) width = int(w) height = int(h) # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/) # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR' # and finally the 4-byte width, height elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n') and (data[12:16] == 'IHDR')): content_type = 'image/png' w, h = struct.unpack(">LL", data[16:24]) width = int(w) height = int(h) # Maybe this is for an older PNG version. elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'): # Check to see if we have the right content type content_type = 'image/png' w, h = struct.unpack(">LL", data[8:16]) width = int(w) height = int(h) # handle JPEGs elif (size >= 2) and data.startswith('\377\330'): content_type = 'image/jpeg' jpeg = StringIO(data) jpeg.read(2) b = jpeg.read(1) try: while (b and ord(b) != 0xDA): while (ord(b) != 0xFF): b = jpeg.read while (ord(b) == 0xFF): b = jpeg.read(1) if (ord(b) >= 0xC0 and ord(b) <= 0xC3): jpeg.read(3) h, w = struct.unpack(">HH", jpeg.read(4)) break else: jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2) b = jpeg.read(1) width = int(w) height = int(h) except struct.error: pass except ValueError: pass return content_type, width, height
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import wsgiref.handlers import os from handlers import * from google.appengine.ext import webapp from google.appengine.ext.webapp import template class NotAvailable(webapp.RequestHandler): def get(self): self.response.clear() self.response.set_status(501) self.response.headers['Content-Type'] = 'text/html;charset=UTF-8' self.response.headers['Pragma'] = 'no-cache' self.response.headers['Cache-Control'] = 'no-cache' self.response.headers['Expires'] = 'Sat, 1 Jan 2011 00:00:00 GMT' self.response.out.write(template.render('static/sorry.html', {})) def main(): application = webapp.WSGIApplication( [('/.*', NotAvailable)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import wsgiref.handlers from handlers import * from handlers import Updater #Updater.update() # TODO updater must be mooved from here app = webapp.WSGIApplication( [('/', MainPage), # Module articles ('/module/article.list', ArticleList), ('/module/article.edit', ArticleEdit), ('/module/article.favourite', ArticleFavourite), ('/module/article.vote', ArticleVote), ('/module/article.tts/.*', ArticleTTS), ('/module/article/.*', ArticleView), ('/module/article.comment.subscribe',ArticleCommentSubscribe), ('/module/article.comment', ArticleComment), ('/module/article.delete', ArticleDelete), ('/module/article.comment.delete', ArticleCommentDelete), ('/module/article.add.communities', ArticleAddCommunities), ('/module/article.comment.edit', ArticleCommentEdit), ('/module/article.visit', ArticleVisit), # Module users ('/module/user.list', UserList), ('/module/user/.*', UserView), ('/module/user.edit', UserEdit), ('/module/user.register', UserRegister), ('/module/user.login', UserLogin), ('/module/user.logout', UserLogout), ('/module/user.changepassword', UserChangePassword), ('/module/user.forgotpassword', UserForgotPassword), ('/module/user.resetpassword', UserResetPassword), ('/module/user.drafts', UserDrafts), ('/module/user.articles/.*', UserArticles), ('/module/user.communities/.*', UserCommunities), ('/module/user.favourites/.*', UserFavourites), ('/module/user.contacts/.*', UserContacts), ('/module/user.contact', UserContact), ('/module/user.promote', UserPromote), ('/module/user.events', UserEvents), ('/module/user.forums/.*', UserForums), # Module Community ('/module/community.list', CommunityList), ('/module/community.edit', CommunityEdit), ('/module/community.move', CommunityMove), ('/module/community.delete', CommunityDelete), ('/module/community/.*', CommunityView), # Community forums ('/module/community.forum.list/.*', CommunityForumList), ('/module/community.forum.edit', CommunityForumEdit), ('/module/community.forum/.*', CommunityForumView), ('/module/community.forum.reply', CommunityForumReply), ('/module/community.forum.subscribe',CommunityForumSubscribe), ('/module/community.forum.delete', CommunityForumDelete), ('/module/community.thread.edit', CommunityThreadEdit), ('/module/community.forum.move', CommunityForumMove), ('/module/community.forum.visit', CommunityForumVisit), # Community articles ('/module/community.article.list/.*',CommunityArticleList), ('/module/community.article.add', CommunityNewArticle), ('/module/community.article.delete', CommunityArticleDelete), # Community users ('/module/community.user.list/.*', CommunityUserList), ('/module/community.user.unjoin', CommunityUserUnjoin), ('/module/community.user.join', CommunityUserJoin), # messages ('/message.edit', MessageEdit), ('/message.sent', MessageSent), ('/message.inbox', MessageInbox), ('/message.read/.*', MessageRead), ('/message.delete', MessageDelete), # forums, ('/forum.list', ForumList), # inviting contacts ('/invite', Invite), # rss ('/feed/.*', Feed), ('/module/mblog.edit', MBlogEdit), ('/module/mblog/mblog.list', Dispatcher), ('/tag/.*', Tag), ('/search', Search), ('/search.result', SearchResult), # images ('/images/upload', ImageUploader), ('/images/browse', ImageBrowser), ('/images/.*', ImageDisplayer), # module admin ('/admin', Admin), ('/module/admin.application', AdminApplication), ('/module/admin.categories', AdminCategories), ('/module/admin.category.edit', AdminCategoryEdit), ('/module/admin.users', AdminUsers), ('/module/admin.lookandfeel', AdminLookAndFeel), ('/module/admin.modules', AdminModules), ('/module/admin.mail', AdminMail), ('/module/admin.google', AdminGoogle), ('/module/admin.stats', AdminStats), ('/module/admin.cache', AdminCache), ('/module/admin.community.add.related', AdminCommunityAddRelated), # Ohters ('/mail.queue', MailQueue), ('/task.queue', TaskQueue), #General ('/about', Dispatcher), #('/initialization', Initialization), ('/html/.*', Static), ('/.*', NotFound)], debug=True)
Python
import urllib from google.appengine.api import urlfetch """ Adapted from http://pypi.python.org/pypi/recaptcha-client to use with Google App Engine by Joscha Feth <joscha@feth.com> Version 0.1 """ API_SSL_SERVER ="https://api-secure.recaptcha.net" API_SERVER ="http://api.recaptcha.net" VERIFY_SERVER ="api-verify.recaptcha.net" class RecaptchaResponse(object): def __init__(self, is_valid, error_code=None): self.is_valid = is_valid self.error_code = error_code def displayhtml (public_key, use_ssl = False, error = None): """Gets the HTML to display for reCAPTCHA public_key -- The public api key use_ssl -- Should the request be sent over ssl? error -- An error message to display (from RecaptchaResponse.error_code)""" error_param = '' if error: error_param = '&error=%s' % error if use_ssl: server = API_SSL_SERVER else: server = API_SERVER return """<script type="text/javascript" src="%(ApiServer)s/challenge?k=%(PublicKey)s%(ErrorParam)s"></script> <noscript> <iframe src="%(ApiServer)s/noscript?k=%(PublicKey)s%(ErrorParam)s" height="300" width="500" frameborder="0"></iframe><br /> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type='hidden' name='recaptcha_response_field' value='manual_challenge' /> </noscript> """ % { 'ApiServer' : server, 'PublicKey' : public_key, 'ErrorParam' : error_param, } def submit (recaptcha_challenge_field, recaptcha_response_field, private_key, remoteip): """ Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form recaptcha_response_field -- The value of recaptcha_response_field from the form private_key -- your reCAPTCHA private key remoteip -- the user's ip address """ if not (recaptcha_response_field and recaptcha_challenge_field and len (recaptcha_response_field) and len (recaptcha_challenge_field)): return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol') headers = { 'Content-type': 'application/x-www-form-urlencoded', "User-agent" : "reCAPTCHA GAE Python" } params = urllib.urlencode ({ 'privatekey': private_key, 'remoteip' : remoteip, 'challenge': recaptcha_challenge_field, 'response' : recaptcha_response_field, }) httpresp = urlfetch.fetch( url = "http://%s/verify" % VERIFY_SERVER, payload = params, method = urlfetch.POST, headers = headers ) if httpresp.status_code == 200: # response was fine # get the return values return_values = httpresp.content.splitlines(); # get the return code (true/false) return_code = return_values[0] if return_code == "true": # yep, filled perfectly return RecaptchaResponse (is_valid=True) else: # nope, something went wrong return RecaptchaResponse (is_valid=False, error_code = return_values [1]) else: # recaptcha server was not reachable return RecaptchaResponse (is_valid=False, error_code = "recaptcha-not-reachable")
Python
#!/usr/bin/env python version = "1.7" version_info = (1,7,0,"rc-2") __revision__ = "$Rev: 72 $" """ Python-Markdown =============== Converts Markdown to HTML. Basic usage as a module: import markdown md = Markdown() html = md.convert(your_text_string) See http://www.freewisdom.org/projects/python-markdown/ for more information and instructions on how to extend the functionality of the script. (You might want to read that before you try modifying this file.) Started by [Manfred Stienstra](http://www.dwerg.net/). Continued and maintained by [Yuri Takhteyev](http://www.freewisdom.org) and [Waylan Limberg](http://achinghead.com/). Contact: yuri [at] freewisdom.org waylan [at] gmail.com License: GPL 2 (http://www.gnu.org/copyleft/gpl.html) or BSD """ import re, sys, codecs from logging import getLogger, StreamHandler, Formatter, \ DEBUG, INFO, WARN, ERROR, CRITICAL MESSAGE_THRESHOLD = CRITICAL # Configure debug message logger (the hard way - to support python 2.3) logger = getLogger('MARKDOWN') logger.setLevel(DEBUG) # This is restricted by handlers later console_hndlr = StreamHandler() formatter = Formatter('%(name)s-%(levelname)s: "%(message)s"') console_hndlr.setFormatter(formatter) console_hndlr.setLevel(MESSAGE_THRESHOLD) logger.addHandler(console_hndlr) def message(level, text): ''' A wrapper method for logging debug messages. ''' # logger.log(level, text) foo = '' # --------------- CONSTANTS YOU MIGHT WANT TO MODIFY ----------------- TAB_LENGTH = 4 # expand tabs to this many spaces ENABLE_ATTRIBUTES = True # @id = xyz -> <... id="xyz"> SMART_EMPHASIS = 1 # this_or_that does not become this<i>or</i>that HTML_REMOVED_TEXT = "[HTML_REMOVED]" # text used instead of HTML in safe mode RTL_BIDI_RANGES = ( (u'\u0590', u'\u07FF'), # from Hebrew to Nko (includes Arabic, Syriac and Thaana) (u'\u2D30', u'\u2D7F'), # Tifinagh ) # Unicode Reference Table: # 0590-05FF - Hebrew # 0600-06FF - Arabic # 0700-074F - Syriac # 0750-077F - Arabic Supplement # 0780-07BF - Thaana # 07C0-07FF - Nko BOMS = { 'utf-8': (codecs.BOM_UTF8, ), 'utf-16': (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE), #'utf-32': (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE) } def removeBOM(text, encoding): convert = isinstance(text, unicode) for bom in BOMS[encoding]: bom = convert and bom.decode(encoding) or bom if text.startswith(bom): return text.lstrip(bom) return text # The following constant specifies the name used in the usage # statement displayed for python versions lower than 2.3. (With # python2.3 and higher the usage statement is generated by optparse # and uses the actual name of the executable called.) EXECUTABLE_NAME_FOR_USAGE = "python markdown.py" # --------------- CONSTANTS YOU _SHOULD NOT_ HAVE TO CHANGE ---------- # a template for html placeholders HTML_PLACEHOLDER_PREFIX = "qaodmasdkwaspemas" HTML_PLACEHOLDER = HTML_PLACEHOLDER_PREFIX + "%dajkqlsmdqpakldnzsdfls" BLOCK_LEVEL_ELEMENTS = ['p', 'div', 'blockquote', 'pre', 'table', 'dl', 'ol', 'ul', 'script', 'noscript', 'form', 'fieldset', 'iframe', 'math', 'ins', 'del', 'hr', 'hr/', 'style'] def isBlockLevel (tag): return ( (tag in BLOCK_LEVEL_ELEMENTS) or (tag[0] == 'h' and tag[1] in "0123456789") ) """ ====================================================================== ========================== NANODOM =================================== ====================================================================== The three classes below implement some of the most basic DOM methods. I use this instead of minidom because I need a simpler functionality and do not want to require additional libraries. Importantly, NanoDom does not do normalization, which is what we want. It also adds extra white space when converting DOM to string """ ENTITY_NORMALIZATION_EXPRESSIONS = [ (re.compile("&"), "&amp;"), (re.compile("<"), "&lt;"), (re.compile(">"), "&gt;")] ENTITY_NORMALIZATION_EXPRESSIONS_SOFT = [ (re.compile("&(?!\#)"), "&amp;"), (re.compile("<"), "&lt;"), (re.compile(">"), "&gt;"), (re.compile("\""), "&quot;")] def getBidiType(text): if not text: return None ch = text[0] if not isinstance(ch, unicode) or not ch.isalpha(): return None else: for min, max in RTL_BIDI_RANGES: if ( ch >= min and ch <= max ): return "rtl" else: return "ltr" class Document: def __init__ (self): self.bidi = "ltr" def appendChild(self, child): self.documentElement = child child.isDocumentElement = True child.parent = self self.entities = {} def setBidi(self, bidi): if bidi: self.bidi = bidi def createElement(self, tag, textNode=None): el = Element(tag) el.doc = self if textNode: el.appendChild(self.createTextNode(textNode)) return el def createTextNode(self, text): node = TextNode(text) node.doc = self return node def createEntityReference(self, entity): if entity not in self.entities: self.entities[entity] = EntityReference(entity) return self.entities[entity] def createCDATA(self, text): node = CDATA(text) node.doc = self return node def toxml (self): return self.documentElement.toxml() def normalizeEntities(self, text, avoidDoubleNormalizing=False): if avoidDoubleNormalizing: regexps = ENTITY_NORMALIZATION_EXPRESSIONS_SOFT else: regexps = ENTITY_NORMALIZATION_EXPRESSIONS for regexp, substitution in regexps: text = regexp.sub(substitution, text) return text def find(self, test): return self.documentElement.find(test) def unlink(self): self.documentElement.unlink() self.documentElement = None class CDATA: type = "cdata" def __init__ (self, text): self.text = text def handleAttributes(self): pass def toxml (self): return "<![CDATA[" + self.text + "]]>" class Element: type = "element" def __init__ (self, tag): self.nodeName = tag self.attributes = [] self.attribute_values = {} self.childNodes = [] self.bidi = None self.isDocumentElement = False def setBidi(self, bidi): if bidi: orig_bidi = self.bidi if not self.bidi or self.isDocumentElement: # Once the bidi is set don't change it (except for doc element) self.bidi = bidi self.parent.setBidi(bidi) def unlink(self): for child in self.childNodes: if child.type == "element": child.unlink() self.childNodes = None def setAttribute(self, attr, value): if not attr in self.attributes: self.attributes.append(attr) self.attribute_values[attr] = value def insertChild(self, position, child): self.childNodes.insert(position, child) child.parent = self def removeChild(self, child): self.childNodes.remove(child) def replaceChild(self, oldChild, newChild): position = self.childNodes.index(oldChild) self.removeChild(oldChild) self.insertChild(position, newChild) def appendChild(self, child): self.childNodes.append(child) child.parent = self def handleAttributes(self): pass def find(self, test, depth=0): """ Returns a list of descendants that pass the test function """ matched_nodes = [] for child in self.childNodes: if test(child): matched_nodes.append(child) if child.type == "element": matched_nodes += child.find(test, depth+1) return matched_nodes def toxml(self): if ENABLE_ATTRIBUTES: for child in self.childNodes: child.handleAttributes() buffer = "" if self.nodeName in ['h1', 'h2', 'h3', 'h4']: buffer += "\n" elif self.nodeName in ['li']: buffer += "\n " # Process children FIRST, then do the attributes childBuffer = "" if self.childNodes or self.nodeName in ['blockquote']: childBuffer += ">" for child in self.childNodes: childBuffer += child.toxml() if self.nodeName == 'p': childBuffer += "\n" elif self.nodeName == 'li': childBuffer += "\n " childBuffer += "</%s>" % self.nodeName else: childBuffer += "/>" buffer += "<" + self.nodeName if self.nodeName in ['p', 'li', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']: if not self.attribute_values.has_key("dir"): if self.bidi: bidi = self.bidi else: bidi = self.doc.bidi if bidi=="rtl": self.setAttribute("dir", "rtl") for attr in self.attributes: value = self.attribute_values[attr] value = self.doc.normalizeEntities(value, avoidDoubleNormalizing=True) buffer += ' %s="%s"' % (attr, value) # Now let's actually append the children buffer += childBuffer if self.nodeName in ['p', 'br ', 'li', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4'] : buffer += "\n" return buffer class TextNode: type = "text" attrRegExp = re.compile(r'\{@([^\}]*)=([^\}]*)}') # {@id=123} def __init__ (self, text): self.value = text def attributeCallback(self, match): self.parent.setAttribute(match.community(1), match.community(2)) def handleAttributes(self): self.value = self.attrRegExp.sub(self.attributeCallback, self.value) def toxml(self): text = self.value self.parent.setBidi(getBidiType(text)) if not text.startswith(HTML_PLACEHOLDER_PREFIX): if self.parent.nodeName == "p": text = text.replace("\n", "\n ") elif (self.parent.nodeName == "li" and self.parent.childNodes[0]==self): text = "\n " + text.replace("\n", "\n ") text = self.doc.normalizeEntities(text) return text class EntityReference: type = "entity_ref" def __init__(self, entity): self.entity = entity def handleAttributes(self): pass def toxml(self): return "&" + self.entity + ";" """ ====================================================================== ========================== PRE-PROCESSORS ============================ ====================================================================== Preprocessors munge source text before we start doing anything too complicated. There are two types of preprocessors: TextPreprocessor and Preprocessor. """ class TextPreprocessor: ''' TextPreprocessors are run before the text is broken into lines. Each TextPreprocessor implements a "run" method that takes a pointer to a text string of the document, modifies it as necessary and returns either the same pointer or a pointer to a new string. TextPreprocessors must extend markdown.TextPreprocessor. ''' def run(self, text): pass class Preprocessor: ''' Preprocessors are run after the text is broken into lines. Each preprocessor implements a "run" method that takes a pointer to a list of lines of the document, modifies it as necessary and returns either the same pointer or a pointer to a new list. Preprocessors must extend markdown.Preprocessor. ''' def run(self, lines): pass class HtmlBlockPreprocessor(TextPreprocessor): """Removes html blocks from the source text and stores it.""" def _get_left_tag(self, block): return block[1:].replace(">", " ", 1).split()[0].lower() def _get_right_tag(self, left_tag, block): return block.rstrip()[-len(left_tag)-2:-1].lower() def _equal_tags(self, left_tag, right_tag): if left_tag == 'div' or left_tag[0] in ['?', '@', '%']: # handle PHP, etc. return True if ("/" + left_tag) == right_tag: return True if (right_tag == "--" and left_tag == "--"): return True elif left_tag == right_tag[1:] \ and right_tag[0] != "<": return True else: return False def _is_oneliner(self, tag): return (tag in ['hr', 'hr/']) def run(self, text): new_blocks = [] text = text.split("\n\n") articles = [] left_tag = '' right_tag = '' in_tag = False # flag for block in text: if block.startswith("\n"): block = block[1:] if not in_tag: if block.startswith("<"): left_tag = self._get_left_tag(block) right_tag = self._get_right_tag(left_tag, block) if not (isBlockLevel(left_tag) \ or block[1] in ["!", "?", "@", "%"]): new_blocks.append(block) continue if self._is_oneliner(left_tag): new_blocks.append(block.strip()) continue if block[1] == "!": # is a comment block left_tag = "--" right_tag = self._get_right_tag(left_tag, block) # keep checking conditions below and maybe just append if block.rstrip().endswith(">") \ and self._equal_tags(left_tag, right_tag): new_blocks.append( self.stash.store(block.strip())) continue else: #if not block[1] == "!": # if is block level tag and is not complete articles.append(block.strip()) in_tag = True continue new_blocks.append(block) else: articles.append(block.strip()) right_tag = self._get_right_tag(left_tag, block) if self._equal_tags(left_tag, right_tag): # if find closing tag in_tag = False new_blocks.append( self.stash.store('\n\n'.join(articles))) articles = [] if articles: new_blocks.append(self.stash.store('\n\n'.join(articles))) new_blocks.append('\n') return "\n\n".join(new_blocks) HTML_BLOCK_PREPROCESSOR = HtmlBlockPreprocessor() class HeaderPreprocessor(Preprocessor): """ Replaces underlined headers with hashed headers to avoid the nead for lookahead later. """ def run (self, lines): i = -1 while i+1 < len(lines): i = i+1 if not lines[i].strip(): continue if lines[i].startswith("#"): lines.insert(i+1, "\n") if (i+1 <= len(lines) and lines[i+1] and lines[i+1][0] in ['-', '=']): underline = lines[i+1].strip() if underline == "="*len(underline): lines[i] = "# " + lines[i].strip() lines[i+1] = "" elif underline == "-"*len(underline): lines[i] = "## " + lines[i].strip() lines[i+1] = "" return lines HEADER_PREPROCESSOR = HeaderPreprocessor() class LinePreprocessor(Preprocessor): """Deals with HR lines (needs to be done before processing lists)""" blockquote_re = re.compile(r'^(> )+') def run (self, lines): for i in range(len(lines)): prefix = '' m = self.blockquote_re.search(lines[i]) if m : prefix = m.community(0) if self._isLine(lines[i][len(prefix):]): lines[i] = prefix + self.stash.store("<hr />", safe=True) return lines def _isLine(self, block): """Determines if a block should be replaced with an <HR>""" if block.startswith(" "): return 0 # a code block text = "".join([x for x in block if not x.isspace()]) if len(text) <= 2: return 0 for pattern in ['isline1', 'isline2', 'isline3']: m = RE.regExp[pattern].match(text) if (m and m.community(1)): return 1 else: return 0 LINE_PREPROCESSOR = LinePreprocessor() class ReferencePreprocessor(Preprocessor): ''' Removes reference definitions from the text and stores them for later use. ''' def run (self, lines): new_text = []; for line in lines: m = RE.regExp['reference-def'].match(line) if m: id = m.community(2).strip().lower() t = m.community(4).strip() # potential title if not t: self.references[id] = (m.community(3), t) elif (len(t) >= 2 and (t[0] == t[-1] == "\"" or t[0] == t[-1] == "\'" or (t[0] == "(" and t[-1] == ")") ) ): self.references[id] = (m.community(3), t[1:-1]) else: new_text.append(line) else: new_text.append(line) return new_text #+ "\n" REFERENCE_PREPROCESSOR = ReferencePreprocessor() """ ====================================================================== ========================== INLINE PATTERNS =========================== ====================================================================== Inline patterns such as *emphasis* are handled by means of auxiliary objects, one per pattern. Pattern objects must be instances of classes that extend markdown.Pattern. Each pattern object uses a single regular expression and needs support the following methods: pattern.getCompiledRegExp() - returns a regular expression pattern.handleMatch(m, doc) - takes a match object and returns a NanoDom node (as a part of the provided doc) or None All of python markdown's built-in patterns subclass from Patter, but you can add additional patterns that don't. Also note that all the regular expressions used by inline must capture the whole block. For this reason, they all start with '^(.*)' and end with '(.*)!'. In case with built-in expression Pattern takes care of adding the "^(.*)" and "(.*)!". Finally, the order in which regular expressions are applied is very important - e.g. if we first replace http://.../ links with <a> tags and _then_ try to replace inline html, we would end up with a mess. So, we apply the expressions in the following order: * escape and backticks have to go before everything else, so that we can preempt any markdown patterns by escaping them. * then we handle auto-links (must be done before inline html) * then we handle inline HTML. At this point we will simply replace all inline HTML strings with a placeholder and add the actual HTML to a hash. * then inline images (must be done before links) * then bracketed links, first regular then reference-style * finally we apply strong and emphasis """ NOBRACKET = r'[^\]\[]*' BRK = ( r'\[(' + (NOBRACKET + r'(\[')*6 + (NOBRACKET+ r'\])*')*6 + NOBRACKET + r')\]' ) NOIMG = r'(?<!\!)' BACKTICK_RE = r'\`([^\`]*)\`' # `e= m*c^2` DOUBLE_BACKTICK_RE = r'\`\`(.*)\`\`' # ``e=f("`")`` ESCAPE_RE = r'\\(.)' # \< EMPHASIS_RE = r'\*([^\*]*)\*' # *emphasis* STRONG_RE = r'\*\*(.*)\*\*' # **strong** STRONG_EM_RE = r'\*\*\*([^_]*)\*\*\*' # ***strong*** if SMART_EMPHASIS: EMPHASIS_2_RE = r'(?<!\S)_(\S[^_]*)_' # _emphasis_ else: EMPHASIS_2_RE = r'_([^_]*)_' # _emphasis_ STRONG_2_RE = r'__([^_]*)__' # __strong__ STRONG_EM_2_RE = r'___([^_]*)___' # ___strong___ LINK_RE = NOIMG + BRK + r'\s*\(([^\)]*)\)' # [text](url) LINK_ANGLED_RE = NOIMG + BRK + r'\s*\(<([^\)]*)>\)' # [text](<url>) IMAGE_LINK_RE = r'\!' + BRK + r'\s*\(([^\)]*)\)' # ![alttxt](http://x.com/) REFERENCE_RE = NOIMG + BRK+ r'\s*\[([^\]]*)\]' # [Google][3] IMAGE_REFERENCE_RE = r'\!' + BRK + '\s*\[([^\]]*)\]' # ![alt text][2] NOT_STRONG_RE = r'( \* )' # stand-alone * or _ AUTOLINK_RE = r'<(http://[^>]*)>' # <http://www.123.com> AUTOMAIL_RE = r'<([^> \!]*@[^> ]*)>' # <me@example.com> #HTML_RE = r'(\<[^\>]*\>)' # <...> HTML_RE = r'(\<[a-zA-Z/][^\>]*\>)' # <...> ENTITY_RE = r'(&[\#a-zA-Z0-9]*;)' # &amp; LINE_BREAK_RE = r' \n' # two spaces at end of line LINE_BREAK_2_RE = r' $' # two spaces at end of text class Pattern: def __init__ (self, pattern): self.pattern = pattern self.compiled_re = re.compile("^(.*)%s(.*)$" % pattern, re.DOTALL) def getCompiledRegExp (self): return self.compiled_re BasePattern = Pattern # for backward compatibility class SimpleTextPattern (Pattern): def handleMatch(self, m, doc): return doc.createTextNode(m.community(2)) class SimpleTagPattern (Pattern): def __init__ (self, pattern, tag): Pattern.__init__(self, pattern) self.tag = tag def handleMatch(self, m, doc): el = doc.createElement(self.tag) el.appendChild(doc.createTextNode(m.community(2))) return el class SubstituteTagPattern (SimpleTagPattern): def handleMatch (self, m, doc): return doc.createElement(self.tag) class BacktickPattern (Pattern): def __init__ (self, pattern): Pattern.__init__(self, pattern) self.tag = "code" def handleMatch(self, m, doc): el = doc.createElement(self.tag) text = m.community(2).strip() #text = text.replace("&", "&amp;") el.appendChild(doc.createTextNode(text)) return el class DoubleTagPattern (SimpleTagPattern): def handleMatch(self, m, doc): tag1, tag2 = self.tag.split(",") el1 = doc.createElement(tag1) el2 = doc.createElement(tag2) el1.appendChild(el2) el2.appendChild(doc.createTextNode(m.community(2))) return el1 class HtmlPattern (Pattern): def handleMatch (self, m, doc): rawhtml = m.community(2) inline = True place_holder = self.stash.store(rawhtml) return doc.createTextNode(place_holder) class LinkPattern (Pattern): def handleMatch(self, m, doc): el = doc.createElement('a') el.appendChild(doc.createTextNode(m.community(2))) parts = m.community(9).split('"') # We should now have [], [href], or [href, title] if parts: el.setAttribute('href', parts[0].strip()) else: el.setAttribute('href', "") if len(parts) > 1: # we also got a title title = '"' + '"'.join(parts[1:]).strip() title = dequote(title) #.replace('"', "&quot;") el.setAttribute('title', title) return el class ImagePattern (Pattern): def handleMatch(self, m, doc): el = doc.createElement('img') src_parts = m.community(9).split() if src_parts: el.setAttribute('src', src_parts[0]) else: el.setAttribute('src', "") if len(src_parts) > 1: el.setAttribute('title', dequote(" ".join(src_parts[1:]))) if ENABLE_ATTRIBUTES: text = doc.createTextNode(m.community(2)) el.appendChild(text) text.handleAttributes() truealt = text.value el.childNodes.remove(text) else: truealt = m.community(2) el.setAttribute('alt', truealt) return el class ReferencePattern (Pattern): def handleMatch(self, m, doc): if m.community(9): id = m.community(9).lower() else: # if we got something like "[Google][]" # we'll use "google" as the id id = m.community(2).lower() if not self.references.has_key(id): # ignore undefined refs return None href, title = self.references[id] text = m.community(2) return self.makeTag(href, title, text, doc) def makeTag(self, href, title, text, doc): el = doc.createElement('a') el.setAttribute('href', href) if title: el.setAttribute('title', title) el.appendChild(doc.createTextNode(text)) return el class ImageReferencePattern (ReferencePattern): def makeTag(self, href, title, text, doc): el = doc.createElement('img') el.setAttribute('src', href) if title: el.setAttribute('title', title) el.setAttribute('alt', text) return el class AutolinkPattern (Pattern): def handleMatch(self, m, doc): el = doc.createElement('a') el.setAttribute('href', m.community(2)) el.appendChild(doc.createTextNode(m.community(2))) return el class AutomailPattern (Pattern): def handleMatch(self, m, doc): el = doc.createElement('a') email = m.community(2) if email.startswith("mailto:"): email = email[len("mailto:"):] for letter in email: entity = doc.createEntityReference("#%d" % ord(letter)) el.appendChild(entity) mailto = "mailto:" + email mailto = "".join(['&#%d;' % ord(letter) for letter in mailto]) el.setAttribute('href', mailto) return el ESCAPE_PATTERN = SimpleTextPattern(ESCAPE_RE) NOT_STRONG_PATTERN = SimpleTextPattern(NOT_STRONG_RE) BACKTICK_PATTERN = BacktickPattern(BACKTICK_RE) DOUBLE_BACKTICK_PATTERN = BacktickPattern(DOUBLE_BACKTICK_RE) STRONG_PATTERN = SimpleTagPattern(STRONG_RE, 'strong') STRONG_PATTERN_2 = SimpleTagPattern(STRONG_2_RE, 'strong') EMPHASIS_PATTERN = SimpleTagPattern(EMPHASIS_RE, 'em') EMPHASIS_PATTERN_2 = SimpleTagPattern(EMPHASIS_2_RE, 'em') STRONG_EM_PATTERN = DoubleTagPattern(STRONG_EM_RE, 'strong,em') STRONG_EM_PATTERN_2 = DoubleTagPattern(STRONG_EM_2_RE, 'strong,em') LINE_BREAK_PATTERN = SubstituteTagPattern(LINE_BREAK_RE, 'br ') LINE_BREAK_PATTERN_2 = SubstituteTagPattern(LINE_BREAK_2_RE, 'br ') LINK_PATTERN = LinkPattern(LINK_RE) LINK_ANGLED_PATTERN = LinkPattern(LINK_ANGLED_RE) IMAGE_LINK_PATTERN = ImagePattern(IMAGE_LINK_RE) IMAGE_REFERENCE_PATTERN = ImageReferencePattern(IMAGE_REFERENCE_RE) REFERENCE_PATTERN = ReferencePattern(REFERENCE_RE) HTML_PATTERN = HtmlPattern(HTML_RE) ENTITY_PATTERN = HtmlPattern(ENTITY_RE) AUTOLINK_PATTERN = AutolinkPattern(AUTOLINK_RE) AUTOMAIL_PATTERN = AutomailPattern(AUTOMAIL_RE) """ ====================================================================== ========================== POST-PROCESSORS =========================== ====================================================================== Markdown also allows post-processors, which are similar to preprocessors in that they need to implement a "run" method. However, they are run after core processing. There are two types of post-processors: Postprocessor and TextPostprocessor """ class Postprocessor: ''' Postprocessors are run before the dom it converted back into text. Each Postprocessor implements a "run" method that takes a pointer to a NanoDom document, modifies it as necessary and returns a NanoDom document. Postprocessors must extend markdown.Postprocessor. There are currently no standard post-processors, but the footnote extension uses one. ''' def run(self, dom): pass class TextPostprocessor: ''' TextPostprocessors are run after the dom it converted back into text. Each TextPostprocessor implements a "run" method that takes a pointer to a text string, modifies it as necessary and returns a text string. TextPostprocessors must extend markdown.TextPostprocessor. ''' def run(self, text): pass class RawHtmlTextPostprocessor(TextPostprocessor): def __init__(self): pass def run(self, text): for i in range(self.stash.html_counter): html, safe = self.stash.rawHtmlBlocks[i] if self.safeMode and not safe: if str(self.safeMode).lower() == 'escape': html = self.escape(html) elif str(self.safeMode).lower() == 'remove': html = '' else: html = HTML_REMOVED_TEXT text = text.replace("<p>%s\n</p>" % (HTML_PLACEHOLDER % i), html + "\n") text = text.replace(HTML_PLACEHOLDER % i, html) return text def escape(self, html): ''' Basic html escaping ''' html = html.replace('&', '&amp;') html = html.replace('<', '&lt;') html = html.replace('>', '&gt;') return html.replace('"', '&quot;') RAWHTMLTEXTPOSTPROCESSOR = RawHtmlTextPostprocessor() """ ====================================================================== ========================== MISC AUXILIARY CLASSES ==================== ====================================================================== """ class HtmlStash: """This class is used for stashing HTML objects that we extract in the beginning and replace with place-holders.""" def __init__ (self): self.html_counter = 0 # for counting inline html segments self.rawHtmlBlocks=[] def store(self, html, safe=False): """Saves an HTML segment for later reinsertion. Returns a placeholder string that needs to be inserted into the document. @param html: an html segment @param safe: label an html segment as safe for safemode @param inline: label a segmant as inline html @returns : a placeholder string """ self.rawHtmlBlocks.append((html, safe)) placeholder = HTML_PLACEHOLDER % self.html_counter self.html_counter += 1 return placeholder class BlockGuru: def _findHead(self, lines, fn, allowBlank=0): """Functional magic to help determine boundaries of indented blocks. @param lines: an array of strings @param fn: a function that returns a substring of a string if the string matches the necessary criteria @param allowBlank: specifies whether it's ok to have blank lines between matching functions @returns: a list of post processes articles and the unused remainder of the original list""" articles = [] article = -1 i = 0 # to keep track of where we are for line in lines: if not line.strip() and not allowBlank: return articles, lines[i:] if not line.strip() and allowBlank: # If we see a blank line, this _might_ be the end i += 1 # Find the next non-blank line for j in range(i, len(lines)): if lines[j].strip(): next = lines[j] break else: # There is no more text => this is the end break # Check if the next non-blank line is still a part of the list part = fn(next) if part: articles.append("") continue else: break # found end of the list part = fn(line) if part: articles.append(part) i += 1 continue else: return articles, lines[i:] else: i += 1 return articles, lines[i:] def detabbed_fn(self, line): """ An auxiliary method to be passed to _findHead """ m = RE.regExp['tabbed'].match(line) if m: return m.community(4) else: return None def detectTabbed(self, lines): return self._findHead(lines, self.detabbed_fn, allowBlank = 1) def print_error(string): """Print an error string to stderr""" sys.stderr.write(string +'\n') def dequote(string): """ Removes quotes from around a string """ if ( ( string.startswith('"') and string.endswith('"')) or (string.startswith("'") and string.endswith("'")) ): return string[1:-1] else: return string """ ====================================================================== ========================== CORE MARKDOWN ============================= ====================================================================== This stuff is ugly, so if you are thinking of extending the syntax, see first if you can do it via pre-processors, post-processors, inline patterns or a combination of the three. """ class CorePatterns: """This class is scheduled for removal as part of a refactoring effort.""" patterns = { 'header': r'(#*)([^#]*)(#*)', # # A title 'reference-def': r'(\ ?\ ?\ ?)\[([^\]]*)\]:\s*([^ ]*)(.*)', # [Google]: http://www.google.com/ 'containsline': r'([-]*)$|^([=]*)', # -----, =====, etc. 'ol': r'[ ]{0,3}[\d]*\.\s+(.*)', # 1. text 'ul': r'[ ]{0,3}[*+-]\s+(.*)', # "* text" 'isline1': r'(\**)', # *** 'isline2': r'(\-*)', # --- 'isline3': r'(\_*)', # ___ 'tabbed': r'((\t)|( ))(.*)', # an indented line 'quoted': r'> ?(.*)', # a quoted block ("> ...") } def __init__ (self): self.regExp = {} for key in self.patterns.keys(): self.regExp[key] = re.compile("^%s$" % self.patterns[key], re.DOTALL) self.regExp['containsline'] = re.compile(r'^([-]*)$|^([=]*)$', re.M) RE = CorePatterns() class Markdown: """ Markdown formatter class for creating an html document from Markdown text """ def __init__(self, source=None, # depreciated extensions=[], extension_configs=None, safe_mode = False): """Creates a new Markdown instance. @param source: The text in Markdown format. Depreciated! @param extensions: A list if extensions. @param extension-configs: Configuration setting for extensions. @param safe_mode: Disallow raw html. """ self.source = source if source is not None: message(WARN, "The `source` arg of Markdown.__init__() is depreciated and will be removed in the future. Use `instance.convert(source)` instead.") self.safeMode = safe_mode self.blockGuru = BlockGuru() self.registeredExtensions = [] self.stripTopLevelTags = 1 self.docType = "" self.textPreprocessors = [HTML_BLOCK_PREPROCESSOR] self.preprocessors = [HEADER_PREPROCESSOR, LINE_PREPROCESSOR, # A footnote preprocessor will # get inserted here REFERENCE_PREPROCESSOR] self.postprocessors = [] # a footnote postprocessor will get # inserted later self.textPostprocessors = [# a footnote postprocessor will get # inserted here RAWHTMLTEXTPOSTPROCESSOR] self.prePatterns = [] self.inlinePatterns = [DOUBLE_BACKTICK_PATTERN, BACKTICK_PATTERN, ESCAPE_PATTERN, REFERENCE_PATTERN, LINK_ANGLED_PATTERN, LINK_PATTERN, IMAGE_LINK_PATTERN, IMAGE_REFERENCE_PATTERN, AUTOLINK_PATTERN, AUTOMAIL_PATTERN, LINE_BREAK_PATTERN_2, LINE_BREAK_PATTERN, HTML_PATTERN, ENTITY_PATTERN, NOT_STRONG_PATTERN, STRONG_EM_PATTERN, STRONG_EM_PATTERN_2, STRONG_PATTERN, STRONG_PATTERN_2, EMPHASIS_PATTERN, EMPHASIS_PATTERN_2 # The order of the handlers matters!!! ] self.registerExtensions(extensions = extensions, configs = extension_configs) self.reset() def registerExtensions(self, extensions, configs): if not configs: configs = {} for ext in extensions: extension_module_name = "mdx_" + ext try: module = __import__(extension_module_name) except: message(CRITICAL, "couldn't load extension %s (looking for %s module)" % (ext, extension_module_name) ) else: if configs.has_key(ext): configs_for_ext = configs[ext] else: configs_for_ext = [] extension = module.makeExtension(configs_for_ext) extension.extendMarkdown(self, globals()) def registerExtension(self, extension): """ This gets called by the extension """ self.registeredExtensions.append(extension) def reset(self): """Resets all state variables so that we can start with a new text.""" self.references={} self.htmlStash = HtmlStash() HTML_BLOCK_PREPROCESSOR.stash = self.htmlStash LINE_PREPROCESSOR.stash = self.htmlStash REFERENCE_PREPROCESSOR.references = self.references HTML_PATTERN.stash = self.htmlStash ENTITY_PATTERN.stash = self.htmlStash REFERENCE_PATTERN.references = self.references IMAGE_REFERENCE_PATTERN.references = self.references RAWHTMLTEXTPOSTPROCESSOR.stash = self.htmlStash RAWHTMLTEXTPOSTPROCESSOR.safeMode = self.safeMode for extension in self.registeredExtensions: extension.reset() def _transform(self): """Transforms the Markdown text into a XHTML body document @returns: A NanoDom Document """ # Setup the document self.doc = Document() self.top_element = self.doc.createElement("span") self.top_element.appendChild(self.doc.createTextNode('\n')) self.top_element.setAttribute('class', 'markdown') self.doc.appendChild(self.top_element) # Fixup the source text text = self.source text = text.replace("\r\n", "\n").replace("\r", "\n") text += "\n\n" text = text.expandtabs(TAB_LENGTH) # Split into lines and run the preprocessors that will work with # self.lines self.lines = text.split("\n") # Run the pre-processors on the lines for prep in self.preprocessors : self.lines = prep.run(self.lines) # Create a NanoDom tree from the lines and attach it to Document buffer = [] for line in self.lines: if line.startswith("#"): self._processSection(self.top_element, buffer) buffer = [line] else: buffer.append(line) self._processSection(self.top_element, buffer) #self._processSection(self.top_element, self.lines) # Not sure why I put this in but let's leave it for now. self.top_element.appendChild(self.doc.createTextNode('\n')) # Run the post-processors for postprocessor in self.postprocessors: postprocessor.run(self.doc) return self.doc def _processSection(self, parent_elem, lines, inList = 0, looseList = 0): """Process a section of a source document, looking for high level structural elements like lists, block quotes, code segments, html blocks, etc. Some those then get stripped of their high level markup (e.g. get unindented) and the lower-level markup is processed recursively. @param parent_elem: A NanoDom element to which the content will be added @param lines: a list of lines @param inList: a level @returns: None""" # Loop through lines until none left. while lines: # Check if this section starts with a list, a blockquote or # a code block processFn = { 'ul': self._processUList, 'ol': self._processOList, 'quoted': self._processQuote, 'tabbed': self._processCodeBlock} for regexp in ['ul', 'ol', 'quoted', 'tabbed']: m = RE.regExp[regexp].match(lines[0]) if m: processFn[regexp](parent_elem, lines, inList) return # We are NOT looking at one of the high-level structures like # lists or blockquotes. So, it's just a regular paragraph # (though perhaps nested inside a list or something else). If # we are NOT inside a list, we just need to look for a blank # line to find the end of the block. If we ARE inside a # list, however, we need to consider that a sublist does not # need to be separated by a blank line. Rather, the following # markup is legal: # # * The top level list article # # Another paragraph of the list. This is where we are now. # * Underneath we might have a sublist. # if inList: start, lines = self._linesUntil(lines, (lambda line: RE.regExp['ul'].match(line) or RE.regExp['ol'].match(line) or not line.strip())) self._processSection(parent_elem, start, inList - 1, looseList = looseList) inList = inList-1 else: # Ok, so it's just a simple block paragraph, lines = self._linesUntil(lines, lambda line: not line.strip()) if len(paragraph) and paragraph[0].startswith('#'): self._processHeader(parent_elem, paragraph) elif paragraph: self._processParagraph(parent_elem, paragraph, inList, looseList) if lines and not lines[0].strip(): lines = lines[1:] # skip the first (blank) line def _processHeader(self, parent_elem, paragraph): m = RE.regExp['header'].match(paragraph[0]) if m: level = len(m.community(1)) h = self.doc.createElement("h%d" % level) parent_elem.appendChild(h) for article in self._handleInline(m.community(2).strip()): h.appendChild(article) else: message(CRITICAL, "We've got a problem header!") def _processParagraph(self, parent_elem, paragraph, inList, looseList): list = self._handleInline("\n".join(paragraph)) if ( parent_elem.nodeName == 'li' and not (looseList or parent_elem.childNodes)): # If this is the first paragraph inside "li", don't # put <p> around it - append the paragraph bits directly # onto parent_elem el = parent_elem else: # Otherwise make a "p" element el = self.doc.createElement("p") parent_elem.appendChild(el) for article in list: el.appendChild(article) def _processUList(self, parent_elem, lines, inList): self._processList(parent_elem, lines, inList, listexpr='ul', tag = 'ul') def _processOList(self, parent_elem, lines, inList): self._processList(parent_elem, lines, inList, listexpr='ol', tag = 'ol') def _processList(self, parent_elem, lines, inList, listexpr, tag): """Given a list of document lines starting with a list article, finds the end of the list, breaks it up, and recursively processes each list article and the remainder of the text file. @param parent_elem: A dom element to which the content will be added @param lines: a list of lines @param inList: a level @returns: None""" ul = self.doc.createElement(tag) # ul might actually be '<ol>' parent_elem.appendChild(ul) looseList = 0 # Make a list of list articles articles = [] article = -1 i = 0 # a counter to keep track of where we are for line in lines: loose = 0 if not line.strip(): # If we see a blank line, this _might_ be the end of the list i += 1 loose = 1 # Find the next non-blank line for j in range(i, len(lines)): if lines[j].strip(): next = lines[j] break else: # There is no more text => end of the list break # Check if the next non-blank line is still a part of the list if ( RE.regExp['ul'].match(next) or RE.regExp['ol'].match(next) or RE.regExp['tabbed'].match(next) ): # get rid of any white space in the line articles[article].append(line.strip()) looseList = loose or looseList continue else: break # found end of the list # Now we need to detect list articles (at the current level) # while also detabing child elements if necessary for expr in ['ul', 'ol', 'tabbed']: m = RE.regExp[expr].match(line) if m: if expr in ['ul', 'ol']: # We are looking at a new article #if m.community(1) : # Removed the check to allow for a blank line # at the beginning of the list article articles.append([m.community(1)]) article += 1 elif expr == 'tabbed': # This line needs to be detabbed articles[article].append(m.community(4)) #after the 'tab' i += 1 break else: articles[article].append(line) # Just regular continuation i += 1 # added on 2006.02.25 else: i += 1 # Add the dom elements for article in articles: li = self.doc.createElement("li") ul.appendChild(li) self._processSection(li, article, inList + 1, looseList = looseList) # Process the remaining part of the section self._processSection(parent_elem, lines[i:], inList) def _linesUntil(self, lines, condition): """ A utility function to break a list of lines upon the first line that satisfied a condition. The condition argument should be a predicate function. """ i = -1 for line in lines: i += 1 if condition(line): break else: i += 1 return lines[:i], lines[i:] def _processQuote(self, parent_elem, lines, inList): """Given a list of document lines starting with a quote finds the end of the quote, unindents it and recursively processes the body of the quote and the remainder of the text file. @param parent_elem: DOM element to which the content will be added @param lines: a list of lines @param inList: a level @returns: None """ dequoted = [] i = 0 blank_line = False # allow one blank line between paragraphs for line in lines: m = RE.regExp['quoted'].match(line) if m: dequoted.append(m.community(1)) i += 1 blank_line = False elif not blank_line and line.strip() != '': dequoted.append(line) i += 1 elif not blank_line and line.strip() == '': dequoted.append(line) i += 1 blank_line = True else: break blockquote = self.doc.createElement('blockquote') parent_elem.appendChild(blockquote) self._processSection(blockquote, dequoted, inList) self._processSection(parent_elem, lines[i:], inList) def _processCodeBlock(self, parent_elem, lines, inList): """Given a list of document lines starting with a code block finds the end of the block, puts it into the dom verbatim wrapped in ("<pre><code>") and recursively processes the the remainder of the text file. @param parent_elem: DOM element to which the content will be added @param lines: a list of lines @param inList: a level @returns: None""" detabbed, theRest = self.blockGuru.detectTabbed(lines) pre = self.doc.createElement('pre') code = self.doc.createElement('code') parent_elem.appendChild(pre) pre.appendChild(code) text = "\n".join(detabbed).rstrip()+"\n" #text = text.replace("&", "&amp;") code.appendChild(self.doc.createTextNode(text)) self._processSection(parent_elem, theRest, inList) def _handleInline (self, line, patternIndex=0): """Transform a Markdown line with inline elements to an XHTML fragment. This function uses auxiliary objects called inline patterns. See notes on inline patterns above. @param line: A line of Markdown text @param patternIndex: The index of the inlinePattern to start with @return: A list of NanoDom nodes """ parts = [line] while patternIndex < len(self.inlinePatterns): i = 0 while i < len(parts): x = parts[i] if isinstance(x, (str, unicode)): result = self._applyPattern(x, \ self.inlinePatterns[patternIndex], \ patternIndex) if result: i -= 1 parts.remove(x) for y in result: parts.insert(i+1,y) i += 1 patternIndex += 1 for i in range(len(parts)): x = parts[i] if isinstance(x, (str, unicode)): parts[i] = self.doc.createTextNode(x) return parts def _applyPattern(self, line, pattern, patternIndex): """ Given a pattern name, this function checks if the line fits the pattern, creates the necessary elements, and returns back a list consisting of NanoDom elements and/or strings. @param line: the text to be processed @param pattern: the pattern to be checked @returns: the appropriate newly created NanoDom element if the pattern matches, None otherwise. """ # match the line to pattern's pre-compiled reg exp. # if no match, move on. m = pattern.getCompiledRegExp().match(line) if not m: return None # if we got a match let the pattern make us a NanoDom node # if it doesn't, move on node = pattern.handleMatch(m, self.doc) # check if any of this nodes have children that need processing if isinstance(node, Element): if not node.nodeName in ["code", "pre"]: for child in node.childNodes: if isinstance(child, TextNode): result = self._handleInline(child.value, patternIndex+1) if result: if result == [child]: continue result.reverse() #to make insertion easier position = node.childNodes.index(child) node.removeChild(child) for article in result: if isinstance(article, (str, unicode)): if len(article) > 0: node.insertChild(position, self.doc.createTextNode(article)) else: node.insertChild(position, article) if node: # Those are in the reverse order! return ( m.communities()[-1], # the string to the left node, # the new node m.community(1)) # the string to the right of the match else: return None def convert (self, source = None): """Return the document in XHTML format. @returns: A serialized XHTML body.""" if source is not None: #Allow blank string self.source = source if not self.source: return u"" try: self.source = unicode(self.source) except UnicodeDecodeError: message(CRITICAL, 'UnicodeDecodeError: Markdown only accepts unicode or ascii input.') return u"" for pp in self.textPreprocessors: self.source = pp.run(self.source) doc = self._transform() xml = doc.toxml() # Return everything but the top level tag if self.stripTopLevelTags: xml = xml.strip()[23:-7] + "\n" for pp in self.textPostprocessors: xml = pp.run(xml) return (self.docType + xml).strip() def __str__(self): ''' Report info about instance. Markdown always returns unicode. ''' if self.source is None: status = 'in which no source text has been assinged.' else: status = 'which contains %d chars and %d line(s) of source.'%\ (len(self.source), self.source.count('\n')+1) return 'An instance of "%s" %s'% (self.__class__, status) __unicode__ = convert # markdown should always return a unicode string # ==================================================================== def markdownFromFile(input = None, output = None, extensions = [], encoding = None, message_threshold = CRITICAL, safe = False): global console_hndlr console_hndlr.setLevel(message_threshold) message(DEBUG, "input file: %s" % input) if not encoding: encoding = "utf-8" input_file = codecs.open(input, mode="r", encoding=encoding) text = input_file.read() input_file.close() text = removeBOM(text, encoding) new_text = markdown(text, extensions, safe_mode = safe) if output: output_file = codecs.open(output, "w", encoding=encoding) output_file.write(new_text) output_file.close() else: sys.stdout.write(new_text.encode(encoding)) def markdown(text, extensions = [], safe_mode = False): message(DEBUG, "in markdown.markdown(), received text:\n%s" % text) extension_names = [] extension_configs = {} for ext in extensions: pos = ext.find("(") if pos == -1: extension_names.append(ext) else: name = ext[:pos] extension_names.append(name) pairs = [x.split("=") for x in ext[pos+1:-1].split(",")] configs = [(x.strip(), y.strip()) for (x, y) in pairs] extension_configs[name] = configs md = Markdown(extensions=extension_names, extension_configs=extension_configs, safe_mode = safe_mode) return md.convert(text) class Extension: def __init__(self, configs = {}): self.config = configs def getConfig(self, key): if self.config.has_key(key): return self.config[key][0] else: return "" def getConfigInfo(self): return [(key, self.config[key][1]) for key in self.config.keys()] def setConfig(self, key, value): self.config[key][0] = value OPTPARSE_WARNING = """ Python 2.3 or higher required for advanced command line options. For lower versions of Python use: %s INPUT_FILE > OUTPUT_FILE """ % EXECUTABLE_NAME_FOR_USAGE def parse_options(): try: optparse = __import__("optparse") except: if len(sys.argv) == 2: return {'input': sys.argv[1], 'output': None, 'message_threshold': CRITICAL, 'safe': False, 'extensions': [], 'encoding': None } else: print OPTPARSE_WARNING return None parser = optparse.OptionParser(usage="%prog INPUTFILE [options]") parser.add_option("-f", "--file", dest="filename", help="write output to OUTPUT_FILE", metavar="OUTPUT_FILE") parser.add_option("-e", "--encoding", dest="encoding", help="encoding for input and output files",) parser.add_option("-q", "--quiet", default = CRITICAL, action="store_const", const=60, dest="verbose", help="suppress all messages") parser.add_option("-v", "--verbose", action="store_const", const=INFO, dest="verbose", help="print info messages") parser.add_option("-s", "--safe", dest="safe", default=False, metavar="SAFE_MODE", help="same mode ('replace', 'remove' or 'escape' user's HTML tag)") parser.add_option("--noisy", action="store_const", const=DEBUG, dest="verbose", help="print debug messages") parser.add_option("-x", "--extension", action="append", dest="extensions", help = "load extension EXTENSION", metavar="EXTENSION") (options, args) = parser.parse_args() if not len(args) == 1: parser.print_help() return None else: input_file = args[0] if not options.extensions: options.extensions = [] return {'input': input_file, 'output': options.filename, 'message_threshold': options.verbose, 'safe': options.safe, 'extensions': options.extensions, 'encoding': options.encoding } if __name__ == '__main__': """ Run Markdown from the command line. """ options = parse_options() #if os.access(inFile, os.R_OK): if not options: sys.exit(0) markdownFromFile(**options)
Python
#!/usr/bin/env python # TODO: change variables i and wordLen to short instead of int # TODO: support for case-sensitive and insensitive searching # DONE: extend to search multiple files within a directory recursively "fgrepwc.py -- searches for string in text file, displays matching lines and counts number of matches" import sys import string # print usage and exit def usage(): print "usage: fgrepwc [-i] string file" sys.exit(1) # count number of substring matches in a line def substrc(word, line): # set cursor i to the start i = 0 # number of matches in line linec = 0 # assign length of the word to a variable wordLen = len(word) while i + wordLen <= len(line) : if word[0] == line[i] and word == line[i:wordLen+i] : linec = linec + 1 i = i + wordLen else: i = i + 1 return linec # opens the file and searches for match per line; calls substrc def filefind(word, filename, caseSens=True): # print caseSens # reset word count count = 0 # can we open file? if so, return file handle try: fh = open(filename, 'r') fileOpened = 1 # if not, exit except: print filename, ":", sys.exc_info()[1] usage() if fileOpened == 1: # read all file lines into list and close allLines = fh.readlines() fh.close() # iterate over all lines of file for eachLine in allLines: # search each line for the word # if string.find(eachLine, word) > -1: # old condition if not caseSens and word.lower() in eachLine.lower() or caseSens and word in eachLine: count = count + substrc(word, eachLine) print eachLine, # when complete, substring count print count # validates arguments and calls filefind() def checkargs(): caseSens = True # argument index i = 1 # check args; 'argv' comes from 'sys' module argc = len(sys.argv) if argc < 3 or argc > 4: usage() elif argc == 4: if sys.argv[1] == "-i": i = i + 1 caseSens = False else: usage() print caseSens; # call fgrepwc.filefind() with args filefind(sys.argv[i], sys.argv[i+1], caseSens) # execute as application on its own if __name__ == '__main__': checkargs()
Python
#!/usr/bin/env python import fgrepwc import os import sys # recursively invoke fgrepwc for all the filenames and directories within this directory def fgrepwcdirectory(word, directory=os.getcwd(), caseSens=True): if directory.endswith("/"): directory = directory[:len(directory)-1] os.chdir(directory) dirList = os.listdir(os.getcwd()) subdirs = [] for fileName in dirList: if os.path.isdir(fileName): # if fileName is a directory, store in temporary list subdirs.append(fileName) else: print "In file: " + directory + "/" + fileName fgrepwc.filefind(word, fileName, caseSens) # recurse for all elements in temporary list for subdir in subdirs: fgrepwcdirectory(word, directory + "/" + subdir, caseSens) if len(sys.argv) > 2: caseSens = True # argument index i = 1 if len(sys.argv) == 4: if sys.argv[1] == "-i": i = i + 1 caseSens = False else: fgrepwc.usage(); print str(caseSens) + " " + sys.argv[i] + " " + sys.argv[i+1]; if os.path.isdir(sys.argv[i+1]): fgrepwcdirectory(sys.argv[i], sys.argv[i+1], caseSens) else: fgrepwc.filefind(sys.argv[i], sys.argv[i+1], caseSens) else: fgrepwc.usage()
Python
#!/usr/bin/env python from setuptools import setup setup(name="foaflib", version="0.2", description="Python library for working with FOAF data", author="Luke Maurits", author_email="luke@maurits.id.au", url="http://code.google.com/p/foaflib/", packages=["foaflib", "foaflib.classes", "foaflib.helpers", "foaflib.utils"], install_requires=["rdflib"] )
Python
from foaflib.utils.activitystreamevent import ActivityStreamEvent try: from urllib import urlopen from urlparse import urljoin from BeautifulSoup import BeautifulSoup from feedparser import parse _CAN_DO_ = True except ImportError: _CAN_DO_ = False def get_latest(foafprofile): entries = [] if not _CAN_DO_: return entries for blog in foafprofile.weblogs: u = urlopen(blog) blogpage = u.read() u.close() try: bs = BeautifulSoup(blogpage) feeds = bs.findAll("link",{"type":"application/rss+xml"}) for feed in feeds: try: feed_url = urljoin(blog, feed["href"]) feedentries = [] for entry in parse(feed_url)["entries"]: event = ActivityStreamEvent() event.type = "Blog post" event.detail = entry["title"] if "published_parsed" in entry: event.timestamp = entry["published_parsed"] if "updated_parsed" in entry: event.timestamp = entry["updated_parsed"] feedentries.append(event) entries.extend(feedentries) break except: continue except: continue return entries
Python
from foaflib.utils.activitystreamevent import ActivityStreamEvent class BaseHelper(object): def __init__(self): self._supported = False def _accept_account(self, onlineaccount): return False def _handle_account(self, onlineaccount): return None def get_latest(self, foafperson): if not self._supported: return [] events = [] for account in foafperson.accounts: if self._accept_account(account): account_events = self._handle_account(account) account_events = filter(lambda x: isinstance(x, ActivityStreamEvent), account_events) events.extend(account_events) return events
Python
from foaflib.utils.activitystreamevent import ActivityStreamEvent from foaflib.helpers.basehelper import BaseHelper class Identica(BaseHelper): def __init__(self): BaseHelper.__init__(self) try: import feedparser self.feedparser = feedparser self._supported = True except ImportError: self._supported = False def _accept_account(self, account): return "identi.ca" in account.accountServiceHomepage def _handle_account(self, account): events = [] username = account.accountName if not username: return events url = "https://identi.ca/api/statuses/user_timeline/%s.atom" % username try: feedentries = self.feedparser.parse(url)["entries"] for entry in feedentries: event = ActivityStreamEvent() event.type = "Identi.ca" event.detail = entry["title"] event.link = entry["link"] event.timestamp = entry["published_parsed"] events.append(event) except: pass return events
Python
from foaflib.helpers.basehelper import BaseHelper from foaflib.utils.activitystreamevent import ActivityStreamEvent class Twitter(BaseHelper): def __init__(self): BaseHelper.__init__(self) try: import twitter self.twitter = twitter import time self.time = time self._supported = True except ImportError: self._supported = False def _accept_account(self, account): return "twitter.com" in account.accountServiceHomepage def _handle_account(self, account): if account.accountName: username = account.accountName elif account.accountProfilePage: username = account.accountProfilePage.split("/")[-1] elif account.accountServiceHomepage: username = account.accountServiceHomepage.split("/")[-1] else: return [] api = self.twitter.Api() tweets = [] for tweet in api.GetUserTimeline(username): event = ActivityStreamEvent() event.type = "Twitter" event.detail = tweet.text event.link = "http://www.twitter.com/%s/status/%d" % (username, tweet.id) event.timestamp = self.time.strptime(tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y") tweets.append(event) return tweets
Python