code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright(C) 2008 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
#
# File: safecode.py
# Author: KuKei
# Create Date: 2008-07-16
# Description: 负责验证码生成。
# Modify Date: 2008-08-06
import md5
import random
from pngcanvas import PNGCanvas
class Image():
text = None
md5Text = None
img = None
width = 0
height = 0
#长度
textX = 10
textY = 10
beginX = 5
endX = 5
beginY = 5
endY = 5
spare = 4
def __init__(self,text=None):
if(text==None):
self.text = self.getRandom()
else:
self.text = text
#self.getMd5Text()
self.width = len(str(self.text))*(self.spare+self.textX)+self.beginX+self.endX
self.height = self.textY + self.beginY + self.endY
def create(self):
self.img = PNGCanvas(self.width,self.height)
self.img.color = [0xff,0xff,0xff,0xff]
#self.img.color = [0x39,0x9e,0xff,0xff]
#self.img.verticalGradient(1,1,self.width-2, self.height-2,[0xff,0,0,0xff],[0x60,0,0xff,0x80])
self.img.verticalGradient(1,1,self.width-2, self.height-2,[0xff,0x45,0x45,0xff],[0xff,0xcb,0x44,0xff])
for i in range(4):
a = str(self.text)[i]
self.writeText(a,i)
return self.img.dump()
def getRandom(self):
intRand = random.randrange(1000,9999)
return intRand
def getMd5Text(self):
m = md5.new()
m.update(str(self.text))
self.md5Text = m.hexdigest()
def writeText(self,text,pos=0):
if(text=="1"):
self.writeLine(pos, "avc")
elif(text=="2"):
self.writeLine(pos, "aht")
self.writeLine(pos, "hvtr")
self.writeLine(pos, "ahc")
self.writeLine(pos, "hvbl")
self.writeLine(pos, "ahb")
elif(text=="3"):
self.writeLine(pos, "aht")
self.writeLine(pos, "ahc")
self.writeLine(pos, "ahb")
self.writeLine(pos, "avr")
elif(text=="4"):
self.writeLine(pos, "hvtl")
self.writeLine(pos, "ahc")
self.writeLine(pos, "avc")
elif(text=="5"):
self.writeLine(pos, "aht")
self.writeLine(pos, "hvtl")
self.writeLine(pos, "ahc")
self.writeLine(pos, "hvbr")
self.writeLine(pos, "ahb")
elif(text=="6"):
self.writeLine(pos, "aht")
self.writeLine(pos, "avl")
self.writeLine(pos, "ahc")
self.writeLine(pos, "hvbr")
self.writeLine(pos, "ahb")
elif(text=="7"):
self.writeLine(pos, "aht")
self.writeLine(pos, "avr")
elif(text=="8"):
self.writeLine(pos, "aht")
self.writeLine(pos, "avl")
self.writeLine(pos, "ahc")
self.writeLine(pos, "avr")
self.writeLine(pos, "ahb")
elif(text=="9"):
self.writeLine(pos, "aht")
self.writeLine(pos, "avr")
self.writeLine(pos, "ahc")
self.writeLine(pos, "ahb")
self.writeLine(pos, "hvtl")
elif(text=="0"):
self.writeLine(pos, "aht")
self.writeLine(pos, "avl")
self.writeLine(pos, "avr")
self.writeLine(pos, "ahb")
'''
type解释
a:全部,部分上下
h:一半
h:横
v:竖
l:左,上
c:中间
r:右,下
t:上
b:下
'''
def writeLine(self,pos,type):
if(type=="avl"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos,
self.beginY,
self.beginX+(self.textX+self.spare)*pos,
self.beginY+self.textY
)
elif(type=="avc"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos+self.textX/2,
self.beginY,
self.beginX+(self.textX+self.spare)*pos+self.textX/2,
self.beginY+self.textY
)
elif(type=="avr"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos+self.textX,
self.beginY,
self.beginX+(self.textX+self.spare)*pos+self.textX,
self.beginY+self.textY
)
elif(type=="aht"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos,
self.beginY,
self.beginX+(self.textX+self.spare)*pos+self.textX,
self.beginY,
)
elif(type=="ahc"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos,
self.beginY+self.textY/2,
self.beginX+(self.textX+self.spare)*pos+self.textX,
self.beginY+self.textY/2
)
elif(type=="ahb"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos,
self.beginY+self.textY,
self.beginX+(self.textX+self.spare)*pos+self.textX,
self.beginY+self.textY
)
elif(type=="hvtl"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos,
self.beginY,
self.beginX+(self.textX+self.spare)*pos,
self.beginY+self.textY/2
)
elif(type=="hvtr"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos+self.textX,
self.beginY,
self.beginX+(self.textX+self.spare)*pos+self.textX,
self.beginY+self.textY/2
)
elif(type=="hvbl"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos,
self.beginY+self.textY/2,
self.beginX+(self.textX+self.spare)*pos,
self.beginY+self.textY
)
elif(type=="hvbr"):
self.img.line(
self.beginX+(self.textX+self.spare)*pos+self.textX,
self.beginY+self.textY/2,
self.beginX+(self.textX+self.spare)*pos+self.textX,
self.beginY+self.textY
)
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi,os
import StringIO
import logging
import re
import sys
import traceback
import urlparse
import webob
import wsgiref.headers
import wsgiref.util
from google.appengine.ext.webapp import *
class RequestHandler(RequestHandler):
def __init__(self):
self.template_vals = {}
def __before__(self,*args):
"""
Allows common code to be used for all get/post/delete methods
"""
pass
def __after__(self,*args):
"""
This runs AFTER response is returned to browser.
If you have follow up work that you don't want to do while
browser is waiting put it here such as sending emails etc
"""
pass
class WSGIApplication2(WSGIApplication):
"""
Modifyed to add new methods __before__ and __after__
before the get/post/delete/etc methods and then
AFTER RESPONSE. This is important because it means you
can do work after the response has been returned to the browser
"""
def __init__(self, url_mapping, debug=False):
"""Initializes this application with the given URL mapping.
Args:
url_mapping: list of (URI, RequestHandler) pairs (e.g., [('/', ReqHan)])
debug: if true, we send Python stack traces to the browser on errors
"""
self._init_url_mappings(url_mapping)
self.__debug = debug
WSGIApplication.active_instance = self
self.current_request_args = ()
def __call__(self, environ, start_response):
"""Called by WSGI when a request comes in."""
request = Request(environ)
response = Response()
WSGIApplication.active_instance = self
handler = None
groups = ()
for regexp, handler_class in self._url_mapping:
match = regexp.match(request.path)
if match:
handler = handler_class()
handler.initialize(request, response)
groups = match.groups()
break
self.current_request_args = groups
if handler:
try:
handler.__before__(*groups)
method = environ['REQUEST_METHOD']
if method == 'GET':
handler.get(*groups)
elif method == 'POST':
handler.post(*groups)
elif method == 'HEAD':
handler.head(*groups)
elif method == 'OPTIONS':
handler.options(*groups)
elif method == 'PUT':
handler.put(*groups)
elif method == 'DELETE':
handler.delete(*groups)
elif method == 'TRACE':
handler.trace(*groups)
else:
handler.error(501)
response.wsgi_write(start_response)
handler.__after__(*groups)
except Exception, e:
handler.handle_exception(e, self.__debug)
else:
response.set_status(404)
response.wsgi_write(start_response)
return ['']
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi,os
import StringIO
import logging
import re
import sys
import traceback
import urlparse
import webob
import wsgiref.headers
import wsgiref.util
from google.appengine.ext.webapp import *
class RequestHandler(RequestHandler):
def __init__(self):
self.template_vals = {}
def __before__(self,*args):
"""
Allows common code to be used for all get/post/delete methods
"""
pass
def __after__(self,*args):
"""
This runs AFTER response is returned to browser.
If you have follow up work that you don't want to do while
browser is waiting put it here such as sending emails etc
"""
pass
class WSGIApplication2(WSGIApplication):
"""
Modifyed to add new methods __before__ and __after__
before the get/post/delete/etc methods and then
AFTER RESPONSE. This is important because it means you
can do work after the response has been returned to the browser
"""
def __init__(self, url_mapping, debug=False):
"""Initializes this application with the given URL mapping.
Args:
url_mapping: list of (URI, RequestHandler) pairs (e.g., [('/', ReqHan)])
debug: if true, we send Python stack traces to the browser on errors
"""
self._init_url_mappings(url_mapping)
self.__debug = debug
WSGIApplication.active_instance = self
self.current_request_args = ()
def __call__(self, environ, start_response):
"""Called by WSGI when a request comes in."""
request = Request(environ)
response = Response()
WSGIApplication.active_instance = self
handler = None
groups = ()
for regexp, handler_class in self._url_mapping:
match = regexp.match(request.path)
if match:
handler = handler_class()
handler.initialize(request, response)
groups = match.groups()
break
self.current_request_args = groups
if handler:
try:
handler.__before__(*groups)
method = environ['REQUEST_METHOD']
if method == 'GET':
handler.get(*groups)
elif method == 'POST':
handler.post(*groups)
elif method == 'HEAD':
handler.head(*groups)
elif method == 'OPTIONS':
handler.options(*groups)
elif method == 'PUT':
handler.put(*groups)
elif method == 'DELETE':
handler.delete(*groups)
elif method == 'TRACE':
handler.trace(*groups)
else:
handler.error(501)
response.wsgi_write(start_response)
handler.__after__(*groups)
except Exception, e:
handler.handle_exception(e, self.__debug)
else:
response.set_status(404)
response.wsgi_write(start_response)
return ['']
| Python |
#!/usr/bin/env python
"""Simple PNG Canvas for Python"""
__version__ = "0.8"
__author__ = "Rui Carmo (http://the.taoofmac.com)"
__copyright__ = "CC Attribution-NonCommercial-NoDerivs 2.0 Rui Carmo"
__contributors__ = ["http://collaboa.weed.rbse.com/repository/file/branches/pgsql/lib/spark_pr.rb"], ["Eli Bendersky"]
import zlib, struct
signature = struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)
# alpha blends two colors, using the alpha given by c2
def blend(c1, c2):
return [c1[i]*(0xFF-c2[3]) + c2[i]*c2[3] >> 8 for i in range(3)]
# calculate a new alpha given a 0-0xFF intensity
def intensity(c,i):
return [c[0],c[1],c[2],(c[3]*i) >> 8]
# calculate perceptive grayscale value
def grayscale(c):
return int(c[0]*0.3 + c[1]*0.59 + c[2]*0.11)
# calculate gradient colors
def gradientList(start,end,steps):
delta = [end[i] - start[i] for i in range(4)]
grad = []
for i in range(steps+1):
grad.append([start[j] + (delta[j]*i)/steps for j in range(4)])
return grad
class PNGCanvas:
def __init__(self, width, height,bgcolor=[0xff,0xff,0xff,0xff],color=[0,0,0,0xff]):
self.canvas = []
self.width = width
self.height = height
self.color = color #rgba
bgcolor = bgcolor[0:3] # we don't need alpha for background
for i in range(height):
self.canvas.append([bgcolor] * width)
def point(self,x,y,color=None):
if x<0 or y<0 or x>self.width-1 or y>self.height-1: return
if color == None: color = self.color
self.canvas[y][x] = blend(self.canvas[y][x],color)
def _rectHelper(self,x0,y0,x1,y1):
x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
if x0 > x1: x0, x1 = x1, x0
if y0 > y1: y0, y1 = y1, y0
return [x0,y0,x1,y1]
def verticalGradient(self,x0,y0,x1,y1,start,end):
x0, y0, x1, y1 = self._rectHelper(x0,y0,x1,y1)
grad = gradientList(start,end,y1-y0)
for x in range(x0, x1+1):
for y in range(y0, y1+1):
self.point(x,y,grad[y-y0])
def rectangle(self,x0,y0,x1,y1):
x0, y0, x1, y1 = self._rectHelper(x0,y0,x1,y1)
self.polyline([[x0,y0],[x1,y0],[x1,y1],[x0,y1],[x0,y0]])
def filledRectangle(self,x0,y0,x1,y1):
x0, y0, x1, y1 = self._rectHelper(x0,y0,x1,y1)
for x in range(x0, x1+1):
for y in range(y0, y1+1):
self.point(x,y,self.color)
def copyRect(self,x0,y0,x1,y1,dx,dy,destination):
x0, y0, x1, y1 = self._rectHelper(x0,y0,x1,y1)
for x in range(x0, x1+1):
for y in range(y0, y1+1):
destination.canvas[dy+y-y0][dx+x-x0] = self.canvas[y][x]
def blendRect(self,x0,y0,x1,y1,dx,dy,destination,alpha=0xff):
x0, y0, x1, y1 = self._rectHelper(x0,y0,x1,y1)
for x in range(x0, x1+1):
for y in range(y0, y1+1):
rgba = self.canvas[y][x] + [alpha]
destination.point(dx+x-x0,dy+y-y0,rgba)
# draw a line using Xiaolin Wu's antialiasing technique
def line(self,x0, y0, x1, y1):
# clean params
x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
if y0>y1:
y0, y1, x0, x1 = y1, y0, x1, x0
dx = x1-x0
if dx < 0:
sx = -1
else:
sx = 1
dx *= sx
dy = y1-y0
# 'easy' cases
if dy == 0:
for x in range(x0,x1,sx):
self.point(x, y0)
return
if dx == 0:
for y in range(y0,y1):
self.point(x0, y)
self.point(x1, y1)
return
if dx == dy:
for x in range(x0,x1,sx):
self.point(x, y0)
y0 = y0 + 1
return
# main loop
self.point(x0, y0)
e_acc = 0
if dy > dx: # vertical displacement
e = (dx << 16) / dy
for i in range(y0,y1-1):
e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xFFFF
if (e_acc <= e_acc_temp):
x0 = x0 + sx
w = 0xFF-(e_acc >> 8)
self.point(x0, y0, intensity(self.color,(w)))
y0 = y0 + 1
self.point(x0 + sx, y0, intensity(self.color,(0xFF-w)))
self.point(x1, y1)
return
# horizontal displacement
e = (dy << 16) / dx
for i in range(x0,x1-sx,sx):
e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xFFFF
if (e_acc <= e_acc_temp):
y0 = y0 + 1
w = 0xFF-(e_acc >> 8)
self.point(x0, y0, intensity(self.color,(w)))
x0 = x0 + sx
self.point(x0, y0 + 1, intensity(self.color,(0xFF-w)))
self.point(x1, y1)
def polyline(self,arr):
for i in range(0,len(arr)-1):
self.line(arr[i][0],arr[i][1],arr[i+1][0], arr[i+1][1])
def dump(self):
raw_list = []
for y in range(self.height):
raw_list.append(chr(0)) # filter type 0 (None)
for x in range(self.width):
raw_list.append(struct.pack("!3B",*self.canvas[y][x]))
raw_data = ''.join(raw_list)
# 8-bit image represented as RGB tuples
# simple transparency, alpha is pure white
return signature + \
self.pack_chunk('IHDR', struct.pack("!2I5B",self.width,self.height,8,2,0,0,0)) + \
self.pack_chunk('tRNS', struct.pack("!6B",0xFF,0xFF,0xFF,0xFF,0xFF,0xFF)) + \
self.pack_chunk('IDAT', zlib.compress(raw_data,9)) + \
self.pack_chunk('IEND', '')
def pack_chunk(self,tag,data):
to_check = tag + data
return struct.pack("!I",len(data)) + to_check + struct.pack("!I", zlib.crc32(to_check) & 0xFFFFFFFF)
def load(self,f):
assert f.read(8) == signature
self.canvas=[]
for tag, data in self.chunks(f):
if tag == "IHDR":
( width,
height,
bitdepth,
colortype,
compression, filter, interlace ) = struct.unpack("!2I5B",data)
self.width = width
self.height = height
if (bitdepth,colortype,compression, filter, interlace) != (8,2,0,0,0):
raise TypeError('Unsupported PNG format')
# we ignore tRNS because we use pure white as alpha anyway
elif tag == 'IDAT':
raw_data = zlib.decompress(data)
rows = []
i = 0
for y in range(height):
filtertype = ord(raw_data[i])
i = i + 1
cur = [ord(x) for x in raw_data[i:i+width*3]]
if y == 0:
rgb = self.defilter(cur,None,filtertype)
else:
rgb = self.defilter(cur,prev,filtertype)
prev = cur
i = i+width*3
row = []
j = 0
for x in range(width):
pixel = rgb[j:j+3]
row.append(pixel)
j = j + 3
self.canvas.append(row)
def defilter(self,cur,prev,filtertype,bpp=3):
if filtertype == 0: # No filter
return cur
elif filtertype == 1: # Sub
xp = 0
for xc in range(bpp,len(cur)):
cur[xc] = (cur[xc] + cur[xp]) % 256
xp = xp + 1
elif filtertype == 2: # Up
for xc in range(len(cur)):
cur[xc] = (cur[xc] + prev[xc]) % 256
elif filtertype == 3: # Average
xp = 0
for xc in range(len(cur)):
cur[xc] = (cur[xc] + (cur[xp] + prev[xc])/2) % 256
xp = xp + 1
elif filtertype == 4: # Paeth
xp = 0
for i in range(bpp):
cur[i] = (cur[i] + prev[i]) % 256
for xc in range(bpp,len(cur)):
a = cur[xp]
b = prev[xc]
c = prev[xp]
p = a + b - c
pa = abs(p - a)
pb = abs(p - b)
pc = abs(p - c)
if pa <= pb and pa <= pc:
value = a
elif pb <= pc:
value = b
else:
value = c
cur[xc] = (cur[xc] + value) % 256
xp = xp + 1
else:
raise TypeError('Unrecognized scanline filter type')
return cur
def chunks(self,f):
while 1:
try:
length = struct.unpack("!I",f.read(4))[0]
tag = f.read(4)
data = f.read(length)
crc = struct.unpack("!i",f.read(4))[0]
except:
return
if zlib.crc32(tag + data) != crc:
raise IOError
yield [tag,data]
if __name__ == '__main__':
width = 128
height = 64
print "Creating Canvas..."
c = PNGCanvas(width,height)
c.color = [0xff,0,0,0xff]
c.rectangle(0,0,width-1,height-1)
print "Generating Gradient..."
c.verticalGradient(1,1,width-2, height-2,[0xff,0,0,0xff],[0x20,0,0xff,0x80])
print "Drawing Lines..."
c.color = [0,0,0,0xff]
c.line(0,0,width-1,height-1)
c.line(0,0,width/2,height-1)
c.line(0,0,width-1,height/2)
# Copy Rect to Self
print "Copy Rect"
c.copyRect(1,1,width/2-1,height/2-1,0,height/2,c)
# Blend Rect to Self
print "Blend Rect"
c.blendRect(1,1,width/2-1,height/2-1,width/2,0,c)
# Write test
print "Writing to file..."
f = open("test.png", "wb")
f.write(c.dump())
f.close()
# Read test
print "Reading from file..."
f = open("test.png", "rb")
c.load(f)
f.close()
# Write back
print "Writing to new file..."
f = open("recycle.png","wb")
f.write(c.dump())
f.close()
| Python |
# gmemsess.py - memcache-backed session Class for Google Appengine
# Version 1.4
# Copyright 2008 Greg Fawcett <greg@vig.co.nz>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import random
from google.appengine.api import memcache
_sidChars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
_defaultTimeout=30*60 # 30 min
_defaultCookieName='gsid'
#----------------------------------------------------------------------
class Session(dict):
"""A secure lightweight memcache-backed session Class for Google Appengine."""
#----------------------------------------------------------
def __init__(self,rh,name=_defaultCookieName,timeout=_defaultTimeout):
"""Create a session object.
Keyword arguments:
rh -- the parent's request handler (usually self)
name -- the cookie name (defaults to "gsid")
timeout -- the number of seconds the session will last between
requests (defaults to 1800 secs - 30 minutes)
"""
self.rh=rh # request handler
self._timeout=timeout
self._name=name
self._new=True
self._invalid=False
dict.__init__(self)
if name in rh.request.str_cookies:
self._sid=rh.request.str_cookies[name]
data=memcache.get(self._sid)
if data!=None:
self.update(data)
# memcache timeout is absolute, so we need to reset it on each access
memcache.set(self._sid,data,self._timeout)
self._new=False
return
# Create a new session ID
# There are about 10^14 combinations, so guessing won't work
self._sid=random.choice(_sidChars)+random.choice(_sidChars)+\
random.choice(_sidChars)+random.choice(_sidChars)+\
random.choice(_sidChars)+random.choice(_sidChars)+\
random.choice(_sidChars)+random.choice(_sidChars)
# Added path so session works with any path
rh.response.headers.add_header('Set-Cookie','%s=%s; path=/;'%(name,self._sid))
#----------------------------------------------------------
def save(self):
"""Save session data."""
if not self._invalid:
memcache.set(self._sid,self.copy(),self._timeout)
#----------------------------------------------------------
def is_new(self):
"""Returns True if session was created during this request."""
return self._new
#----------------------------------------------------------
def get_id(self):
"""Returns session id string."""
return self._sid
#----------------------------------------------------------
def invalidate(self):
"""Delete session data and cookie."""
self.rh.response.headers.add_header('Set-Cookie',
'%s=; expires=Sat, 1-Jan-2000 00:00:00 GMT;'%(self._name))
memcache.delete(self._sid)
self.clear()
self._invalid=True
| Python |
import os,logging,re
from model import OptionSet
from google.appengine.ext.webapp import template
from google.appengine.ext import zipserve
RE_FIND_GROUPS = re.compile('\(.*?\)')
class PluginIterator:
def __init__(self, plugins_path='plugins'):
self.iterating = False
self.plugins_path = plugins_path
self.list = []
self.cursor = 0
def __iter__(self):
return self
def next(self):
if not self.iterating:
self.iterating = True
self.list = os.listdir(self.plugins_path)
self.cursor = 0
if self.cursor >= len(self.list):
self.iterating = False
raise StopIteration
else:
value = self.list[self.cursor]
self.cursor += 1
if os.path.isdir(os.path.join(self.plugins_path, value)):
return (value,'%s.%s.%s'%(self.plugins_path,value,value))
elif value.endswith('.py') and not value=='__init__.py':
value=value[:-3]
return (value,'%s.%s'%(self.plugins_path,value))
else:
return self.next()
class Plugins:
def __init__(self,blog=None):
self.blog=blog
self.list={}
self._filter_plugins={}
self._action_plugins={}
self._urlmap={}
self._handlerlist={}
self._setupmenu=[]
pi=PluginIterator()
self.active_list=OptionSet.getValue("PluginActive",[])
for v,m in pi:
try:
#import plugins modules
mod=__import__(m,globals(),locals(),[v])
plugin=getattr(mod,v)()
#internal name
plugin.iname=v
plugin.active=v in self.active_list
plugin.blog=self.blog
self.list[v]=plugin
except:
pass
def add_urlhandler(self,plugin,application):
for regexp,handler in plugin._handlerlist.items():
try:
application._handler_map[handler.__name__] = handler
if not regexp.startswith('^'):
regexp = '^' + regexp
if not regexp.endswith('$'):
regexp += '$'
compiled = re.compile(regexp)
application._url_mapping.insert(-2,(compiled, handler))
num_groups = len(RE_FIND_GROUPS.findall(regexp))
handler_patterns = application._pattern_map.setdefault(handler, [])
handler_patterns.insert(-2,(compiled, num_groups))
except:
pass
def remove_urlhandler(self,plugin,application):
for regexp,handler in plugin._handlerlist.items():
try:
if application._handler_map.has_key(handler.__name__):
del application._handler_map[handler.__name__]
for um in application._url_mapping:
if um[1].__name__==handler.__name__:
del um
break
for pm in application._pattern_map:
if pm.__name__==handler.__name__:
del pm
break
except:
pass
def register_handlerlist(self,application):
for name,item in self.list.items():
if item.active and item._handlerlist:
self.add_urlhandler(item,application)
def reload(self):
pass
def __getitem__(self,index):
return self.list.values()[index]
def getPluginByName(self,iname):
if self.list.has_key(iname):
return self.list[iname]
else:
return None
def activate(self,iname,active):
if active:
plugin=self.getPluginByName(iname)
if plugin:
if (iname not in self.active_list):
self.active_list.append(iname)
OptionSet.setValue("PluginActive",self.active_list)
plugin.active=active
#add filter
for k,v in plugin._filter.items():
if self._filter_plugins.has_key(k):
if not v in self._filter_plugins[k]:
self._filter_plugins[k].append(v)
#add action
for k,v in plugin._action.items():
if self._action_plugins.has_key(k):
if not v in self._action_plugins[k]:
self._action_plugins[k].append(v)
if self.blog.application:
self.add_urlhandler(plugin,self.blog.application)
else:
plugin=self.getPluginByName(iname)
if plugin:
if (iname in self.active_list):
self.active_list.remove(iname)
OptionSet.setValue("PluginActive",self.active_list)
plugin.active=active
#remove filter
for k,v in plugin._filter.items():
if self._filter_plugins.has_key(k):
if v in self._filter_plugins[k]:
self._filter_plugins[k].remove(v)
#remove action
for k,v in plugin._action.items():
if self._action_plugins.has_key(k):
if v in self._action_plugins[k]:
self._action_plugins[k].remove(v)
if self.blog.application:
self.remove_urlhandler(plugin,self.blog.application)
self._urlmap={}
self._setupmenu=[]
def filter(self,attr,value):
rlist=[]
for item in self:
if item.active and hasattr(item,attr) and getattr(item,attr)==value:
rlist.append(item)
return rlist
def get_filter_plugins(self,name):
if not self._filter_plugins.has_key(name) :
for item in self:
if item.active and hasattr(item,"_filter") :
if item._filter.has_key(name):
if self._filter_plugins.has_key(name):
self._filter_plugins[name].append(item._filter[name])
else:
self._filter_plugins[name]=[item._filter[name]]
if self._filter_plugins.has_key(name):
return tuple(self._filter_plugins[name])
else:
return ()
def get_action_plugins(self,name):
if not self._action_plugins.has_key(name) :
for item in self:
if item.active and hasattr(item,"_action") :
if item._action.has_key(name):
if self._action_plugins.has_key(name):
self._action_plugins[name].append(item._action[name])
else:
self._action_plugins[name]=[item._action[name]]
if self._action_plugins.has_key(name):
return tuple(self._action_plugins[name])
else:
return ()
def get_urlmap_func(self,url):
if not self._urlmap:
for item in self:
if item.active:
self._urlmap.update(item._urlmap)
if self._urlmap.has_key(url):
return self._urlmap[url]
else:
return None
def get_setupmenu(self):
#Get menu list for admin setup page
if not self._setupmenu:
for item in self:
if item.active:
self._setupmenu+=item._setupmenu
return self._setupmenu
def get_handlerlist(self,url):
if not self._handlerlist:
for item in self:
if item.active:
self._handlerlist.update(item._handlerlist)
if self._handlerlist.has_key(url):
return self._handlerlist[url]
else:
return {}
def tigger_filter(self,name,content,*arg1,**arg2):
for func in self.get_filter_plugins(name):
content=func(content,*arg1,**arg2)
return content
def tigger_action(self,name,*arg1,**arg2):
for func in self.get_action_plugins(name):
func(*arg1,**arg2)
def tigger_urlmap(self,url,*arg1,**arg2):
func=self.get_urlmap_func(url)
if func:
func(*arg1,**arg2)
return True
else:
return None
class Plugin:
def __init__(self,pfile=__file__):
self.name="Unnamed"
self.author=""
self.description=""
self.uri=""
self.version=""
self.authoruri=""
self.template_vals={}
self.dir=os.path.dirname(pfile)
self._filter={}
self._action={}
self._urlmap={}
self._handlerlist={}
self._urlhandler={}
self._setupmenu=[]
def get(self,page):
return "<h3>%s</h3><p>%s</p>"%(self.name,self.description)
def render_content(self,template_file,template_vals={}):
"""
Helper method to render the appropriate template
"""
self.template_vals.update(template_vals)
path = os.path.join(self.dir, template_file)
return template.render(path, self.template_vals)
def error(self,msg=""):
return "<h3>Error:%s</h3>"%msg
def register_filter(self,name,func):
self._filter[name]=func
def register_action(self,name,func):
self._action[name]=func
def register_urlmap(self,url,func):
self._urlmap[url]=func
def register_urlhandler(self,url,handler):
self._handlerlist[url]=handler
def register_urlzip(self,name,zipfile):
zipfile=os.path.join(self.dir,zipfile)
self._handlerlist[name]=zipserve.make_zip_handler(zipfile)
def register_setupmenu(self,m_id,title,url):
#Add menu to admin setup page.
#m_id is a flag to check current page
self._setupmenu.append({'m_id':m_id,'title':title,'url':url})
class Plugin_importbase(Plugin):
def __init__(self,pfile,name,description=""):
Plugin.__init__(self,pfile)
self.is_import_plugin=True
self.import_name=name
self.import_description=description
def post(self):
pass
| Python |
# -*- coding: utf-8 -*-
import os,logging
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import Model as DBModel
from google.appengine.api import memcache
from google.appengine.api import mail
from google.appengine.api import urlfetch
from datetime import datetime
import urllib, hashlib,urlparse
import zipfile,re,pickle,uuid
#from base import *
logging.info('module base reloaded')
rootpath=os.path.dirname(__file__)
def vcache(key="",time=3600):
def _decorate(method):
def _wrapper(*args, **kwargs):
if not g_blog.enable_memcache:
return method(*args, **kwargs)
result=method(*args, **kwargs)
memcache.set(key,result,time)
return result
return _wrapper
return _decorate
class Theme:
def __init__(self, name='default'):
self.name = name
self.mapping_cache = {}
self.dir = '/themes/%s' % name
self.viewdir=os.path.join(rootpath, 'view')
self.server_dir = os.path.join(rootpath, 'themes',self.name)
if os.path.exists(self.server_dir):
self.isZip=False
else:
self.isZip=True
self.server_dir =self.server_dir+".zip"
#self.server_dir=os.path.join(self.server_dir,"templates")
logging.debug('server_dir:%s'%self.server_dir)
def __getattr__(self, name):
if self.mapping_cache.has_key(name):
return self.mapping_cache[name]
else:
path ="/".join((self.name,'templates', name + '.html'))
logging.debug('path:%s'%path)
## if not os.path.exists(path):
## path = os.path.join(rootpath, 'themes', 'default', 'templates', name + '.html')
## if not os.path.exists(path):
## path = None
self.mapping_cache[name]=path
return path
class ThemeIterator:
def __init__(self, theme_path='themes'):
self.iterating = False
self.theme_path = theme_path
self.list = []
def __iter__(self):
return self
def next(self):
if not self.iterating:
self.iterating = True
self.list = os.listdir(self.theme_path)
self.cursor = 0
if self.cursor >= len(self.list):
self.iterating = False
raise StopIteration
else:
value = self.list[self.cursor]
self.cursor += 1
if value.endswith('.zip'):
value=value[:-4]
return value
#return (str(value), unicode(value))
class LangIterator:
def __init__(self,path='locale'):
self.iterating = False
self.path = path
self.list = []
for value in os.listdir(self.path):
if os.path.isdir(os.path.join(self.path,value)):
if os.path.exists(os.path.join(self.path,value,'LC_MESSAGES')):
try:
lang=open(os.path.join(self.path,value,'language')).readline()
self.list.append({'code':value,'lang':lang})
except:
self.list.append( {'code':value,'lang':value})
def __iter__(self):
return self
def next(self):
if not self.iterating:
self.iterating = True
self.cursor = 0
if self.cursor >= len(self.list):
self.iterating = False
raise StopIteration
else:
value = self.list[self.cursor]
self.cursor += 1
return value
def getlang(self,language):
from django.utils.translation import to_locale
for item in self.list:
if item['code']==language or item['code']==to_locale(language):
return item
return {'code':'en_US','lang':'English'}
class BaseModel(db.Model):
def __init__(self, parent=None, key_name=None, _app=None, **kwds):
self.__isdirty = False
DBModel.__init__(self, parent=None, key_name=None, _app=None, **kwds)
def __setattr__(self,attrname,value):
"""
DataStore api stores all prop values say "email" is stored in "_email" so
we intercept the set attribute, see if it has changed, then check for an
onchanged method for that property to call
"""
if (attrname.find('_') != 0):
if hasattr(self,'_' + attrname):
curval = getattr(self,'_' + attrname)
if curval != value:
self.__isdirty = True
if hasattr(self,attrname + '_onchange'):
getattr(self,attrname + '_onchange')(curval,value)
DBModel.__setattr__(self,attrname,value)
class Cache(db.Model):
cachekey = db.StringProperty(multiline=False)
content = db.TextProperty()
class Blog(db.Model):
owner = db.UserProperty()
author=db.StringProperty(default='admin')
rpcuser=db.StringProperty(default='admin')
rpcpassword=db.StringProperty(default='')
description = db.TextProperty()
baseurl = db.StringProperty(multiline=False,default=None)
urlpath = db.StringProperty(multiline=False)
title = db.StringProperty(multiline=False,default='Micolog')
subtitle = db.StringProperty(multiline=False,default='This is a micro blog.')
entrycount = db.IntegerProperty(default=0)
posts_per_page= db.IntegerProperty(default=10)
feedurl = db.StringProperty(multiline=False,default='/feed')
blogversion = db.StringProperty(multiline=False,default='0.30')
theme_name = db.StringProperty(multiline=False,default='default')
enable_memcache = db.BooleanProperty(default = False)
link_format=db.StringProperty(multiline=False,default='%(year)s/%(month)s/%(day)s/%(postname)s.html')
comment_notify_mail=db.BooleanProperty(default=True)
#评论顺序
comments_order=db.IntegerProperty(default=0)
#每页评论数
comments_per_page=db.IntegerProperty(default=20)
#comment check type 0-No 1-算术 2-验证码 3-客户端计算
comment_check_type=db.IntegerProperty(default=1)
blognotice=db.TextProperty(default='')
domain=db.StringProperty()
show_excerpt=db.BooleanProperty(default=True)
version=0.713
timedelta=db.FloatProperty(default=8.0)# hours
language=db.StringProperty(default="en-us")
sitemap_entries=db.IntegerProperty(default=30)
sitemap_include_category=db.BooleanProperty(default=False)
sitemap_include_tag=db.BooleanProperty(default=False)
sitemap_ping=db.BooleanProperty(default=False)
default_link_format=db.StringProperty(multiline=False,default='?p=%(post_id)s')
default_theme=Theme("default")
allow_pingback=db.BooleanProperty(default=False)
allow_trackback=db.BooleanProperty(default=False)
theme=None
langs=None
application=None
def __init__(self,
parent=None,
key_name=None,
_app=None,
_from_entity=False,
**kwds):
from micolog_plugin import Plugins
self.plugins=Plugins(self)
db.Model.__init__(self,parent,key_name,_app,_from_entity,**kwds)
def tigger_filter(self,name,content,*arg1,**arg2):
return self.plugins.tigger_filter(name,content,blog=self,*arg1,**arg2)
def tigger_action(self,name,*arg1,**arg2):
return self.plugins.tigger_action(name,blog=self,*arg1,**arg2)
def tigger_urlmap(self,url,*arg1,**arg2):
return self.plugins.tigger_urlmap(url,blog=self,*arg1,**arg2)
def get_ziplist(self):
return self.plugins.get_ziplist();
def save(self):
self.put()
def initialsetup(self):
self.title = 'Your Blog Title'
self.subtitle = 'Your Blog Subtitle'
def get_theme(self):
self.theme= Theme(self.theme_name);
return self.theme
def get_langs(self):
self.langs=LangIterator()
return self.langs
def cur_language(self):
return self.get_langs().getlang(self.language)
def rootpath(self):
return rootpath
@vcache("blog.hotposts")
def hotposts(self):
return Entry.all().filter('entrytype =','post').filter("published =", True).order('-readtimes').fetch(8)
@vcache("blog.recentposts")
def recentposts(self):
return Entry.all().filter('entrytype =','post').filter("published =", True).order('-date').fetch(8)
@vcache("blog.postscount")
def postscount(self):
return Entry.all().filter('entrytype =','post').filter("published =", True).order('-date').count()
class Category(db.Model):
uid=db.IntegerProperty()
name=db.StringProperty(multiline=False)
slug=db.StringProperty(multiline=False)
parent_cat=db.SelfReferenceProperty()
@property
def posts(self):
return Entry.all().filter('entrytype =','post').filter("published =", True).filter('categorie_keys =',self)
@property
def count(self):
return self.posts.count()
def put(self):
db.Model.put(self)
g_blog.tigger_action("save_category",self)
def delete(self):
for entry in Entry.all().filter('categorie_keys =',self):
entry.categorie_keys.remove(self.key())
entry.put()
db.Model.delete(self)
g_blog.tigger_action("delete_category",self)
def ID(self):
try:
id=self.key().id()
if id:
return id
except:
pass
if self.uid :
return self.uid
else:
#旧版本Category没有ID,为了与wordpress兼容
from random import randint
uid=randint(0,99999999)
cate=Category.all().filter('uid =',uid).get()
while cate:
uid=randint(0,99999999)
cate=Category.all().filter('uid =',uid).get()
self.uid=uid
print uid
self.put()
return uid
@classmethod
def get_from_id(cls,id):
cate=Category.get_by_id(id)
if cate:
return cate
else:
cate=Category.all().filter('uid =',id).get()
return cate
@property
def children(self):
key=self.key()
return [c for c in Category.all().filter('parent_cat =',self)]
@classmethod
def allTops(self):
return [c for c in Category.all() if not c.parent_cat]
class Archive(db.Model):
monthyear = db.StringProperty(multiline=False)
year = db.StringProperty(multiline=False)
month = db.StringProperty(multiline=False)
entrycount = db.IntegerProperty(default=0)
date = db.DateTimeProperty(auto_now_add=True)
class Tag(db.Model):
tag = db.StringProperty(multiline=False)
tagcount = db.IntegerProperty(default=0)
@property
def posts(self):
return Entry.all('entrytype =','post').filter("published =", True).filter('tags =',self)
@classmethod
def add(cls,value):
if value:
tag= Tag.get_by_key_name(value)
if not tag:
tag=Tag(key_name=value)
tag.tag=value
tag.tagcount+=1
tag.put()
return tag
else:
return None
@classmethod
def remove(cls,value):
if value:
tag= Tag.get_by_key_name(value)
if tag:
if tag.tagcount>1:
tag.tagcount-=1
else:
tag.delete()
class Link(db.Model):
href = db.StringProperty(multiline=False,default='')
linktype = db.StringProperty(multiline=False,default='blogroll')
linktext = db.StringProperty(multiline=False,default='')
linkcomment = db.StringProperty(multiline=False,default='')
createdate=db.DateTimeProperty(auto_now=True)
@property
def get_icon_url(self):
"get ico url of the wetsite"
ico_path = '/favicon.ico'
ix = self.href.find('/',len('http://') )
return (ix>0 and self.href[:ix] or self.href ) + ico_path
def put(self):
db.Model.put(self)
g_blog.tigger_action("save_link",self)
def delete(self):
db.Model.delete(self)
g_blog.tigger_action("delete_link",self)
class Entry(BaseModel):
author = db.UserProperty()
author_name = db.StringProperty()
published = db.BooleanProperty(default=False)
content = db.TextProperty(default='')
readtimes = db.IntegerProperty(default=0)
title = db.StringProperty(multiline=False,default='')
date = db.DateTimeProperty(auto_now_add=True)
mod_date = db.DateTimeProperty(auto_now_add=True)
tags = db.StringListProperty()
categorie_keys=db.ListProperty(db.Key)
slug = db.StringProperty(multiline=False,default='')
link= db.StringProperty(multiline=False,default='')
monthyear = db.StringProperty(multiline=False)
entrytype = db.StringProperty(multiline=False,default='post',choices=[
'post','page'])
entry_parent=db.IntegerProperty(default=0)#When level=0 show on main menu.
menu_order=db.IntegerProperty(default=0)
commentcount = db.IntegerProperty(default=0)
allow_comment = db.BooleanProperty(default=True) #allow comment
#allow_pingback=db.BooleanProperty(default=False)
allow_trackback=db.BooleanProperty(default=True)
password=db.StringProperty()
#compatible with wordpress
is_wp=db.BooleanProperty(default=False)
post_id= db.IntegerProperty()
excerpt=db.StringProperty(multiline=True)
#external page
is_external_page=db.BooleanProperty(default=False)
target=db.StringProperty(default="_self")
external_page_address=db.StringProperty()
#keep in top
sticky=db.BooleanProperty(default=False)
postname=''
_relatepost=None
@property
def content_excerpt(self):
return self.get_content_excerpt(_('..more').decode('utf8'))
def get_author_user(self):
if not self.author:
self.author=g_blog.owner
return User.all().filter('email =',self.author.email()).get()
def get_content_excerpt(self,more='..more'):
if g_blog.show_excerpt:
if self.excerpt:
return self.excerpt+' <a href="/%s">%s</a>'%(self.link,more)
else:
sc=self.content.split('<!--more-->')
if len(sc)>1:
return sc[0]+u' <a href="/%s">%s</a>'%(self.link,more)
else:
return sc[0]
else:
return self.content
def slug_onchange(self,curval,newval):
if not (curval==newval):
self.setpostname(newval)
def setpostname(self,newval):
#check and fix double slug
if newval:
slugcount=Entry.all()\
.filter('entrytype',self.entrytype)\
.filter('date <',self.date)\
.filter('slug =',newval)\
.filter('published',True)\
.count()
if slugcount>0:
self.postname=newval+str(slugcount)
else:
self.postname=newval
else:
self.postname=""
@property
def fullurl(self):
return g_blog.baseurl+'/'+self.link;
@property
def categories(self):
try:
return db.get(self.categorie_keys)
except:
return []
@property
def post_status(self):
return self.published and 'publish' or 'draft'
def settags(self,values):
if not values:tags=[]
if type(values)==type([]):
tags=values
else:
tags=values.split(',')
if not self.tags:
removelist=[]
addlist=tags
else:
#search different tags
removelist=[n for n in self.tags if n not in tags]
addlist=[n for n in tags if n not in self.tags]
for v in removelist:
Tag.remove(v)
for v in addlist:
Tag.add(v)
self.tags=tags
def get_comments_by_page(self,index,psize):
return self.comments().fetch(psize,offset = (index-1) * psize)
@property
def strtags(self):
return ','.join(self.tags)
@property
def edit_url(self):
return '/admin/%s?key=%s&action=edit'%(self.entrytype,self.key())
def comments(self):
if g_blog.comments_order:
return Comment.all().filter('entry =',self).order('-date')
else:
return Comment.all().filter('entry =',self).order('date')
def commentsTops(self):
return [c for c in self.comments() if c.parent_key()==None]
def delete_comments(self):
cmts = Comment.all().filter('entry =',self)
for comment in cmts:
comment.delete()
self.commentcount = 0
def update_archive(self,cnt=1):
"""Checks to see if there is a month-year entry for the
month of current blog, if not creates it and increments count"""
my = self.date.strftime('%B %Y') # September-2008
sy = self.date.strftime('%Y') #2008
sm = self.date.strftime('%m') #09
archive = Archive.all().filter('monthyear',my).get()
if self.entrytype == 'post':
if not archive:
archive = Archive(monthyear=my,year=sy,month=sm,entrycount=1)
self.monthyear = my
archive.put()
else:
# ratchet up the count
archive.entrycount += cnt
archive.put()
g_blog.entrycount+=cnt
g_blog.put()
def save(self,is_publish=False):
"""
Use this instead of self.put(), as we do some other work here
@is_pub:Check if need publish id
"""
g_blog.tigger_action("pre_save_post",self,is_publish)
my = self.date.strftime('%B %Y') # September 2008
self.monthyear = my
old_publish=self.published
self.mod_date=datetime.now()
if is_publish:
if not self.is_wp:
self.put()
self.post_id=self.key().id()
#fix for old version
if not self.postname:
self.setpostname(self.slug)
vals={'year':self.date.year,'month':str(self.date.month).zfill(2),'day':self.date.day,
'postname':self.postname,'post_id':self.post_id}
if self.entrytype=='page':
if self.slug:
self.link=self.postname
else:
#use external page address as link
if self.is_external_page:
self.link=self.external_page_address
else:
self.link=g_blog.default_link_format%vals
else:
if g_blog.link_format and self.postname:
self.link=g_blog.link_format.strip()%vals
else:
self.link=g_blog.default_link_format%vals
self.published=is_publish
self.put()
if is_publish:
if g_blog.sitemap_ping:
Sitemap_NotifySearch()
if old_publish and not is_publish:
self.update_archive(-1)
if not old_publish and is_publish:
self.update_archive(1)
self.removecache()
self.put()
g_blog.tigger_action("save_post",self,is_publish)
def removecache(self):
memcache.delete('/')
memcache.delete('/'+self.link)
memcache.delete('/sitemap')
memcache.delete('blog.postcount')
g_blog.tigger_action("clean_post_cache",self)
@property
def next(self):
return Entry.all().filter('entrytype =','post').filter("published =", True).order('post_id').filter('post_id >',self.post_id).fetch(1)
@property
def prev(self):
return Entry.all().filter('entrytype =','post').filter("published =", True).order('-post_id').filter('post_id <',self.post_id).fetch(1)
@property
def relateposts(self):
if self._relatepost:
return self._relatepost
else:
if self.tags:
self._relatepost= Entry.gql("WHERE published=True and tags IN :1 and post_id!=:2 order by post_id desc ",self.tags,self.post_id).fetch(5)
else:
self._relatepost= []
return self._relatepost
@property
def trackbackurl(self):
if self.link.find("?")>-1:
return g_blog.baseurl+"/"+self.link+"&code="+str(self.key())
else:
return g_blog.baseurl+"/"+self.link+"?code="+str(self.key())
def getbylink(self):
pass
def delete(self):
g_blog.tigger_action("pre_delete_post",self)
if self.published:
self.update_archive(-1)
self.delete_comments()
db.Model.delete(self)
g_blog.tigger_action("delete_post",self)
class User(db.Model):
user = db.UserProperty(required = False)
dispname = db.StringProperty()
email=db.StringProperty()
website = db.LinkProperty()
isadmin=db.BooleanProperty(default=False)
isAuthor=db.BooleanProperty(default=True)
#rpcpwd=db.StringProperty()
def __unicode__(self):
#if self.dispname:
return self.dispname
#else:
# return self.user.nickname()
def __str__(self):
return self.__unicode__().encode('utf-8')
COMMENT_NORMAL=0
COMMENT_TRACKBACK=1
COMMENT_PINGBACK=2
class Comment(db.Model):
entry = db.ReferenceProperty(Entry)
date = db.DateTimeProperty(auto_now_add=True)
content = db.TextProperty(required=True)
author=db.StringProperty()
email=db.EmailProperty()
weburl=db.URLProperty()
status=db.IntegerProperty(default=0)
reply_notify_mail=db.BooleanProperty(default=False)
ip=db.StringProperty()
ctype=db.IntegerProperty(default=COMMENT_NORMAL)
comment_order=db.IntegerProperty(default=1)
@property
def shortcontent(self,len=20):
scontent=self.content
scontent=re.sub(r'<br\s*/>',' ',scontent)
scontent=re.sub(r'<[^>]+>','',scontent)
scontent=re.sub(r'(@[\S]+)-\d+[:]',r'\1:',scontent)
return scontent[:len].replace('<','<').replace('>','>')
def gravatar_url(self):
# Set your variables here
default = g_blog.baseurl+'/static/images/homsar.jpeg'
if not self.email:
return default
size = 50
try:
# construct the url
imgurl = "http://www.gravatar.com/avatar/"
imgurl +=hashlib.md5(self.email).hexdigest()+"?"+ urllib.urlencode({
'd':default, 's':str(size),'r':'G'})
return imgurl
except:
return default
def save(self):
self.put()
self.entry.commentcount+=1
self.comment_order=self.entry.commentcount
self.entry.put()
memcache.delete("/"+self.entry.link)
def delit(self):
self.entry.commentcount-=1
self.entry.put()
self.delete()
def put(self):
g_blog.tigger_action("pre_comment",self)
db.Model.put(self)
g_blog.tigger_action("save_comment",self)
def delete(self):
db.Model.delete(self)
g_blog.tigger_action("delete_comment",self)
@property
def children(self):
key=self.key()
comments=Comment.all().ancestor(self)
return [c for c in comments if c.parent_key()==key]
class Media(db.Model):
name =db.StringProperty()
mtype=db.StringProperty()
bits=db.BlobProperty()
date=db.DateTimeProperty(auto_now_add=True)
download=db.IntegerProperty(default=0)
@property
def size(self):
return len(self.bits)
class OptionSet(db.Model):
name=db.StringProperty()
value=db.TextProperty()
#blobValue=db.BlobProperty()
#isBlob=db.BooleanProperty()
@classmethod
def getValue(cls,name,default=None):
try:
opt=OptionSet.get_by_key_name(name)
return pickle.loads(str(opt.value))
except:
return default
@classmethod
def setValue(cls,name,value):
opt=OptionSet.get_or_insert(name)
opt.name=name
opt.value=pickle.dumps(value)
opt.put()
@classmethod
def remove(cls,name):
opt= OptionSet.get_by_key_name(name)
if opt:
opt.delete()
NOTIFICATION_SITES = [
('http', 'www.google.com', 'webmasters/sitemaps/ping', {}, '', 'sitemap')
]
def Sitemap_NotifySearch():
""" Send notification of the new Sitemap(s) to the search engines. """
url=g_blog.baseurl+"/sitemap"
# Cycle through notifications
# To understand this, see the comment near the NOTIFICATION_SITES comment
for ping in NOTIFICATION_SITES:
query_map = ping[3]
query_attr = ping[5]
query_map[query_attr] = url
query = urllib.urlencode(query_map)
notify = urlparse.urlunsplit((ping[0], ping[1], ping[2], query, ping[4]))
try:
urlfetch.fetch(notify)
except :
logging.error('Cannot contact: %s' % ping[1])
def InitBlogData():
global g_blog
OptionSet.setValue('PluginActive',[u'googleAnalytics', u'wordpress', u'sys_plugin'])
g_blog = Blog(key_name = 'default')
g_blog.domain=os.environ['HTTP_HOST']
g_blog.baseurl="http://"+g_blog.domain
g_blog.feedurl=g_blog.baseurl+"/feed"
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
lang="zh-cn"
if os.environ.has_key('HTTP_ACCEPT_LANGUAGE'):
lang=os.environ['HTTP_ACCEPT_LANGUAGE'].split(',')[0]
from django.utils.translation import activate,to_locale
g_blog.language=to_locale(lang)
from django.conf import settings
settings._target = None
activate(g_blog.language)
g_blog.save()
entry=Entry(title=_("Hello world!").decode('utf8'))
entry.content=_('<p>Welcome to micolog. This is your first post. Edit or delete it, then start blogging!</p>').decode('utf8')
entry.save(True)
link=Link(href='http://xuming.net',linktext=_("Xuming's blog").decode('utf8'))
link.put()
return g_blog
def gblog_init():
global g_blog
try:
if g_blog :
return g_blog
except:
pass
g_blog = Blog.get_by_key_name('default')
if not g_blog:
g_blog=InitBlogData()
g_blog.get_theme()
g_blog.rootdir=os.path.dirname(__file__)
return g_blog
try:
g_blog=gblog_init()
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.utils.translation import activate
from django.conf import settings
settings._target = None
activate(g_blog.language)
except:
pass
| Python |
# -*- coding: utf-8 -*-
import cgi, os,sys,traceback
import wsgiref.handlers
##os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
##from django.conf import settings
##settings._target = None
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.utils.translation import check_for_language, activate, to_locale, get_language
from django.conf import settings
settings._target = None
from google.appengine.ext.webapp import template, \
WSGIApplication
from google.appengine.api import users
#import app.webapp as webapp2
from google.appengine.ext import db
from google.appengine.ext import zipserve
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.api.labs import taskqueue
from datetime import datetime ,timedelta
import base64,random,math,zipfile
from django.utils import simplejson
import pickle
from base import *
from model import *
from app.trackback import TrackBack
import xmlrpclib
from xmlrpclib import Fault
class Error404(BaseRequestHandler):
#@printinfo
def get(self,slug=None):
self.render2('views/admin/404.html')
class setlanguage(BaseRequestHandler):
def get(self):
lang_code = self.param('language')
next = self.param('next')
if (not next) and os.environ.has_key('HTTP_REFERER'):
next = os.environ['HTTP_REFERER']
if not next:
next = '/'
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.utils.translation import check_for_language, activate, to_locale, get_language
from django.conf import settings
settings._target = None
if lang_code and check_for_language(lang_code):
g_blog.language=lang_code
activate(g_blog.language)
g_blog.save()
self.redirect(next)
## if hasattr(request, 'session'):
## request.session['django_language'] = lang_code
## else:
## cookiestr='django_language=%s;expires=%s;domain=%s;path=/'%( lang_code,
## (datetime.now()+timedelta(days=100)).strftime("%a, %d-%b-%Y %H:%M:%S GMT"),
## ''
## )
## self.write(cookiestr)
#self.response.headers.add_header('Set-Cookie', cookiestr)
class admin_do_action(BaseRequestHandler):
@requires_admin
def get(self,slug=None):
try:
func=getattr(self,'action_'+slug)
if func and callable(func):
func()
else:
self.render2('views/admin/error.html',{'message':_('This operate has not defined!')})
except:
self.render2('views/admin/error.html',{'message':_('This operate has not defined!')})
@requires_admin
def post(self,slug=None):
try:
func=getattr(self,'action_'+slug)
if func and callable(func):
func()
else:
self.render2('views/admin/error.html',{'message':_('This operate has not defined!')})
except:
self.render2('views/admin/error.html',{'message':_('This operate has not defined!')})
def action_test(self):
self.write(os.environ)
def action_cacheclear(self):
memcache.flush_all()
self.write(_('"Cache cleared successful"'))
def action_updatecomments(self):
for entry in Entry.all():
cnt=entry.comments().count()
if cnt<>entry.commentcount:
entry.commentcount=cnt
entry.put()
self.write(_('"All comments updated"'))
def action_updatelink(self):
link_format=self.param('linkfmt')
if link_format:
link_format=link_format.strip()
g_blog.link_format=link_format
g_blog.save()
for entry in Entry.all():
vals={'year':entry.date.year,'month':str(entry.date.month).zfill(2),'day':entry.date.day,
'postname':entry.slug,'post_id':entry.post_id}
if entry.slug:
newlink=link_format%vals
else:
newlink=g_blog.default_link_format%vals
if entry.link<>newlink:
entry.link=newlink
entry.put()
self.write(_('"Link formated succeed"'))
else:
self.write(_('"Please input url format."'))
def action_init_blog(self,slug=None):
for com in Comment.all():
com.delete()
for entry in Entry.all():
entry.delete()
g_blog.entrycount=0
self.write(_('"Init has succeed."'))
def action_update_tags(self,slug=None):
for tag in Tag.all():
tag.delete()
for entry in Entry.all().filter('entrytype =','post'):
if entry.tags:
for t in entry.tags:
try:
Tag.add(t)
except:
traceback.print_exc()
self.write(_('"All tags for entry have been updated."'))
def action_update_archives(self,slug=None):
for archive in Archive.all():
archive.delete()
entries=Entry.all().filter('entrytype =','post')
archives={}
for entry in entries:
my = entry.date.strftime('%B %Y') # September-2008
sy = entry.date.strftime('%Y') #2008
sm = entry.date.strftime('%m') #09
if archives.has_key(my):
archive=archives[my]
archive.entrycount+=1
else:
archive = Archive(monthyear=my,year=sy,month=sm,entrycount=1)
archives[my]=archive
for ar in archives.values():
ar.put()
self.write(_('"All entries have been updated."'))
def action_trackback_ping(self):
tbUrl=self.param('tbUrl')
title=self.param('title')
excerpt=self.param('excerpt')
url=self.param('url')
blog_name=self.param('blog_name')
tb=TrackBack(tbUrl,title,excerpt,url,blog_name)
tb.ping()
def action_pingback_ping(self):
"""Try to notify the server behind `target_uri` that `source_uri`
points to `target_uri`. If that fails an `PingbackError` is raised.
"""
source_uri=self.param('source')
target_uri=self.param('target')
try:
response =urlfetch.fetch(target_uri)
except:
raise PingbackError(32)
try:
pingback_uri = response.headers['X-Pingback']
except KeyError:
_pingback_re = re.compile(r'<link rel="pingback" href="([^"]+)" ?/?>(?i)')
match = _pingback_re.search(response.data)
if match is None:
raise PingbackError(33)
pingback_uri =urldecode(match.group(1))
rpc = xmlrpclib.ServerProxy(pingback_uri)
try:
return rpc.pingback.ping(source_uri, target_uri)
except Fault, e:
raise PingbackError(e.faultCode)
except:
raise PingbackError(32)
class admin_tools(BaseRequestHandler):
def __init__(self):
self.current="config"
@requires_admin
def get(self,slug=None):
self.render2('views/admin/tools.html')
class admin_sitemap(BaseRequestHandler):
def __init__(self):
self.current="config"
@requires_admin
def get(self,slug=None):
self.render2('views/admin/sitemap.html')
@requires_admin
def post(self):
str_options= self.param('str_options').split(',')
for name in str_options:
value=self.param(name)
setattr(g_blog,name,value)
bool_options= self.param('bool_options').split(',')
for name in bool_options:
value=self.param(name)=='on'
setattr(g_blog,name,value)
int_options= self.param('int_options').split(',')
for name in int_options:
try:
value=int( self.param(name))
setattr(g_blog,name,value)
except:
pass
float_options= self.param('float_options').split(',')
for name in float_options:
try:
value=float( self.param(name))
setattr(g_blog,name,value)
except:
pass
g_blog.save()
self.render2('views/admin/sitemap.html',{})
class admin_import(BaseRequestHandler):
def __init__(self):
self.current='config'
@requires_admin
def get(self,slug=None):
gblog_init()
self.render2('views/admin/import.html',{'importitems':
self.blog.plugins.filter('is_import_plugin',True)})
## def post(self):
## try:
## queue=taskqueue.Queue("import")
## wpfile=self.param('wpfile')
## #global imt
## imt=import_wordpress(wpfile)
## imt.parse()
## memcache.set("imt",imt)
##
#### import_data=OptionSet.get_or_insert(key_name="import_data")
#### import_data.name="import_data"
#### import_data.bigvalue=pickle.dumps(imt)
#### import_data.put()
##
## queue.add(taskqueue.Task( url="/admin/import_next"))
## self.render2('views/admin/import.html',
## {'postback':True})
## return
## memcache.set("import_info",{'count':len(imt.entries),'msg':'Begin import...','index':1})
## #self.blog.import_info={'count':len(imt.entries),'msg':'Begin import...','index':1}
## if imt.categories:
## queue.add(taskqueue.Task( url="/admin/import_next",params={'cats': pickle.dumps(imt.categories),'index':1}))
##
## return
## index=0
## if imt.entries:
## for entry in imt.entries :
## try:
## index=index+1
## queue.add(taskqueue.Task(url="/admin/import_next",params={'entry':pickle.dumps(entry),'index':index}))
## except:
## pass
##
## except:
## self.render2('views/admin/import.html',{'error':'import faiure.'})
class admin_setup(BaseRequestHandler):
def __init__(self):
self.current='config'
@requires_admin
def get(self,slug=None):
vals={'themes':ThemeIterator()}
self.render2('views/admin/setup.html',vals)
@requires_admin
def post(self):
old_theme=g_blog.theme_name
str_options= self.param('str_options').split(',')
for name in str_options:
value=self.param(name)
setattr(g_blog,name,value)
bool_options= self.param('bool_options').split(',')
for name in bool_options:
value=self.param(name)=='on'
setattr(g_blog,name,value)
int_options= self.param('int_options').split(',')
for name in int_options:
try:
value=int( self.param(name))
setattr(g_blog,name,value)
except:
pass
float_options= self.param('float_options').split(',')
for name in float_options:
try:
value=float( self.param(name))
setattr(g_blog,name,value)
except:
pass
if old_theme !=g_blog.theme_name:
g_blog.get_theme()
g_blog.owner=self.login_user
g_blog.author=g_blog.owner.nickname()
g_blog.save()
gblog_init()
vals={'themes':ThemeIterator()}
memcache.flush_all()
self.render2('views/admin/setup.html',vals)
class admin_entry(BaseRequestHandler):
def __init__(self):
self.current='write'
@requires_admin
def get(self,slug='post'):
action=self.param("action")
entry=None
cats=Category.all()
if action and action=='edit':
try:
key=self.param('key')
entry=Entry.get(key)
except:
pass
else:
action='add'
def mapit(cat):
return {'name':cat.name,'slug':cat.slug,'select':entry and cat.key() in entry.categorie_keys}
vals={'action':action,'entry':entry,'entrytype':slug,'cats':map(mapit,cats)}
self.render2('views/admin/entry.html',vals)
@requires_admin
def post(self,slug='post'):
action=self.param("action")
title=self.param("post_title")
content=self.param('content')
tags=self.param("tags")
cats=self.request.get_all('cats')
key=self.param('key')
if self.param('publish')!='':
published=True
elif self.param('unpublish')!='':
published=False
else:
published=self.param('published')=='True'
allow_comment=self.parambool('allow_comment')
allow_trackback=self.parambool('allow_trackback')
entry_slug=self.param('slug')
entry_parent=self.paramint('entry_parent')
menu_order=self.paramint('menu_order')
entry_excerpt=self.param('excerpt').replace('\n','<br>')
password=self.param('password')
sticky=self.parambool('sticky')
is_external_page=self.parambool('is_external_page')
target=self.param('target')
external_page_address=self.param('external_page_address')
def mapit(cat):
return {'name':cat.name,'slug':cat.slug,'select':cat.slug in cats}
vals={'action':action,'postback':True,'cats':Category.all(),'entrytype':slug,
'cats':map(mapit,Category.all()),
'entry':{ 'title':title,'content':content,'strtags':tags,'key':key,'published':published,
'allow_comment':allow_comment,
'allow_trackback':allow_trackback,
'slug':entry_slug,
'entry_parent':entry_parent,
'excerpt':entry_excerpt,
'menu_order':menu_order,
'is_external_page':is_external_page,
'target':target,
'external_page_address':external_page_address,
'password':password,
'sticky':sticky}
}
if not (title and (content or (is_external_page and external_page_address))):
vals.update({'result':False, 'msg':_('Please input title and content.')})
self.render2('views/admin/entry.html',vals)
else:
if action=='add':
entry= Entry(title=title,content=content)
entry.settags(tags)
entry.entrytype=slug
entry.slug=entry_slug.replace(" ","-")
entry.entry_parent=entry_parent
entry.menu_order=menu_order
entry.excerpt=entry_excerpt
entry.is_external_page=is_external_page
entry.target=target
entry.external_page_address=external_page_address
newcates=[]
entry.allow_comment=allow_comment
entry.allow_trackback=allow_trackback
entry.author=self.author.user
entry.author_name=self.author.dispname
entry.password=password
entry.sticky=sticky
if cats:
for cate in cats:
c=Category.all().filter('slug =',cate)
if c:
newcates.append(c[0].key())
entry.categorie_keys=newcates;
entry.save(published)
if published:
smsg=_('Saved ok. <a href="/%(link)s" target="_blank">View it now!</a>')
else:
smsg=_('Saved ok.')
vals.update({'action':'edit','result':True,'msg':smsg%{'link':str(entry.link)},'entry':entry})
self.render2('views/admin/entry.html',vals)
elif action=='edit':
try:
entry=Entry.get(key)
entry.title=title
entry.content=content
entry.slug=entry_slug.replace(' ','-')
entry.entry_parent=entry_parent
entry.menu_order=menu_order
entry.excerpt=entry_excerpt
entry.is_external_page=is_external_page
entry.target=target
entry.external_page_address=external_page_address
entry.settags(tags)
entry.author=self.author.user
entry.author_name=self.author.dispname
entry.password=password
entry.sticky=sticky
newcates=[]
if cats:
for cate in cats:
c=Category.all().filter('slug =',cate)
if c:
newcates.append(c[0].key())
entry.categorie_keys=newcates;
entry.allow_comment=allow_comment
entry.allow_trackback=allow_trackback
entry.save(published)
if published:
smsg=_('Saved ok. <a href="/%(link)s" target="_blank">View it now!</a>')
else:
smsg=_('Saved ok.')
vals.update({'result':True,'msg':smsg%{'link':str(entry.link)},'entry':entry})
self.render2('views/admin/entry.html',vals)
except:
vals.update({'result':False,'msg':_('Error:Entry can''t been saved.')})
self.render2('views/admin/entry.html',vals)
class admin_entries(BaseRequestHandler):
@requires_admin
def get(self,slug='post'):
try:
page_index=int(self.param('page'))
except:
page_index=1
entries=Entry.all().filter('entrytype =',slug).order('-date')
entries,links=Pager(query=entries,items_per_page=15).fetch(page_index)
self.render2('views/admin/'+slug+'s.html',
{
'current':slug+'s',
'entries':entries,
'pager':links
}
)
@requires_admin
def post(self,slug='post'):
try:
linkcheck= self.request.get_all('checks')
for id in linkcheck:
kid=int(id)
entry=Entry.get_by_id(kid)
#delete it's comments
#entry.delete_comments()
entry.delete()
g_blog.entrycount-=1
finally:
self.redirect('/admin/entries/'+slug)
class admin_categories(BaseRequestHandler):
@requires_admin
def get(self,slug=None):
try:
page_index=int(self.param('page'))
except:
page_index=1
cats=Category.allTops()
entries,pager=Pager(query=cats,items_per_page=15).fetch(page_index)
self.render2('views/admin/categories.html',
{
'current':'categories',
'cats':cats,
'pager':pager
}
)
@requires_admin
def post(self,slug=None):
try:
linkcheck= self.request.get_all('checks')
for key in linkcheck:
cat=Category.get(key)
cat.delete()
finally:
self.redirect('/admin/categories')
class admin_comments(BaseRequestHandler):
@requires_admin
def get(self,slug=None):
try:
page_index=int(self.param('page'))
except:
page_index=1
cq=self.param('cq')
cv=self.param('cv')
if cq and cv:
query=Comment.all().filter(cq+' =',cv).order('-date')
else:
query=Comment.all().order('-date')
comments,pager=Pager(query=query,items_per_page=15).fetch(page_index)
self.render2('views/admin/comments.html',
{
'current':'comments',
'comments':comments,
'pager':pager,
'cq':cq,
'cv':cv
}
)
@requires_admin
def post(self,slug=None):
try:
linkcheck= self.request.get_all('checks')
for key in linkcheck:
comment=Comment.get(key)
comment.delit()
finally:
self.redirect(self.request.uri)
class admin_links(BaseRequestHandler):
@requires_admin
def get(self,slug=None):
self.render2('views/admin/links.html',
{
'current':'links',
'links':Link.all().filter('linktype =','blogroll')#.order('-createdate')
}
)
@requires_admin
def post(self):
linkcheck= self.request.get_all('linkcheck')
for link_id in linkcheck:
kid=int(link_id)
link=Link.get_by_id(kid)
link.delete()
self.redirect('/admin/links')
class admin_link(BaseRequestHandler):
@requires_admin
def get(self,slug=None):
action=self.param("action")
vals={'current':'links'}
if action and action=='edit':
try:
action_id=int(self.param('id'))
link=Link.get_by_id(action_id)
vals.update({'link':link})
except:
pass
else:
action='add'
vals.update({'action':action})
self.render2('views/admin/link.html',vals)
@requires_admin
def post(self):
action=self.param("action")
name=self.param("link_name")
url=self.param("link_url")
comment = self.param("link_comment")
vals={'action':action,'postback':True,'current':'links'}
if not (name and url):
vals.update({'result':False,'msg':_('Please input name and url.')})
self.render2('views/admin/link.html',vals)
else:
if action=='add':
link= Link(linktext=name,href=url,linkcomment=comment)
link.put()
vals.update({'result':True,'msg':'Saved ok'})
self.render2('views/admin/link.html',vals)
elif action=='edit':
try:
action_id=int(self.param('id'))
link=Link.get_by_id(action_id)
link.linktext=name
link.href=url
link.linkcomment = comment
link.put()
#goto link manage page
self.redirect('/admin/links')
except:
vals.update({'result':False,'msg':_('Error:Link can''t been saved.')})
self.render2('views/admin/link.html',vals)
class admin_category(BaseRequestHandler):
def __init__(self):
self.current='categories'
@requires_admin
def get(self,slug=None):
action=self.param("action")
key=self.param('key')
category=None
if action and action=='edit':
try:
category=Category.get(key)
except:
pass
else:
action='add'
vals={'action':action,'category':category,'key':key,'categories':[c for c in Category.all() if not category or c.key()!=category.key()]}
self.render2('views/admin/category.html',vals)
@requires_admin
def post(self):
def check(cate):
parent=cate.parent_cat
skey=cate.key()
while parent:
if parent.key()==skey:
return False
parent=parent.parent_cat
return True
action=self.param("action")
name=self.param("name")
slug=self.param("slug")
parentkey=self.param('parentkey')
key=self.param('key')
vals={'action':action,'postback':True}
try:
if action=='add':
cat= Category(name=name,slug=slug)
if not (name and slug):
raise Exception(_('Please input name and slug.'))
if parentkey:
cat.parent_cat=Category.get(parentkey)
cat.put()
self.redirect('/admin/categories')
#vals.update({'result':True,'msg':_('Saved ok')})
#self.render2('views/admin/category.html',vals)
elif action=='edit':
cat=Category.get(key)
cat.name=name
cat.slug=slug
if not (name and slug):
raise Exception(_('Please input name and slug.'))
if parentkey:
cat.parent_cat=Category.get(parentkey)
if not check(cat):
raise Exception(_('A circle declaration found.'))
else:
cat.parent_cat=None
cat.put()
self.redirect('/admin/categories')
except Exception ,e :
if cat.is_saved():
cates=[c for c in Category.all() if c.key()!=cat.key()]
else:
cates= Category.all()
vals.update({'result':False,'msg':e.message,'category':cat,'key':key,'categories':cates})
self.render2('views/admin/category.html',vals)
class admin_status(BaseRequestHandler):
@requires_admin
def get(self):
self.render2('views/admin/status.html',{'cache':memcache.get_stats(),'current':'status','environ':os.environ})
class admin_authors(BaseRequestHandler):
@requires_admin
def get(self):
try:
page_index=int(self.param('page'))
except:
page_index=1
authors=User.all().filter('isAuthor =',True)
entries,pager=Pager(query=authors,items_per_page=15).fetch(page_index)
self.render2('views/admin/authors.html',
{
'current':'authors',
'authors':authors,
'pager':pager
}
)
@requires_admin
def post(self,slug=None):
try:
linkcheck= self.request.get_all('checks')
for key in linkcheck:
author=User.get(key)
author.delete()
finally:
self.redirect('/admin/authors')
class admin_author(BaseRequestHandler):
def __init__(self):
self.current='authors'
@requires_admin
def get(self,slug=None):
action=self.param("action")
author=None
if action and action=='edit':
try:
key=self.param('key')
author=User.get(key)
except:
pass
else:
action='add'
vals={'action':action,'author':author}
self.render2('views/admin/author.html',vals)
@requires_admin
def post(self):
action=self.param("action")
name=self.param("name")
slug=self.param("email")
vals={'action':action,'postback':True}
if not (name and slug):
vals.update({'result':False,'msg':_('Please input dispname and email.')})
self.render2('views/admin/author.html',vals)
else:
if action=='add':
author= User(dispname=name,email=slug )
author.user=db.users.User(slug)
author.put()
vals.update({'result':True,'msg':'Saved ok'})
self.render2('views/admin/author.html',vals)
elif action=='edit':
try:
key=self.param('key')
author=User.get(key)
author.dispname=name
author.email=slug
author.user=db.users.User(slug)
author.put()
if author.isadmin:
g_blog.author=name
self.redirect('/admin/authors')
except:
vals.update({'result':False,'msg':_('Error:Author can''t been saved.')})
self.render2('views/admin/author.html',vals)
class admin_plugins(BaseRequestHandler):
def __init__(self):
self.current='plugins'
@requires_admin
def get(self,slug=None):
vals={'plugins':self.blog.plugins}
self.render2('views/admin/plugins.html',vals)
@requires_admin
def post(self):
action=self.param("action")
name=self.param("plugin")
ret=self.param("return")
self.blog.plugins.activate(name,action=="activate")
if ret:
self.redirect(ret)
else:
vals={'plugins':self.blog.plugins}
self.render2('views/admin/plugins.html',vals)
class admin_plugins_action(BaseRequestHandler):
def __init__(self):
self.current='plugins'
@requires_admin
def get(self,slug=None):
plugin=self.blog.plugins.getPluginByName(slug)
if not plugin :
self.error(404)
return
plugins=self.blog.plugins.filter('active',True)
if not plugin.active:
pcontent=_('''<div>Plugin '%(name)s' havn't actived!</div><br><form method="post" action="/admin/plugins?action=activate&plugin=%(iname)s&return=/admin/plugins/%(iname)s"><input type="submit" value="Activate Now"/></form>''')%{'name':plugin.name,'iname':plugin.iname}
plugins.insert(0,plugin)
else:
pcontent=plugin.get(self)
vals={'plugins':plugins,
'plugin':plugin,
'pcontent':pcontent}
self.render2('views/admin/plugin_action.html',vals)
@requires_admin
def post(self,slug=None):
plugin=self.blog.plugins.getPluginByName(slug)
if not plugin :
self.error(404)
return
plugins=self.blog.plugins.filter('active',True)
if not plugin.active:
pcontent=_('''<div>Plugin '%(name)s' havn't actived!</div><br><form method="post" action="/admin/plugins?action=activate&plugin=%(iname)s&return=/admin/plugins/%(iname)s"><input type="submit" value="Activate Now"/></form>''')%{'name':plugin.name,'iname':plugin.iname}
plugins.insert(0,plugin)
else:
pcontent=plugin.post(self)
vals={'plugins':plugins,
'plugin':plugin,
'pcontent':pcontent}
self.render2('views/admin/plugin_action.html',vals)
class WpHandler(BaseRequestHandler):
@requires_admin
def get(self,tags=None):
try:
all=self.param('all')
except:
all=False
if(all):
entries = Entry.all().order('-date')
else:
str_date_begin=self.param('date_begin')
str_date_end=self.param('date_end')
try:
date_begin=datetime.strptime(str_date_begin,"%Y-%m-%d")
date_end=datetime.strptime(str_date_end,"%Y-%m-%d")
entries = Entry.all().filter('date >=',date_begin).filter('date <',date_end).order('-date')
except:
self.render2('views/admin/404.html')
return
cates=Category.all()
tags=Tag.all()
self.response.headers['Content-Type'] = 'binary/octet-stream'#'application/atom+xml'
self.render2('views/wordpress.xml',{'entries':entries,'cates':cates,'tags':tags})
class Upload(BaseRequestHandler):
@requires_admin
def post(self):
name = self.param('filename')
mtype = self.param('fileext')
bits = self.param('upfile')
Media(name = name, mtype = mtype, bits = bits).put()
self.redirect('/admin/filemanager')
class UploadEx(BaseRequestHandler):
@requires_admin
def get(self):
extstr=self.param('ext')
ext=extstr.split('|')
files=Media.all()
if extstr!='*':
files=files.filter('mtype IN',ext)
self.render2('views/admin/upload.html',{'ext':extstr,'files':files})
@requires_admin
def post(self):
ufile=self.request.params['userfile']
#if ufile:
name=ufile.filename
mtype =os.path.splitext(name)[1][1:]
bits = self.param('userfile')
media=Media(name = name, mtype = mtype, bits = bits)
media.put()
self.write(simplejson.dumps({'name':media.name,'size':media.size,'id':str(media.key())}))
class FileManager(BaseRequestHandler):
def __init__(self):
self.current='files'
@requires_admin
def get(self):
try:
page_index=int(self.param('page'))
except:
page_index=1
files = Media.all().order('-date')
files,links=Pager(query=files,items_per_page=15).fetch(page_index)
self.render2('views/admin/filemanager.html',{'files' : files,'pager':links})
@requires_admin
def post(self): # delete files
delids = self.request.POST.getall('del')
if delids:
for id in delids:
file = Media.get_by_id(int(id))
file.delete()
self.redirect('/admin/filemanager')
class admin_main(BaseRequestHandler):
@requires_admin
def get(self,slug=None):
if self.is_admin:
self.redirect('/admin/setup')
else:
self.redirect('/admin/entries/post')
class admin_ThemeEdit(BaseRequestHandler):
@requires_admin
def get(self,slug):
zfile=zipfile.ZipFile(os.path.join(rootpath,"themes",slug+".zip"))
newfile=zipfile.ZipFile('')
for item in zfile.infolist():
self.write(item.filename+"<br>")
def main():
webapp.template.register_template_library('filter')
webapp.template.register_template_library('app.recurse')
application = webapp.WSGIApplication(
[
('/admin/{0,1}',admin_main),
('/admin/setup',admin_setup),
('/admin/entries/(post|page)',admin_entries),
('/admin/links',admin_links),
('/admin/categories',admin_categories),
('/admin/comments',admin_comments),
('/admin/link',admin_link),
('/admin/category',admin_category),
('/admin/(post|page)',admin_entry),
('/admin/status',admin_status),
('/admin/authors',admin_authors),
('/admin/author',admin_author),
('/admin/import',admin_import),
('/admin/tools',admin_tools),
('/admin/plugins',admin_plugins),
('/admin/plugins/(\w+)',admin_plugins_action),
('/admin/sitemap',admin_sitemap),
('/admin/export/micolog.xml',WpHandler),
('/admin/do/(\w+)',admin_do_action),
('/admin/lang',setlanguage),
('/admin/theme/edit/(\w+)',admin_ThemeEdit),
('/admin/upload', Upload),
('/admin/filemanager', FileManager),
('/admin/uploadex', UploadEx),
('.*',Error404),
],debug=True)
g_blog.application=application
g_blog.plugins.register_handlerlist(application)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == "__main__":
main() | Python |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""A simple wrapper for Django templates.
The main purpose of this module is to hide all of the package import pain
you normally have to go through to get Django to work. We expose the Django
Template and Context classes from this module, handling the import nonsense
on behalf of clients.
Typical usage:
from google.appengine.ext.webapp import template
print template.render('templates/index.html', {'foo': 'bar'})
Django uses a global setting for the directory in which it looks for templates.
This is not natural in the context of the webapp module, so our load method
takes in a complete template path, and we set these settings on the fly
automatically. Because we have to set and use a global setting on every
method call, this module is not thread safe, though that is not an issue
for applications.
Django template documentation is available at:
http://www.djangoproject.com/documentation/templates/
"""
import md5
import os,logging
try:
from django import v0_96
except ImportError:
pass
import django
import django.conf
try:
django.conf.settings.configure(
DEBUG=False,
TEMPLATE_DEBUG=False,
TEMPLATE_LOADERS=(
'django.template.loaders.filesystem.load_template_source',
),
)
except (EnvironmentError, RuntimeError):
pass
import django.template
import django.template.loader
from google.appengine.ext import webapp
def render(theme,template_file, template_dict, debug=False):
"""Renders the template at the given path with the given dict of values.
Example usage:
render("templates/index.html", {"name": "Bret", "values": [1, 2, 3]})
Args:
template_path: path to a Django template
template_dict: dictionary of values to apply to the template
"""
t = load(theme,template_file, debug)
return t.render(Context(template_dict))
template_cache = {}
def load(theme,template_file, debug=False):
"""Loads the Django template from the given path.
It is better to use this function than to construct a Template using the
class below because Django requires you to load the template with a method
if you want imports and extends to work in the template.
"""
#template_file=os.path.join("templates",template_file)
if theme.isZip:
theme_path=theme.server_dir
else:
theme_path=os.path.join( theme.server_dir,"templates")
abspath =os.path.join( theme_path,template_file)
logging.debug("theme_path:%s,abspath:%s"%(theme_path,abspath))
if not debug:
template = template_cache.get(abspath, None)
else:
template = None
if not template:
#file_name = os.path.split(abspath)
new_settings = {
'TEMPLATE_DIRS': (theme_path,),
'TEMPLATE_DEBUG': debug,
'DEBUG': debug,
}
old_settings = _swap_settings(new_settings)
try:
template = django.template.loader.get_template(template_file)
finally:
_swap_settings(old_settings)
if not debug:
template_cache[abspath] = template
def wrap_render(context, orig_render=template.render):
URLNode = django.template.defaulttags.URLNode
save_urlnode_render = URLNode.render
old_settings = _swap_settings(new_settings)
try:
URLNode.render = _urlnode_render_replacement
return orig_render(context)
finally:
_swap_settings(old_settings)
URLNode.render = save_urlnode_render
template.render = wrap_render
return template
def _swap_settings(new):
"""Swap in selected Django settings, returning old settings.
Example:
save = _swap_settings({'X': 1, 'Y': 2})
try:
...new settings for X and Y are in effect here...
finally:
_swap_settings(save)
Args:
new: A dict containing settings to change; the keys should
be setting names and the values settings values.
Returns:
Another dict structured the same was as the argument containing
the original settings. Original settings that were not set at all
are returned as None, and will be restored as None by the
'finally' clause in the example above. This shouldn't matter; we
can't delete settings that are given as None, since None is also a
legitimate value for some settings. Creating a separate flag value
for 'unset' settings seems overkill as there is no known use case.
"""
settings = django.conf.settings
old = {}
for key, value in new.iteritems():
old[key] = getattr(settings, key, None)
setattr(settings, key, value)
return old
def create_template_register():
"""Used to extend the Django template library with custom filters and tags.
To extend the template library with a custom filter module, create a Python
module, and create a module-level variable named "register", and register
all custom filters to it as described at
http://www.djangoproject.com/documentation/templates_python/
#extending-the-template-system:
templatefilters.py
==================
register = webapp.template.create_template_register()
def cut(value, arg):
return value.replace(arg, '')
register.filter(cut)
Then, register the custom template module with the register_template_library
function below in your application module:
myapp.py
========
webapp.template.register_template_library('templatefilters')
"""
return django.template.Library()
def register_template_library(package_name):
"""Registers a template extension module to make it usable in templates.
See the documentation for create_template_register for more information."""
if not django.template.libraries.get(package_name, None):
django.template.add_to_builtins(package_name)
Template = django.template.Template
Context = django.template.Context
def _urlnode_render_replacement(self, context):
"""Replacement for django's {% url %} block.
This version uses WSGIApplication's url mapping to create urls.
Examples:
<a href="{% url MyPageHandler "overview" %}">
{% url MyPageHandler implicit_args=False %}
{% url MyPageHandler "calendar" %}
{% url MyPageHandler "jsmith","calendar" %}
"""
args = [arg.resolve(context) for arg in self.args]
try:
app = webapp.WSGIApplication.active_instance
handler = app.get_registered_handler_by_name(self.view_name)
return handler.get_url(implicit_args=True, *args)
except webapp.NoUrlFoundError:
return ''
| Python |
from django import forms
from nutrition.models import DataSource, DataSourceLink, DataDerivation
from nutrition.models import FoodGroup, FoodDescription, Footnote
from nutrition.models import NutrientData, NutrientDefinition, SourceCode
from nutrition.models import Weight
class DataSourceForm(forms.ModelForm):
class Meta:
model = DataSource
class DataSourceLinkForm(forms.ModelForm):
class Meta:
model = DataSourceLink
class DataDerivationForm(forms.ModelForm):
class Meta:
model = DataDerivation
class SourceCodeForm(forms.ModelForm):
class Meta:
model = SourceCode
class NutrientDefinitionForm(forms.ModelForm):
class Meta:
model = NutrientDefinition
class NutrientDataForm(forms.ModelForm):
class Meta:
model = NutrientData
class WeightForm(forms.ModelForm):
class Meta:
model = Weight
class FoodGroupForm(forms.ModelForm):
class Meta:
model = FoodGroup
class FootnoteForm(forms.ModelForm):
class Meta:
model = Footnote
class FoodDescriptionForm(forms.ModelForm):
class Meta:
model = FoodDescription | Python |
from django.db import models
class BaseNutritionClass(models.Model):
def resolve_relations(self, force=False):
# By default, assume no relations exist and return true.
return True
class Meta:
abstract = Treu
class FoodDescription(BaseNutritionClass):
# Relation Fields
food_group = models.ForeignKey('FoodGroup', blank=True, null=True,
help_text='''Related via fdgrp_cd''')
nutrient_data = models.ForeignKey('NutrientData', blank=True, null=True,
help_text='''Related via ndb_no''')
weight = models.ForeignKey('Weight', blank=True, null=True,
help_text='''Related via ndb_no''')
footnote = models.ForeignKey('Footnote', blank=True, null=True,
help_text='''Related via ndb_no''')
# Imported Data Fields
ndb_no = models.IntegerField(max_length=10, unique=True,
help_text='''5-digit Nutrient Databank number that uniquely identifies a food item''')
fdgrp_cd = models.IntegerField(max_length=8,
help_text='''4-digit code indicating food group to which a food item belongs''')
long_desc = models.TextField(
verbose_name='''long description''',
help_text='''200-character description of food item''')
shrt_desc = models.CharField(max_length=255,
verbose_name='''short description''',
help_text='''60-character abbreviated description of food item. Generated from the 200-character description using abbreviations in Appendix A. If short description is longer than 60 characters, additional abbreviations are made.''')
comname = models.CharField(max_length=255, blank=True,
verbose_name='''common name''',
help_text='''Other names commonly used to describe a food, including local or regional names for various foods, for example, \u201csoda\u201d or \u201cpop\u201d for \u201ccarbonated beverages\u201d''')
manufacname = models.CharField(max_length=255, blank=True,
verbose_name='''manufacturer name''',
help_text='''Indicates the company that manufactured the product, when appropriate''')
survey = models.NullBooleanField(
help_text='''Indicates if the food item is used in the USDA Food and Nutrient Database for Dietary Studies (FNDDS) and has a complete nutrient profile for a specified set of nutrients''')
ref_desc = models.TextField(blank=True,
verbose_name='''refuse description''',
help_text='''Description of inedible parts of a food item (refuse), such as seeds or bone''')
refuse = models.IntegerField(blank=True, null=True,
help_text='''Percentage of refuse''')
sciname = models.CharField(max_length=255, blank=True,
verbose_name='''scientific name''',
help_text='''Scientific name of the food item. Given for the least processed form of the food (usually raw), if applicable''')
n_factor = models.FloatField(blank=True, null=True,
help_text='''Factor for converting nitrogen to protein''')
pro_factor = models.FloatField(blank=True, null=True,
help_text='''Factor for calculating calories from protein''')
fat_factor = models.FloatField(blank=True, null=True,
help_text='''Factor for calculating calories from fat''')
cho_factor = models.FloatField(blank=True, null=True,
help_text='''Factor for calculating calories from carbohydrate''')
class Meta:
verbose_name = "food description"
verbose_name_plural = "food descriptions"
def __unicode__(self):
return self.long_desc
def resolve_relations(self, force=False):
# Resolve Relation Fields
resolved = True
if force or not self.food_group:
try:
self.food_group = FoodGroup.objects.get(fdgrp_cd=self.fdgrp_cd)
except FoodGroup.DoesNotExist:
resolved = False
if force or not self.nutrient_data:
try:
self.nutrient_data = NutrientData.objects.get(ndb_no=self.ndb_no)
except NutrientData.DoesNotExist:
resolved = False
if force or not self.weight:
try:
self.weight = Weight.objects.get(ndb_no=self.ndb_no)
except Weight.DoesNotExist:
resolved = False
if force or not self.footnote:
try:
self.footnote = Footnote.objects.get(ndb_no=self.ndb_no)
except Footnote.DoesNotExist:
resolved = False
self.save()
return resolved
class FoodGroup(BaseNutritionClass):
# Imported Data Fields
fdgrp_cd = models.CharField(max_length=8, unique=True,
verbose_name='''code''',
help_text='''4-digit code identifying a food group. Only the first 2 digits are currently assigned. In the future, the last 2 digits may be used. Codes may not be consecutive.''')
fdgrp_desc = models.CharField(max_length=255,
verbose_name='''name''',
help_text='''Name of food group''')
class Meta:
verbose_name = "food group"
verbose_name_plural = "food groups"
def __unicode__(self):
return self.fdgrp_desc
class NutrientData(BaseNutritionClass):
# Relation Fields
nutrient_def = models.ForeignKey('NutrientDefinition', blank=True, null=True,
verbose_name='''nutrient definition''',
help_text='''Related via nutr_no''')
source_code = models.ForeignKey('SourceCode', blank=True, null=True,
help_text='''Related via src_cd''')
data_derivation = models.ForeignKey('DataDerivation', blank=True, null=True,
help_text='''Related via deriv_cd''')
data_source_ln = models.ManyToManyField('DataSourceLink', blank=True, null=True,
verbose_name='''data source link''',
help_text='''Related via ndb_no and nutr_no''')
# Imported Data Fields
ndb_no = models.IntegerField(max_length=10,
help_text='''5-digit Nutrient Databank number that uniquely identifies a food item''')
nutr_no = models.IntegerField(max_length=6,
help_text='''Unique 3-digit identifier code for a nutrient''')
nutr_val = models.FloatField(
help_text = '''Amount in 100 grams, edible portion''')
num_data_pts = models.FloatField(
help_text='''Number of data points''')
std_error = models.FloatField(blank=True, null=True,
help_text='''Standard error of the mean. Null if can not be calculated''')
src_cd = models.IntegerField(
help_text='''Code indicating type of data''')
deriv_cd = models.CharField(max_length=8, blank=True,
help_text='''Data Derivation Code giving specific information on how the value is determined''')
ref_ndb_no = models.IntegerField(max_length=10, blank=True, null=True,
help_text='''NDB number of the item used to impute a missing value. Populated only for items added or updated starting with SR14''')
add_nutr_mark = models.NullBooleanField(
help_text='''Indicates a vitamin or mineral added for fortification or enrichment. This field is populated for ready-to-eat breakfast cereals and many brand-name hot cereals in food group 8''')
num_studies = models.IntegerField(blank=True, null=True,
help_text='''Number of studies''')
min = models.FloatField(blank=True, null=True,
help_text='''Minimum value''')
max = models.FloatField(blank=True, null=True,
help_text='''Maximum value''')
df = models.IntegerField(blank=True, null=True,
help_text='''Degrees of freedom''')
low_eb = models.FloatField(blank=True, null=True,
help_text='''Lower 95% error bound''')
up_eb = models.FloatField(blank=True, null=True,
help_text='''Upper 95% error bound''')
stat_cmt = models.CharField(max_length=255, blank=True,
help_text='''Statistical comments. See definitions below''')
cc = models.CharField(max_length=2, blank=True,
help_text='''Confidence Code indicating data quality, based on evaluation of sample plan, sample handling, analytical method, analytical quality control, and number of samples analyzed. Not included in this release, but is planned for future releases''')
class Meta:
#unique_together = ('nutrient_def', 'source_code', 'data_derivation', 'data_source_ln')
verbose_name = "nutrient data"
verbose_name_plural = "nutrient data"
def __unicode__(self):
return self.nutrient_def.__unicode__()
def resolve_relations(self, force=False):
# Resolve Relation Fields
resolved = True
# Nutrient Definition
if force or not self.nutrient_def:
try:
self.nutrient_def = NutrientDefinition.objects.get(nutr_no=self.nutr_no)
except NutrientDefinition.DoesNotExist:
resolved = False
# Source Code
if force or not self.source_code:
try:
self.source_code = SourceCode.objects.get(src_cd=self.src_cd)
except SourceCode.DoesNotExist:
resolved = False
# Data Derivation
if force or not self.data_derivation:
try:
self.data_derivation = DataDerivation.objects.get(deriv_cd=self.deriv_cd)
except DataDerivation.DoesNotExist:
resolved = False
# Data Source Link
if force or not self.data_source_ln:
try:
kwargs = { 'ndb_no': self.ndb_no, }
if self.nutr_no:
kwargs['nutr_no'] = self.nutr_no
self.data_source_ln.add(*DataSourceLink.objects.filter(**kwargs))
except DataSourceLink.DoesNotExist:
resolved = False
self.save()
return resolved
class NutrientDefinition(BaseNutritionClass):
# Imported Data Fields
nutr_no = models.IntegerField(unique=True,
help_text='''Unique 3-digit identifier code for a nutrient''')
units = models.CharField(max_length=14,
help_text='''Units of measure (mg, g, ?g, and so on)''')
tagname = models.CharField(max_length=40, blank=True,
help_text='''International Network of Food Data Systems (INFOODS)''')
tagnames = models.CharField(max_length=255,
help_text='''A unique abbreviation for a nutrient/food component developed by INFOODS to aid in the interchange of data NutrDesc A 60 N Name of nutrient/food component''')
num_dec = models.IntegerField(
verbose_name='''number of decimal places''',
help_text='''Number of decimal places to which a nutrient value is rounded''')
sr_order = models.IntegerField(
verbose_name='''sorting order''',
help_text='''Used to sort nutrient records in the same order as various reports produced from SR''')
class Meta:
verbose_name = "nutrient definition"
verbose_name_plural = "nutrient definitions"
def __unicode__(self):
return u"%s" % self.tagnames
class SourceCode(BaseNutritionClass):
# Imported Data Fields
src_cd = models.IntegerField(unique=True,
verbose_name='''code''',
help_text='''2-digit code''')
srccd_desc = models.CharField(max_length=255,
verbose_name='''description''',
help_text='''Description of source code that identifies the type of nutrient data''')
class Meta:
verbose_name = "source code"
verbose_name_plural = "source codes"
def __unicode__(self):
return u"%s" % self.srccd_desc
class DataDerivation(BaseNutritionClass):
# Imported Data Fields
deriv_cd = models.CharField(max_length=8, unique=True,
help_text='''Derivation Code''')
deriv_desc = models.TextField(
help_text='''Description of derivation code giving specific information
on how the value was determined''')
class Meta:
verbose_name = "data derivation"
verbose_name_plural = "data derivations"
def __unicode__(self):
return self.deriv_cd
class Weight(BaseNutritionClass):
# Imported Data Fields
ndb_no = models.IntegerField(
help_text='''5-digit Nutrient Databank number''')
seq = models.IntegerField(
help_text='''Sequence number''')
amount = models.FloatField(
help_text='''Unit modifier (for example, 1 in \u201c1 cup\u201d)''')
msre_desc = models.TextField(
help_text='''Description (for example, cup, diced, and 1-inch pieces)''')
gm_wgt = models.FloatField(
help_text='''Gram weight''')
num_data_pts = models.FloatField(blank=True, null=True,
help_text='''Number of data points''')
std_dev = models.FloatField(blank=True, null=True,
help_text='''Standard deviation''')
class Meta:
unique_together = ('ndb_no', 'seq')
verbose_name = "weight"
verbose_name_plural = "weights"
def __unicode__(self):
return u"%s - %s" % (self.ndb_no, self.msre_desc)
FOOTNOTE_TYPE_CHOICES = (
('D', 'food description'),
('M', 'measure description'),
('N', 'nutrient value'),
)
class Footnote(BaseNutritionClass):
# Relation Fields
nutrient_def = models.ForeignKey('NutrientDefinition', blank=True, null=True,
help_text='''Related via nutr_no''')
# Imported Data Fields
ndb_no = models.IntegerField(
help_text='''5-digit Nutrient Databank number''')
footnt_no = models.IntegerField(blank=True, null=True,
help_text='''Sequence number. If a given footnote applies to more than one nutrient number, the same footnote number is used. As a result, this file cannot be indexed''')
footnt_typ = models.CharField(max_length=1, choices=FOOTNOTE_TYPE_CHOICES,
help_text='''Type of footnote:
D = footnote adding information to the food description;
M = footnote adding information to measure description;
N = footnote providing additional information on a nutrient value. If the Footnt_typ = N, the Nutr_No will also be filled in''')
nutr_no = models.IntegerField(blank=True, null=True,
help_text='''Unique 3-digit identifier code for a nutrient to which footnote applies''')
footnt_txt = models.TextField(
help_text='''Footnote text''')
class Meta:
unique_together = ('ndb_no', 'footnt_no', 'nutr_no')
verbose_name = "footnote"
verbose_name_plural = "footnotes"
def __unicode__(self):
return "%s - %s" % (self.ndb_no, self.footnt_no)
def resolve_relations(self, force=False):
# Resolve Relation Fields
resolved = True
if force or not self.nutrient_def:
try:
self.nutrient_def = NutrientData.objects.get(nutr_no=self.nutr_no)
except NutrientData.DoesNotExist:
resolved = False
self.save()
return resolved
class DataSourceLink(BaseNutritionClass):
# Relation Fields
data_source = models.ForeignKey('DataSource', blank=True, null=True,
help_text='''Related via datasrc_id''')
# Imported Data Fields
ndb_no = models.IntegerField(
help_text='''5-digit Nutrient Databank number''')
nutr_no = models.IntegerField(
help_text='''Unique 3-digit identifier code for a nutrient''')
datasrc_id = models.CharField(max_length=12,
help_text='''Unique ID identifying the reference/source''')
class Meta:
verbose_name = "data source link"
verbose_name_plural = "data source links"
def __unicode__(self):
return u"%s - %s" % (self.ndb_no, self.nutr_no)
def resolve_relations(self, force=False):
# Resolve Relation Fields
resolved = True
if force or not self.data_source:
try:
self.data_source = DataSource.objects.get(datasrc_id=self.datasrc_id)
except DataSource.DoesNotExist:
resolved = False
self.save()
return resolved
class DataSource(BaseNutritionClass):
# Imported Data Fields
datasrc_id = models.CharField(max_length=10, unique=True,
help_text='''Unique number identifying the reference/source''')
authors = models.CharField(max_length=255, blank=True, null=True,
help_text='''List of authors for a journal article or name of sponsoring organization for other documents''')
title = models.CharField(max_length=255, blank=True,
help_text='''Title of article or name of document, such as a report from a company or trade association''')
year = models.IntegerField(max_length=8, blank=True, null=True,
help_text='''Year article or document was published''')
journal = models.CharField(max_length=255, blank=True,
help_text='''Name of the journal in which the article was published''')
vol_city = models.CharField(max_length=255, blank=True,
help_text='''Volume number for journal articles, books, or reports; city where sponsoring organization is located''')
issue_state = models.CharField(max_length=10, blank=True,
help_text='''Issue number for journal article; State where the sponsoring organization is located''')
start_page = models.CharField(max_length=10, blank=True,
help_text='''Starting page number of article/document''')
end_page = models.CharField(max_length=10, blank=True,
help_text='''Ending page number of article/document''')
class Meta:
verbose_name = "data source"
verbose_name_plural = "data sources"
def __unicode__(self):
return self.title | Python |
import os
from csv import DictReader
# Define order of migrations
MIGRATION_TASKS = [
'FD_GROUP', 'DERIV_CD', 'SRC_CD', 'DATA_SRC', 'NUTR_DEF',
'NUT_DATA', 'WEIGHT', 'FOOTNOTE', 'DATSRCLN', 'FOOD_DES',
]
FORM_DICT = {
'DATA_SRC': {
'form_name': 'DataSourceForm',
'fieldnames': [
'datasrc_id', 'authors', 'title', 'year', 'journal', 'vol_city',
'issue_state', 'start_page', 'end_page'
],
},
'DATSRCLN': {
'form_name': 'DataSourceLinkForm',
'fieldnames': ['ndb_no', 'nutr_no', 'datasrc_id'],
},
'DERIV_CD': {
'form_name': 'DataDerivationForm',
'fieldnames': ['deriv_cd', 'deriv_desc'],
},
'FD_GROUP': {
'form_name': 'FoodGroupForm',
'fieldnames': ['fdgrp_cd', 'fdgrp_desc'],
},
'FOOD_DES': {
'form_name': 'FoodDescriptionForm',
'fieldnames': [
'ndb_no', 'fdgrp_cd', 'long_desc', 'shrt_desc', 'comname',
'manufacname', 'survey', 'ref_desc', 'refuse', 'sciname',
'n_factor', 'pro_factor', 'fat_factor', 'cho_factor'
],
},
'FOOTNOTE': {
'form_name': 'FootnoteForm',
'fieldnames': [
'ndb_no', 'footnt_no', 'footnt_typ', 'nutr_no', 'footnt_txt'
],
},
'NUT_DATA': {
'form_name': 'NutrientDataForm',
'fieldnames': [
'ndb_no', 'nutr_no', 'nutr_val', 'num_data_pts', 'std_error',
'src_cd', 'deriv_cd', 'ref_ndb_no', 'add_nutr_mark', 'num_studies',
'min', 'max', 'df', 'low_eb', 'up_eb', 'stat_cmt', 'cc'
],
},
'NUTR_DEF': {
'form_name': 'NutrientDefinitionForm',
'fieldnames': [
'nutr_no', 'units', 'tagname', 'tagnames', 'num_dec', 'sr_order'
],
},
'SRC_CD' : {
'form_name': 'SourceCodeForm',
'fieldnames': ['src_cd', 'srccd_desc'],
},
'WEIGHT' : {
'form_name': 'WeightForm',
'fieldnames': [
'ndb_no', 'seq', 'amount', 'msre_desc', 'gm_wgt', 'num_data_pts',
'std_dev'
],
},
}
class ARSReader:
"""
A CSV reader which will iterate over lines in given file ``f``, which
should be one of the 10 ASCII nutritional data files from the
`USDA National Nutrient Database for Standard Reference` dataset, which
can be obtained here:
http://www.ars.usda.gov/Services/docs.htm?docid=17478
"""
def __init__(self, file_name, fieldnames, encoding='latin-1', start=0, end=None, **kwargs):
self.reader = DictReader(open(file_name, "r"), fieldnames, delimiter="^", quotechar='~', **kwargs)
self.encoding = encoding
try:
self.start = int(start)
except TypeError:
self.start = 0
try:
self.end = int(end)
except TypeError:
self.end = None
def next(self):
while self.reader.reader.line_num < self.start:
self.reader.next()
if self.end and self.reader.reader.line_num >= self.end:
raise StopIteration
row = self.reader.next()
for k,v in row.items():
row[k] = unicode(v.rstrip('~').lstrip('~'), self.encoding)
return row
def count(self):
return sum(1 for row in self)
def __iter__(self):
return self
def dynamic_import(name):
'''This function allows you to dynamically import a module given a string
corresponding to it's normal import command.
e.g. Nutrition app's forms
>>> dynamic_import('nutrition.forms')
'''
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod | Python |
from django.contrib import admin
from nutrition.models import FoodDescription, FoodGroup, NutrientData
from nutrition.models import NutrientDefinition, SourceCode, DataDerivation
from nutrition.models import Weight, Footnote, DataSourceLink, DataSource
class FoodDescriptionAdmin(admin.ModelAdmin):
raw_id_fields = ('food_group', 'nutrient_data', 'weight', 'footnote')
search_fields = ('long_desc', 'shrt_desc', 'comname', 'manufacname', 'ref_desc', 'sciname')
ordering = ('long_desc', )
class FoodGroupAdmin(admin.ModelAdmin):
list_display = ('fdgrp_cd', 'fdgrp_desc')
ordering = ('fdgrp_cd', )
search_fields = ('fdgrp_desc', )
class NutrientDataAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'nutr_no', 'data_derivation', 'num_studies', 'num_data_pts', 'std_error')
list_filter = ('data_derivation', )
ordering = ('ndb_no', )
raw_id_fields = ('nutrient_def', 'source_code', 'data_derivation', 'data_source_ln')
class NutrientDefinitionAdmin(admin.ModelAdmin):
list_display = ('sr_order', '__unicode__', 'units')
list_filter = ('units', )
ordering = ('sr_order', )
search_fields = ('tagname', 'tagnames')
class SourceAdmin(admin.ModelAdmin):
search_fields = ('srccd_desc', )
class DataDerivationAdmin(admin.ModelAdmin):
list_display = ('deriv_cd', 'deriv_desc')
ordering = ('deriv_cd', )
search_fields = ('deriv_desc', )
class DataSourceAdmin(admin.ModelAdmin):
list_display = ('authors', 'title', 'year')
ordering = ('authors', 'title', 'year')
search_fields = ('authors', 'title', 'year', 'journal', 'vol_city')
admin.site.register(FoodDescription, FoodDescriptionAdmin)
admin.site.register(FoodGroup, FoodGroupAdmin)
admin.site.register(NutrientData, NutrientDataAdmin)
admin.site.register(NutrientDefinition, NutrientDefinitionAdmin)
admin.site.register(SourceCode, SourceAdmin)
admin.site.register(DataDerivation, DataDerivationAdmin)
admin.site.register(Weight)
admin.site.register(Footnote)
admin.site.register(DataSourceLink)
admin.site.register(DataSource, DataSourceAdmin) | Python |
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError
from django.core import serializers
from django.utils.datastructures import SortedDict
from optparse import make_option
import os, subprocess
from nutrition.migration import dynamic_import, FORM_DICT, MIGRATION_TASKS
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--key', default='', dest='key', type='str',
help='Specifies the key of the corresponding csv file.'),
make_option('--start', default=0, dest='start', type='int',
help='Specifies the starting row of the csv file.'),
make_option('--end', default=None, dest='end', type='int',
help='Specifies the ending row of the csv file'),
make_option('--threshold', default=2000, dest='THRESHOLD', type='int',
help='Specifies the maximum number of rows for a individual process to handle.'),
make_option('-f', action="store_true", dest="force",
help='Specifies the maximum number of rows for a individual process to handle.'),
)
help = 'Resolve relationships of the imported data from the sr21 USDA National Nutrient Database.'
def handle(self, **options):
key = options.get('key', None)
start = options.get('start', 0)
end = options.get('end', None)
THRESHOLD = options.get('THRESHOLD', 2000)
force = options.get('force', False)
PWD = os.environ['PWD']
if key:
if key not in FORM_DICT.keys():
raise CommandError("Invalid key specified. Key choices are: %s" % FORM_DICT.keys())
value = FORM_DICT[key]
# Dynamically import the corresponding module and get the Form attribute
module = dynamic_import('nutrition.forms')
form = getattr(module, value['form_name'])
# If an end value is provided, ignore the total count
if end:
length = end - start
else:
# Determine a row count from the total objects
count = form._meta.model.objects.count()
length = count - start
if length > THRESHOLD:
num_segments = int(round(length / THRESHOLD))
command_set = []
for multiplier in range(0, num_segments + 1):
cmd = [
PWD + '/manage.py',
'resolve_sr21',
'--key=%s' % key,
'--start=%s' % (int(start) + THRESHOLD * multiplier),
'--end=%s' % (int(start) + THRESHOLD * (multiplier + 1)),
'--threshold=%s' % THRESHOLD,
]
if force:
cmd.append('-f')
command_set.append(cmd)
#print command_set
for cmd in command_set:
p = subprocess.Popen(cmd)
p.wait()
else:
failures = sum(not obj.resolve_relations(force) for obj in form._meta.model.objects.all()[start:(end or count)])
if failures:
print "%s out of %s unresolved objects" % (failures, length)
else:
for source in MIGRATION_TASKS:
print "%s working..." % source
cmd = [
PWD + '/manage.py',
'resolve_sr21',
'--key=%s' % source,
'--threshold=%s' % THRESHOLD,
]
if force:
cmd.append('-f')
p = subprocess.Popen(cmd)
p.wait()
print "%s complete" % source | Python |
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError
from django.core import serializers
from django.utils.datastructures import SortedDict
from optparse import make_option
import os, subprocess
from nutrition.migration import dynamic_import, ARSReader, FORM_DICT, MIGRATION_TASKS
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--key', default='', dest='key', type='str',
help='Specifies the key of the corresponding csv file.'),
make_option('--start', default=0, dest='start', type='int',
help='Specifies the starting row of the csv file.'),
make_option('--end', default=None, dest='end', type='int',
help='Specifies the ending row of the csv file'),
make_option('--encoding', default='latin-1', dest='encoding', type='str',
help='Specifies the csv file encoding.'),
make_option('--threshold', default=10000, dest='THRESHOLD', type='int',
help='Specifies the maximum number of rows for a individual process to handle.'),
)
help = 'Import all or part of the sr21 USDA National Nutrient Database.'
args = '[sr21 dataset directory]'
def handle(self, path, **options):
if not os.path.exists(path):
raise CommandError("The path %s does not exist." % path)
key = options.get('key', None)
start = options.get('start', 0)
end = options.get('end', None)
encoding = options.get('encoding', 'latin-1')
THRESHOLD = options.get('THRESHOLD', 10000)
PWD = os.environ['PWD']
if key:
if key not in FORM_DICT.keys():
raise CommandError("Invalid key specified. Key choices are: %s" % FORM_DICT.keys())
value = FORM_DICT[key]
# Dynamically import the corresponding module and get the Form attribute
module = dynamic_import('nutrition.forms')
form = getattr(module, value['form_name'])
# Ensure that the path ends with a trailing slash
path = path.rstrip('/') + '/'
file_path = path + key + '.txt'
if not os.path.exists(file_path):
raise CommandError("The file %s does not exist. Please make sure you leave the extracted sr21 dataset untouched." % file_path)
# Set the fieldnames to a var
fieldnames = value['fieldnames']
# If an end value is provided, check the length before
# counting the rows
if end:
length = end - start
else:
# Open a sanitizing DictReader on the current key
reader = ARSReader(file_path, fieldnames, encoding, start, end)
# Determine a row count and delete the reader
row_count = reader.count()
del reader
length = row_count - start
if length > THRESHOLD:
num_segments = int(round(length / THRESHOLD))
command_set = []
for multiplier in range(0, num_segments + 1):
cmd = [
PWD + '/manage.py',
'import_sr21',
path,
'--key=%s' % key,
'--start=%s' % (int(start) + THRESHOLD * multiplier),
'--end=%s' % (int(start) + THRESHOLD * (multiplier + 1)),
'--threshold=%s' % THRESHOLD,
]
command_set.append(cmd)
for cmd in command_set:
p = subprocess.Popen(cmd)
p.wait()
else:
# Open a sanitizing DictReader on the current key
reader = ARSReader(file_path, fieldnames, encoding, start, end)
print start, end
for row in reader:
populated_form = form(data=row)
obj = populated_form.save(commit=False)
obj.save()
else:
for source in MIGRATION_TASKS:
print "%s working..." % source
cmd = [
PWD + '/manage.py',
'import_sr21',
path,
'--key=%s' % source,
'--threshold=%s' % THRESHOLD,
]
p = subprocess.Popen(cmd)
p.wait()
print "%s complete" % source | Python |
from distutils.core import setup
import os
# Compile the list of packages available, because distutils doesn't have
# an easy way to do this.
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
if root_dir:
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.walk('nutrition'):
# Ignore dirnames that start with '.'
for i, dirname in enumerate(dirnames):
if dirname.startswith('.'): del dirnames[i]
if '__init__.py' in filenames:
pkg = dirpath.replace(os.path.sep, '.')
if os.path.altsep:
pkg = pkg.replace(os.path.altsep, '.')
packages.append(pkg)
elif filenames:
prefix = dirpath[13:] # Strip "nutrition/" or "nutrition\"
for f in filenames:
data_files.append(os.path.join(prefix, f))
setup(name='django-nutrition',
version='0.1',
description='An application providing the data structure of and import script for the USDA National Nutrient Database for Standard Reference data set SR21 for Django',
author='David Martin',
author_email='dave.robert.martin@gmail.com',
url='http://code.google.com/p/django-nutrition/',
download_url='http://code.google.com/p/django-nutrition/source/checkout',
package_dir={'nutrition': 'nutrition'},
packages=packages,
package_data={'nutrition': data_files},
classifiers=['Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'],
) | 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 os
import sha
import time
import Cookie
COOKIE_NAME = 'vikuit'
class Session(object):
def __init__(self, seed):
self.time = None
self.user = None
self.auth = None
self.seed = seed
def load(self):
string_cookie = os.environ.get('HTTP_COOKIE', '')
string_cookie = string_cookie.replace(';', ':') # for old sessions
self.cookie = Cookie.SimpleCookie()
self.cookie.load(string_cookie)
if self.cookie.get(COOKIE_NAME):
value = self.cookie[COOKIE_NAME].value
tokens = value.split(':')
if len(tokens) != 3:
return False
else:
h = tokens[2]
tokens = tokens[:-1]
tokens.append(self.seed)
if h == self.hash(tokens):
self.time = tokens[0]
self.user = tokens[1]
self.auth = h
try:
t = int(self.time)
except:
return False
if t > int(time.time()):
return True
return False
def store(self, user, expire):
self.time = str(int(time.time())+expire)
self.user = user
params = [self.time, self.user, self.seed]
self.auth = self.hash(params)
params = [self.time, self.user, self.auth]
self.cookie[COOKIE_NAME] = ':'.join(params)
self.cookie[COOKIE_NAME]['expires'] = expire
self.cookie[COOKIE_NAME]['path'] = '/'
print 'Set-Cookie: %s; HttpOnly' % (self.cookie.output().split(':', 1)[1].strip())
def hash(self, params):
return sha.new(';'.join(params)).hexdigest()
"""
def __str__(self):
params = [self.time, self.user, self.auth]
self.cookie[COOKIE_NAME] = ':'.join(params)
self.cookie[COOKIE_NAME]['path'] = '/'
return self.cookie.output()
s = Session('1234')
s.load()
if s.load():
print s.auth
print s.user
s.store('anabel', 3200)
""" | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Ignacio Andreu <plunchete 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 simplejson
import model
from google.appengine.api import memcache
from google.appengine.ext import webapp
class BaseRest(webapp.RequestHandler):
def render_json(self, data):
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))
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Ignacio Andreu <plunchete 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 SearchResult(BaseHandler):
def execute(self):
self.render('templates/search-result.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete 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 Static(BaseHandler):
def execute(self):
template = self.request.path.split('/', 2)[2]
self.render('templates/static/%s' % template) | 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 BaseHandler
class NotFound(BaseHandler):
def execute(self):
self.not_found() | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (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.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext.webapp import template
from handlers.BaseHandler import *
from utilities.AppProperties import AppProperties
# Params
UPDATER_VERSION = "0.8"
def update():
app = model.Application.all().get()
if app is None:
initializeDb()
#self.response.out.write('App installed. Created user administrator. nickname="admin", password="1234". Please change the password.')
return
elif not app.session_seed:
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.put()
#self.response.out.write('Seed installed')
version = app.version
if version is None or version != UPDATER_VERSION:
update07to08()
#self.response.out.write ('updated to version 0.8')
# elif app.version == '0.8':
# update08to09()
# elif app.version == '0.9':
# update09to10()
return
def initializeDb():
app = model.Application.all().get()
if app is None:
app = model.Application()
app.name = 'vikuit-example'
app.subject = 'Social portal: lightweight and easy to install'
app.recaptcha_public_key = '6LdORAMAAAAAAL42zaVvAyYeoOowf4V85ETg0_h-'
app.recaptcha_private_key = '6LdORAMAAAAAAGS9WvIBg5d7kwOBNaNpqwKXllMQ'
app.theme = 'blackbook'
app.users = 0
app.communities = 0
app.articles = 0
app.threads = 0
app.url = "http://localhost:8080"
app.mail_subject_prefix = "[Vikuit]"
app.mail_sender = "admin.example@vikuit.com"
app.mail_footer = ""
app.max_results = 20
app.max_results_sublist = 20
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.version = UPDATER_VERSION
app.put()
user = model.UserData(nickname='admin',
email='admin.example@vikuit.com',
password='1:c07cbf8821d47575a471c1606a56b79e5f6e6a68',
language='en',
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,
rol='admin')
user.put()
parent_category = model.Category(title='General',
description='General category description',
articles = 0,
communities = 0)
parent_category.put()
category = model.Category(title='News',
description='News description',
articles = 0,
communities = 0)
category.parent_category = parent_category
category.put()
post = model.Mblog(author=user,
author_nickname=user.nickname,
content='Welcome to Vikuit!!',
responses=0)
post.put()
# update from 0.7 to 0.8 release
def update07to08():
app = model.Application.all().get()
app.theme = 'blackbook'
app.version = '0.8'
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
return
# update from 0.8 to 0.9 release
def update08to09():
app = model.Application.all().get()
app.version = '0.9'
app.put()
# update from 0.9 to 01 release
def update09to10():
app = model.Application.all().get()
app.version = '1.0'
app.put()
| 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 google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from handlers.BaseHandler import *
class Initialization(BaseHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
app = model.Application.all().get()
if app is None:
populateDB()
self.response.out.write('App installed. Created user administrator. nickname="admin", password="1234". Please change the password.')
return
elif not app.session_seed:
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.put()
self.response.out.write('Seed installed')
return
p = int(self.request.get('p'))
key = self.request.get('key')
action = self.request.get('action')
if key:
community = model.Community.get(key)
if not community:
self.response.out.write('community not found')
return
offset = (p-1)*10
if action == 'gi':
i = self.community_articles(community, offset)
elif action == 'gu':
i = self.community_users(community, offset)
elif action == 'th':
i = self.threads(offset)
elif action == 'cc':
i = self.contacts(offset)
elif action == 'fv':
i = self.favourites(offset)
elif action == 'sg':
i = self.show_communities(offset)
return
elif action == 'ut':
i = self.update_threads(offset)
elif action == 'uis':
i = self.update_article_subscription(p-1)
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action))
return
elif action == 'ugs':
i = self.update_community_subscription(community, offset)
elif action == 'uts':
i = self.update_thread_subscription(p-1)
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action))
return
elif action == 'ugc':
i = self.update_community_counters(p-1)
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action))
return
elif action == 'adus':
i = self.add_date_user_subscription(offset)
elif action == 'afg':
i = self.add_follower_community(offset)
elif action == 'afu':
i = self.add_follower_user(offset)
elif action == 'afi':
i = self.add_follower_article(offset)
elif action == 'aft':
i = self.add_follower_thread(offset)
else:
self.response.out.write('unknown action -%s-' % action)
return
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (offset, i[0], i[1], action))
def community_articles(self, community, offset):
i = offset
p = 0
for gi in model.CommunityArticle.all().filter('community', community).order('-creation_date').fetch(10, offset):
if not gi.community_title:
article = gi.article
community = gi.community
gi.article_author_nickname = article.author_nickname
gi.article_title = article.title
gi.article_url_path = article.url_path
gi.community_title = community.title
gi.community_url_path = community.url_path
gi.put()
p += 1
i+=1
return (i, p)
def community_users(self, community, offset):
i = offset
p = 0
for gu in model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(10, offset):
if not gu.community_title:
user = gu.user
community = gu.community
gu.user_nickname = gu.user.nickname
gu.community_title = community.title
gu.community_url_path = community.url_path
gu.put()
p += 1
i+=1
return (i, p)
def threads(self, offset):
i = offset
p = 0
for th in model.Thread.all().order('-creation_date').fetch(10, offset):
if not th.community_title:
community = th.community
th.community_title = community.title
th.community_url_path = community.url_path
if not th.url_path:
th.url_path = th.parent_thread.url_path
th.put()
p += 1
i+=1
return (i, p)
def contacts(self, offset):
i = offset
p = 0
for cc in model.Contact.all().order('-creation_date').fetch(10, offset):
if not cc.user_from_nickname:
cc.user_from_nickname = cc.user_from.nickname
cc.user_to_nickname = cc.user_to.nickname
cc.put()
p += 1
i+=1
return (i, p)
def favourites(self, offset):
i = offset
p = 0
for fv in model.Favourite.all().order('-creation_date').fetch(10, offset):
if not fv.user_nickname:
article = fv.article
fv.article_author_nickname = article.author_nickname
fv.article_title = article.title
fv.article_url_path = article.url_path
fv.user_nickname = fv.user.nickname
fv.put()
p += 1
i+=1
return (i, p)
def show_communities(self, offset):
for g in model.Community.all().order('-creation_date').fetch(10, offset):
self.response.out.write("('%s', '%s', %d),\n" % (g.title, str(g.key()), g.members))
def update_threads(self, offset):
i = offset
p = 0
for th in model.Thread.all().filter('parent_thread', None).order('-creation_date').fetch(10, offset):
if th.views is None:
th.views = 0
th.put()
p += 1
i+=1
return (i, p)
def update_article_subscription(self, offset):
i = offset
p = 0
for article in model.Article.all().order('-creation_date').fetch(1, offset):
if article.subscribers:
for subscriber in article.subscribers:
user = model.UserData.all().filter('email', subscriber).get()
if not model.UserSubscription.all().filter('user', user).filter('subscription_type', 'article').filter('subscription_id', article.key().id()).get():
self.add_user_subscription(user, 'article', article.key().id())
p += 1
i+=1
return (i, p)
def update_community_subscription(self, community, offset):
i = offset
p = 0
for community_user in model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(10, offset):
if not model.UserSubscription.all().filter('user', community_user.user).filter('subscription_type', 'community').filter('subscription_id', community.key().id()).get():
self.add_user_subscription(community_user.user, 'community', community.key().id())
p += 1
i += 1
return (i, p)
def update_thread_subscription(self, offset):
i = offset
p = 0
for thread in model.Thread.all().filter('parent_thread', None).order('-creation_date').fetch(1, offset):
if thread.subscribers:
for subscriber in thread.subscribers:
user = model.UserData.all().filter('email', subscriber).get()
if not model.UserSubscription.all().filter('user', user).filter('subscription_type', 'thread').filter('subscription_id', thread.key().id()).get():
self.add_user_subscription(user, 'thread', thread.key().id())
p += 1
i+=1
return (i, p)
def update_community_counters(self, offset):
i = offset
p = 0
for community in model.Community.all().order('-creation_date').fetch(1, offset):
users = model.CommunityUser.all().filter('community', community).count()
articles = model.CommunityArticle.all().filter('community', community).count()
community_threads = model.Thread.all().filter('community', community).filter('parent_thread', None)
threads = community_threads.count()
comments = 0
for thread in community_threads:
comments += model.Thread.all().filter('community', community).filter('parent_thread', thread).count()
if community.members != users or community.articles != articles or community.threads != threads or community.responses != comments:
community.members = users
community.articles = articles
community.threads = threads
community.responses = comments
p += 1
if not community.activity:
community.activity = 0
community.activity = (community.members * 1) + (community.threads * 5) + (community.articles * 15) + (community.responses * 2)
community.put()
i += 1
return (i, p)
def add_date_user_subscription(self, offset):
i = offset
p = 0
for user_subscription in model.UserSubscription.all().fetch(10, offset):
if user_subscription.creation_date is None:
user_subscription.creation_date = datetime.datetime.now()
user_subscription.put()
p += 1
i += 1
return (i, p)
def add_follower_community(self, offset):
i = offset
p = 0
for community_user in model.CommunityUser.all().fetch(10, offset):
if community_user.user_nickname is None:
self.desnormalizate_community_user(community_user)
self.add_follower(community=community_user, nickname=community_user.user_nickname)
p +=1
i += 1
return(i,p)
def add_follower_user(self, offset):
i = offset
p = 0
for cc in model.Contact.all().fetch(10, offset):
if cc.user_from_nickname is None:
self.desnormalizate_user_contact(cc)
self.add_follower(user=cc.user_to, nickname=cc.user_from_nickname)
p += 1
i += 1
return(i,p)
def add_follower_article(self, offset):
i = offset
p = 0
for article in model.Article.all().filter('deletion_date', None).filter('draft', False).fetch(10, offset):
self.add_follower(article=article, nickname=article.author_nickname)
p += 1
i += 1
return(i,p)
def add_follower_thread(self, offset):
i = offset
p = 0
for t in model.Thread.all().filter('parent_thread', None).fetch(10, offset):
self.add_follower(thread=t, nickname=t.author_nickname)
p += 1
i += 1
return(i, p)
def desnormalizate_community_user(self, gu):
user = gu.user
community = gu.community
gu.user_nickname = gu.user.nickname
gu.community_title = community.title
gu.community_url_path = community.url_path
gu.put()
def desnormalizate_user_contact(self, cc):
cc.user_from_nickname = cc.user_from.nickname
cc.user_to_nickname = cc.user_to.nickname
cc.put()
def populateDB():
app = model.Application.all().get()
if app is None:
app = model.Application()
app.name = 'vikuit-example'
app.subject = 'Social portal: lightweight and easy to install'
app.recaptcha_public_key = '6LdORAMAAAAAAL42zaVvAyYeoOowf4V85ETg0_h-'
app.recaptcha_private_key = '6LdORAMAAAAAAGS9WvIBg5d7kwOBNaNpqwKXllMQ'
app.theme = 'blackbook'
app.users = 0
app.communities = 0
app.articles = 0
app.threads = 0
app.url = "http://localhost:8080"
app.mail_subject_prefix = "[Vikuit]"
app.mail_sender = "admin.example@vikuit.com"
app.mail_footer = ""
app.max_results = 20
app.max_results_sublist = 20
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.put()
user = model.UserData(nickname='admin',
email='admin.example@vikuit.com',
password='1:c07cbf8821d47575a471c1606a56b79e5f6e6a68',
language='en',
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,
rol='admin')
user.put()
parent_category = model.Category(title='General',
description='General category description',
articles = 0,
communities = 0)
parent_category.put()
category = model.Category(title='News',
description='News description',
articles = 0,
communities = 0)
category.parent_category = parent_category
category.put()
post = model.Mblog(author=user,
author_nickname=user.nickname,
content='Welcome to Vikuit!!',
responses=0)
post.put()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete 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 Tag(BaseHandler):
def execute(self):
tag = self.request.path.split('/', 2)[2]
query = model.Article.all().filter('tags =', tag).filter('draft', False).filter('deletion_date', None).order('-creation_date')
self.values['articles'] = self.paging(query, 10)
self.add_tag_cloud()
self.values['tag'] = tag
self.render('templates/tag.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 *
class AuthenticatedHandler(BaseHandler):
def pre_execute(self):
user = self.get_current_user()
#user = self.values['user']
if not user:
self.redirect(self.values['login'])
return
self.execute() | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete 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 ForumList(BaseHandler):
def execute(self):
self.values['tab'] = '/forum.list'
query = model.Thread.all().filter('parent_thread', None)
app = self.get_application()
key = '%s?%s' % (self.request.path, self.request.query)
results = 10
if app.max_results:
results = app.max_results
threads = self.paging(query, results, '-last_response_date', app.threads, ['-last_response_date'], key)
# migration
for t in threads:
if not t.last_response_date:
last_response = model.Thread.all().filter('parent_thread', t).order('-creation_date').get()
if last_response:
t.last_response_date = last_response.creation_date
else:
t.last_response_date = t.creation_date
t.put()
# end migration
self.values['threads'] = threads
self.add_tag_cloud()
self.render('templates/forum-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 model
import logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
class ImageDisplayer(webapp.RequestHandler):
def get(self):
cached = memcache.get(self.request.path)
params = self.request.path.split('/')
if params[2] == 'user':
user = model.UserData.gql('WHERE nickname=:1', params[4]).get()
self.display_image(user, params, cached, 'user128_1.png', 'user48_1.png')
elif params[2] == 'community':
community = model.Community.get_by_id(int(params[4]))
self.display_image(community, params, cached, 'community128.png', 'community48.png')
elif params[2] == 'gallery':
query = model.Image.gql('WHERE url_path=:1', '%s/%s' % (params[4], params[5]) )
image = query.get()
self.display_image(image, params, cached, 'unknown128.png', 'unknown48.png', False)
elif params[2] == 'application':
app = model.Application.all().get()
image = app.logo
self.display_image(image, params, cached, 'logo.gif', 'logo.gif', False)
else:
self.error(404)
return
def display_image(self, obj, params, cached, default_avatar, default_thumbnail, not_gallery=True):
if obj is None:
if not_gallery:
self.error(404)
else:
self.redirect('/static/images/%s' % default_thumbnail)
return
image = None
if cached:
image = self.write_image(cached)
else:
if params[3] == 'avatar':
image = obj.avatar
if not image:
self.redirect('/static/images/%s' % default_avatar)
return
elif params[3] == 'thumbnail':
image = obj.thumbnail
if not image:
self.redirect('/static/images/%s' % default_thumbnail)
return
elif params[3] == 'logo':
image = obj
if not image:
self.redirect('/static/images/%s' % default_thumbnail)
return
if not_gallery and (len(params) == 5 or not obj.image_version or int(params[5]) != obj.image_version):
if not obj.image_version:
obj.image_version = 1
obj.put()
newparams = params[:5]
newparams.append(str(obj.image_version))
self.redirect('/'.join(newparams))
return
# self.response.headers['Content-Type'] = 'text/plain'
# self.response.out.write('/'.join(params))
else:
if not cached:
memcache.add(self.request.path, image)
self.write_image(image)
def write_image(self, image):
self.response.headers['Content-Type'] = 'image/jpg'
self.response.headers['Cache-Control'] = 'public, max-age=31536000'
self.response.out.write(image)
def showImage(self, image, default):
if image:
self.write_image(image)
memcache.add(self.request.path, image)
else:
self.redirect('/static/images/%s' % default) | 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 logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
from handlers.BaseHandler import BaseHandler
class ImageBrowser(BaseHandler):
def execute(self):
user = self.values['user']
#TODO PAGINATE
if user:
list = ""
if user.rol == 'admin':
images = model.Image.all()
else:
images = model.Image.gql('WHERE author_nickname=:1', user.nickname)
self.values['images'] = images
self.render('templates/editor/browse.html')
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
import os
import model
import logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
from handlers.AuthenticatedHandler import AuthenticatedHandler
class ImageUploader(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
if method == 'GET':#Request identifies actions
action = self.get_param('act')
url_path = self.get_param('url')
query = model.Image.gql('WHERE url_path=:1', url_path )
image = query.get()
if not image:
self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') })
elif user.nickname != image.author_nickname and user.rol != 'admin':
self.render_json({ 'saved': False, 'msg': self.getLocale('Not allowed') })
elif action == 'del': #delete image
image.delete()
self.render_json({ 'saved': True })
else:
self.render_json({ 'saved': False })
else:#File upload
# Get the uploaded file from request.
upload = self.request.get("upload")
nick = user.nickname
dt = datetime.datetime.now()
prnt = dt.strftime("%Y%m%d%H%M%S")
url_path = nick +"/"+ prnt
try:
query = model.Image.all(keys_only=True).filter('url_path', url_path)
entity = query.get()
if entity:
raise Exception('unique_property must have a unique value!')
image = model.Image(author=user,
author_nickname=nick,
thumbnail=upload,
url_path=url_path)
image.put()
self.values["label"] = self.getLocale("Uploaded as: %s") % url_path
except:
self.values["label"] = self.getLocale('Error saving image')
self.render("/translator-util.html")
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 time
import model
import datetime
import markdown
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from time import strftime, gmtime, time
from utilities.AppProperties import AppProperties
class Feed(webapp.RequestHandler):
def get(self):
data = memcache.get(self.request.path)
if not data:
time = 600
params = self.request.path.split('/', 4)
if not params[2]:
latest = model.Article.gql('WHERE draft=:1 AND deletion_date=:2 ORDER BY creation_date DESC LIMIT 20', False, None)
data = self.to_rss(self.get_application().name, latest)
elif params[2] == 'mblog':
query = model.Mblog.all().filter('deletion_date', None).order('-creation_date')
latest = [o for o in query.fetch(25)]
data = self.posts_to_rss(self.getLocale("Microbblogging"), latest)
time = 200
elif params[2] == 'tag':
query = model.Article.all().filter('deletion_date', None).filter('tags =', params[3]).order('-creation_date')
latest = [o for o in query.fetch(10)]
data = self.to_rss(self.getLocale("Articles labeled with %s") % params[3], latest)
elif params[3] == 'community.forum':
community = model.Community.gql('WHERE url_path=:1',params[4]).get()
if not community:
community = model.Community.gql('WHERE old_url_path=:1',params[4]).get()
threads = model.Thread.gql('WHERE community=:1 ORDER BY creation_date DESC LIMIT 20', community)
data = self.threads_to_rss(self.getLocale("Forum %s") % community.title, threads)
elif params[3] == 'community':
community = model.Community.gql('WHERE url_path=:1',params[4]).get()
if not community:
community = model.Community.gql('WHERE old_url_path=:1',params[4]).get()
community_articles = model.CommunityArticle.gql('WHERE community=:1 ORDER BY creation_date DESC LIMIT 20', community)
latest = [gi.article for gi in community_articles]
data = self.to_rss(self.getLocale("Articles by community %s") % community.title, latest)
elif params[3] == 'user':
latest = model.Article.gql('WHERE author_nickname=:1 AND draft=:2 AND deletion_date=:3 ORDER BY creation_date DESC LIMIT 20', params[4], False, None)
data = self.to_rss(self.getLocale("Articles by %s") % params[3], latest)
else:
data = self.not_found()
memcache.add(self.request.path, data, time)
self.response.headers['Content-Type'] = 'application/rss+xml'
self.response.out.write(template.render('templates/feed.xml', data))
def threads_to_rss(self, title, threads):
articles = []
url = self.get_application().url
md = markdown.Markdown()
for i in threads:
article = {
'title': i.title,
'link': "%s/module/community.forum/%s" % (url, i.url_path),
'description': md.convert(i.content),
'pubDate': self.to_rfc822(i.creation_date),
'guid':"%s/module/community.forum/%s" % (url,i.url_path),
'author': i.author_nickname
# guid como link para mantener compatibilidad con feed.xml
}
articles.append(article)
values = {
'title': title,
'self': url+self.request.path,
'link': url,
'description': '',
'articles': articles
}
return values
def posts_to_rss(self, title, list):
posts = []
url = self.get_application().url
for i in list:
post = {
'title': "%s" % i.content,
'link': "%s/module/mblog.edit/%s" % (url, i.key().id()),
'description': "%s" % i.content,
'pubDate': self.to_rfc822(i.creation_date),
'guid':"%s/module/mblog.edit/%s" % (url,i.key().id()),
'author': i.author_nickname
}
posts.append(post)
values = {
'title': title,
'self': url+self.request.path,
'link': url,
'description': '%s Microbblogging' % self.get_application().name,
'articles': posts
}
return values
def to_rss(self, title, latest):
import MediaContentFilters as contents
articles = []
url = self.get_application().url
md = markdown.Markdown()
for i in latest:
if i.author.not_full_rss:
content = md.convert(i.description)
else:
content = md.convert(i.content)
content = contents.media_content(content)
article = {
'title': i.title,
'link': "%s/module/article/%s" % (url, i.url_path),
'description': content,
'pubDate': self.to_rfc822(i.creation_date),
'guid':"%s/module/article/%d/" % (url, i.key().id()),
'author': i.author_nickname
}
articles.append(article)
values = {
'title': title,
'self': url+self.request.path,
'link': url,
'description': '',
'articles': articles
}
return values
def to_rfc822(self, date):
return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
def get_application(self):
app = memcache.get('app')
import logging
if not app:
app = model.Application.all().get()
memcache.add('app', app, 0)
return app
def not_found(self):
url = self.get_application().url
values = {
'title': self.get_application().name,
'self': url,
'link': url,
'description': '',
'articles': ''
}
return values
### i18n
def getLocale(self, label):
env = AppProperties().getJinjaEnv()
t = env.get_template("/translator-util.html")
return t.render({"label": label})
| 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.api import mail
from google.appengine.ext import db
from handlers.BaseHandler import *
import re
class Invite(BaseHandler):
def execute(self):
user = self.values['user']
method = self.request.method
app = self.get_application()
if not user:
self.redirect('/module/user.login')
if method == 'GET':
#u"""Te invito a visitar %s, %s.\n %s
self.values['personalmessage'] = self.getLocale("Let me invite you to visit %s, %s. %s") % (app.name, app.subject, app.url)
self.render('templates/invite-friends.html')
return
elif self.auth():
contacts = self.get_param('contacts').replace(' ','')
contacts = contacts.rsplit(',',19)
if contacts[0]=='' or not contacts:
self.values['failed']=True
self.render('templates/invite-friends.html')
return
self.values['_users'] = []
invitations = []
for contact in contacts:
#FIXME inform the user about bad formed mails
if re.match('\S+@\S+\.\S+', contact):
u = model.UserData.gql('WHERE email=:1', contact).get()
if u:
self.values['_users'].append(u)
else:
invitations.append(contact)
personalmessage = self.get_param('personalmessage')
subject = self.getLocale("%s invites you to participate in %s") % (user.nickname, app.name)
body = self.getLocale("Let me invite you to visit %s, %s. %s") % (app.name, app.subject, app.url)
if personalmessage:
body = u"%s \n\n\n\n\t %s" % (self.clean_ascii(personalmessage), self.get_application().url)
self.mail(subject=subject, body=body, bcc=invitations)
self.values['sent'] = True
self.values['invitations'] = invitations
self.render('templates/invite-friends.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Néstor Salceda <nestor.salceda at gmail dot com>
# (C) Copyright 2008 Alberto Gimeno <gimenete 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 model
from google.appengine.api import mail
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import webapp
class MailQueue(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
n = 10
next = model.MailQueue.all().get()
sent = None
if not next:
self.response.out.write('No pending mail')
return
if not next.bcc and not next.to:
self.response.out.write('email without recipients')
next.delete()
return
if next.bcc:
bcc = next.bcc[:n]
del next.bcc[:n]
sent = self.send_mail(next, bcc=bcc)
elif next.to:
to = next.to[:n]
del next.to[:n]
sent = self.send_mail(next, to=to)
if not sent:
self.response.out.write('error. Mail was not sent')
return
if next.bcc or next.to:
next.put()
self.response.out.write('mail sent, something pending')
else:
next.delete()
self.response.out.write('mail sent, mail queue deleted')
def send_mail(self, queue, bcc=[], to=[]):
app = model.Application.all().get()
message = mail.EmailMessage(sender=app.mail_sender,
subject=queue.subject, body=queue.body)
if not to:
to = app.mail_sender
message.to = to
if bcc:
message.bcc = bcc
try:
message.send()
except apiproxy_errors.OverQuotaError, message:
return False
return True
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete 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 model
import simplejson
from google.appengine.ext import webapp
class TaskQueue(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain;charset=utf-8'
task = model.Task.all().order('-priority').get()
if not task:
self.response.out.write('No pending tasks')
return
data = simplejson.loads(task.data)
data = self.__class__.__dict__[task.task_type].__call__(self, data)
if data is None:
self.response.out.write('Task finished %s %s' % (task.task_type, task.data))
task.delete()
else:
task.data = simplejson.dumps(data)
task.put()
self.response.out.write('Task executed but not finished %s %s' % (task.task_type, task.data))
def delete_recommendations(self, data):
offset = data['offset']
recs = model.Recommendation.all().fetch(1, offset)
if len(recs) == 0:
return None
next = recs[0]
article_to = next.article_to
article_from = next.article_from
if article_from.draft or article_to.draft or article_from.deletion_date is not None or article_to.deletion_date is not None:
next.delete()
else:
data['offset'] += 1
return data
def update_recommendations(self, data):
offset = data['offset']
recs = model.Recommendation.all().fetch(1, offset)
if len(recs) == 0:
return None
next = recs[0]
article_to = next.article_to
article_from = next.article_from
self.calculate_recommendation(article_from, article_to)
data['offset'] += 1
return data
def begin_recommendations(self, data):
offset = data['offset']
articles = model.Article.all().filter('draft', False).filter('deletion_date', None).order('creation_date').fetch(1, offset)
print 'articles: %d' % len(articles)
if len(articles) == 0:
return None
next = articles[0]
data['offset'] += 1
t = model.Task(task_type='article_recommendation', priority=0, data=simplejson.dumps({'article': next.key().id(), 'offset': 0}))
t.put()
return data
def article_recommendation(self, data):
article = model.Article.get_by_id(data['article'])
if article.draft or article.deletion_date is not None:
return None
offset = data['offset']
articles = model.Article.all().filter('draft', False).filter('deletion_date', None).order('creation_date').fetch(1, offset)
if not articles:
return None
next = articles[0]
data['offset'] += 1
self.calculate_recommendation(next, article)
return data
def calculate_recommendation(self, next, article):
def distance(v1, v2):
all = []
all.extend(v1)
all.extend(v2)
return float(len(all) - len(set(all)))
def create_recommendation(article_from, article_to, value):
return model.Recommendation(article_from=article_from,
article_to=article_to,
value=value,
article_from_title=article_from.title,
article_to_title=article_to.title,
article_from_author_nickname=article_from.author_nickname,
article_to_author_nickname=article_to.author_nickname,
article_from_url_path=article_from.url_path,
article_to_url_path=article_to.url_path)
if next.key().id() == article.key().id():
return
r1 = model.Recommendation.all().filter('article_from', article).filter('article_to', next).get()
r2 = model.Recommendation.all().filter('article_from', next).filter('article_to', article).get()
diff = distance(article.tags, next.tags)
if diff > 0:
if not r1:
r1 = create_recommendation(article, next, diff)
else:
r1.value = diff
if not r2:
r2 = create_recommendation(next, article, diff)
else:
r2.value = diff
r1.put()
r2.put()
else:
if r1:
r1.delete()
if r2:
r2.delete()
| 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 UserView(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
user = self.values['user']
contact = False
if user and user.nickname != this_user.nickname:
self.values['canadd'] = True
contact = self.is_contact(this_user)
self.values['is_contact'] = contact
if (user is not None and this_user.nickname == user.nickname) or contact:
self.values['im_addresses'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in this_user.im_addresses]
else:
self.values['im_addresses'] = []
self.values['this_user'] = this_user
linksChanged = False
counter = 0
for link in this_user.list_urls:
if not link.startswith('http'):
linksChanged = True
link = 'http://' + link
this_user.list_urls[counter] = link
if link.startswith('http://https://'):
linksChanged = True
link = link[7:len(link)]
this_user.list_urls[counter] = link
counter += 1
if linksChanged:
this_user.put()
links = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in this_user.list_urls]
self.values['links'] = links
self.values['personal_message'] = this_user.personal_message
self.values['articles'] = model.Article.all().filter('author =', this_user).filter('draft =', False).filter('deletion_date', None).order('-creation_date').fetch(5)
self.values['communities'] = model.CommunityUser.all().filter('user =', this_user).order('-creation_date').fetch(18)
self.values['contacts'] = model.Contact.all().filter('user_from', this_user).order('-creation_date').fetch(18)
self.render('templates/module/user/user-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/>.
##
from google.appengine.api import mail
from handlers.AuthenticatedHandler import *
class UserContact(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
if not self.auth():
return
contact = model.Contact.all().filter('user_from', user).filter('user_to', user_to).get()
if not contact:
contact = model.Contact(user_from=user,
user_to=user_to,
user_from_nickname=user.nickname,
user_to_nickname=user_to.nickname)
contact.put()
user.contacts += 1
user.put()
self.add_follower(user=user_to, nickname=user.nickname)
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
if not user_to.nickname in followers:
followers.append(user_to.nickname)
self.create_event(event_type='contact.add', followers=followers, user=user, user_to=user_to)
app = self.get_application()
subject = self.getLocale("%s has added you as contact") % user.nickname # "%s te ha agregado como contacto"
# %s te ha agregado como contacto en %s\nPuedes visitar su perfil en: %s/module/user/%s\n
body = self.getLocale("%s has added you as contact in %s\nVisit profile page: %s/module/user/%s\n") % (user.nickname, app.url, app.url, user.nickname)
self.mail(subject=subject, body=body, to=[user_to.email])
if self.get_param('x'):
self.render_json({ 'action': 'added' })
else:
self.redirect('/module/user/%s' % user_to.nickname)
else:
contact.delete()
user.contacts -= 1
user.put()
self.remove_follower(user=user_to, nickname=user.nickname)
if self.get_param('x'):
self.render_json({ 'action': 'deleted' })
else:
self.redirect('/module/user/%s' % user_to.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/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserArticles(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.Article.all().filter('author =', this_user).filter('draft =', False).filter('deletion_date', None)
self.values['articles'] = self.paging(query, 10, '-creation_date', this_user.articles, ['-creation_date'])
self.render('templates/module/user/user-articles.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 *
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': '© 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 |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.