code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python # -*- coding: utf8 -*- ''' Created on 2011-8-2 @author: zhongfeng ''' from neweggpageparser import NewEggAllSortParser,NewEggSort3PageParser,NewEggSort4PageParser from pageparser import ObuyUrlSummary from spider import ObuySpider if __name__ == '__main__': parserDict = {0:NewEggAllSortParser,3:NewEggSort3PageParser,4:NewEggSort4PageParser} sort3 = ObuyUrlSummary(url = ur'http://www.newegg.com.cn/SubCategory/1046.htm?pageSize=96',name='newegg', isRecursed = True,catagoryLevel = 3) digitRoot = ObuyUrlSummary(url = ur'http://www.newegg.com.cn/SubCategory/1046-3.htm?pageSize=96', name='digital',catagoryLevel = 4) newEggRoot = ObuyUrlSummary(url = ur'http://www.newegg.com.cn/CategoryList.htm',name='newegg') pserver = ObuyUrlSummary(url = ur'http://www.newegg.com.cn/Category/536.htm', name='服务器',catagoryLevel = 2) spider = ObuySpider(rootUrlSummary = newEggRoot,parserDict = parserDict,include =None,exclude = None,threadNum = 5) spider.spide()
Python
#/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2011-7-27 主要用于从网站上爬取信息后,抽取页面信息; @author: zhongfeng ''' from BeautifulSoup import BeautifulSoup from crawlerhttp import UrlSummary, CrawlerType from time import strftime import chardet,re from urlparse import urlparse encodingDict = {'360buy':'gb2312','newegg':'gb2312','dangdang':'gb2312','gome':'utf-8','amazon':'utf-8'} class ObuyUrlSummary(UrlSummary): ''' 链接抽象类 ''' def __init__(self, url, data=None, headers=None, crawlerType=CrawlerType.GET_URL, name='', isCrawle=True, isRecursed=True, catagoryLevel=0, parentPath=None, stat=0, errReason='', include=None, exclude=None): super(ObuyUrlSummary, self).__init__(url, data, headers, crawlerType) self.name = name #分类名称 self.catagoryLevel = catagoryLevel #分类级别 self.parentPath = [] if parentPath is None else parentPath #路径 self.isCrawle = isCrawle #是否抓取 self.isRecursed = isRecursed #是否递归抓取 self.stat = stat #抓取的最终状态 self.errReason = errReason #错误原因 self.include = None #subUrl中应该包含的url列表 self.exclude = None #subUrl中剔除的url列表,如果include,exclude同时设置,则include规则优先 def getUrlSumAbstract(self): return self.name,self.url,self.catagoryLevel def __str__(self): return str(vars(self)) __repr__ = __str__ class ParserResult(object): def logstr(self): pass def convertToUnicode(dataStr,siteName): if isinstance(dataStr, str): encoding = encodingDict.get(siteName,None) if encoding is None: encoding = chardet.detect(dataStr)['encoding'] encodingDict[siteName] = encoding dataStr = dataStr.decode(encoding, 'ignore') return dataStr class Parser(object): def __init__(self, dataStr, rootUrlSummary, include=None, exclude=None): self.rootUrlSummary = rootUrlSummary self.include = include self.exclude = exclude siteName = urlparse(rootUrlSummary.url).hostname.split('.')[1] self.dataStr = convertToUnicode(dataStr,siteName) self.soup = BeautifulSoup(self.dataStr,convertEntities = BeautifulSoup.HTML_ENTITIES) #默认使用BeautifulSoup做解析器 @staticmethod def compareUrlSumm(urla, urlb): if urla.url != None and len(urla.url) > 0: return urla.url == urlb.url elif urla.name != None and len(urla.name) > 0: return urla.name == urlb.name else: return False @staticmethod def urlSummContain(urlsumm, sort_urlsumm): if Parser.compareUrlSumm(urlsumm, sort_urlsumm): return True else: for parent in sort_urlsumm.parentPath: if Parser.compareUrlSumm(urlsumm, parent): return True return False def filterUrlList(self, finalUrlList): filterResult = list(finalUrlList) if self.include != None: for urlsumm in self.include: filterResult = [ finalUrl for finalUrl in finalUrlList if Parser.urlSummContain(urlsumm, finalUrl)] elif self.exclude != None: for urlsumm in self.exclude: filterResult = [ finalUrl for finalUrl in finalUrlList if not Parser.urlSummContain(urlsumm, finalUrl)] return filterResult def parserPageInfos(self): ''' 返回ParserResult组成的list ''' pass def parserSubUrlSums(self): pass class ParserUtils(object): ''' html标签解析类,return (name,url) ''' @staticmethod def parserTag_A(a): return a.getText().strip(), a['href'].strip() @staticmethod def getPrice(sPrice): '''¥4899.00变为4899.00''' sPrice = sPrice.replace(u',', '') regx = u'[0-9]+.[0-9]{2}' p = re.compile(regx) return p.search(sPrice).group() class RootCatagoryPageParser(Parser): ''' 根站点分类解析父类,获取所有的三级分类的ObuyUrlSummary ''' def __init__(self, dataStr, rootUrlSummary, include=None, exclude=None): super(RootCatagoryPageParser, self).__init__(dataStr, rootUrlSummary, include, exclude) def buildSort_N(self, url, name, parent, isCrawle=True): ''' 构造各级节点逻辑 ''' sort_n_urlsum = ObuyUrlSummary(url=url, name=name, parentPath=[], isCrawle=isCrawle) sort_n_urlsum.catagoryLevel = parent.catagoryLevel + 1 sort_n_urlsum.parentPath.extend(parent.parentPath) sort_n_urlsum.parentPath.append(parent) return sort_n_urlsum def getBaseSort3UrlSums(self): pass def parserSubUrlSums(self): result = self.getBaseSort3UrlSums() return self.filterUrlList(result) class Sort3PageParser(Parser): ''' 三级页面解析类, a.负责获取当前分类的所有的后续页面的UrlSummary b.负责获取页面的所有商品的信息 ''' def __init__(self, dataStr, rootUrlSummary, include=None, exclude=None): super(Sort3PageParser, self).__init__(dataStr, rootUrlSummary, include, exclude) def buildSort_4(self, url): sort4_urlsum = ObuyUrlSummary(url=url, name=self.rootUrlSummary.name, parentPath=[], catagoryLevel=4) sort4_urlsum.parentPath.extend(self.rootUrlSummary.parentPath) return sort4_urlsum def getTotal(self): pass def nextPageUrlPattern(self): pass def buildSort_4UrlSums(self): finalUrlList = [] totalPage = self.getTotal() if totalPage > 1: for pageNum in range(2, totalPage + 1): url = self.nextPageUrlPattern().format(str(pageNum)) finalUrlList.append(self.buildSort_4(url)) return finalUrlList def getSort4PageUrlSums(self): return self.buildSort_4UrlSums() def parserSubUrlSums(self): result = self.getSort4PageUrlSums() return self.filterUrlList(result) class ProductDetails(ParserResult): ''' 商品详细信息 ''' def __init__(self, name='', imageUrl=None, productId=None, catagory=None, fullUrl=None, pubPrice=None, privPrice=None, adWords='', reputation=None, evaluateNum=None, updateTime=None): self.name = name #商品名称 self.imageUrl = imageUrl #商品图片URL self.productId = productId #商品在原网站的ID self.catagory = catagory #商品所属分类 self.fullUrl = fullUrl #原始链接 self.pubPrice = pubPrice #商品标称的原价 self.privPrice = privPrice #商家卖价,没扣除广告折扣价格 self.adWords = adWords #促销信息,包括下单立减、返劵等 self.reputation = reputation #好评度 self.evaluateNum = evaluateNum #评论数 self.updateTime = strftime("%Y-%m-%d %H:%M:%S") if updateTime is None else updateTime #更新时间 def logstr(self): return '|'.join((str(self.productId), self.privPrice, self.updateTime, self.name, self.adWords)) def __str__(self): return str(vars(self)) __repr__ = __str__
Python
#!/usr/bin/env python # -*- coding: utf8 -*- ''' Created on 2011-8-16 @author: zhongfeng ''' COO8_FEATURES_MAP = { ''' __ __ __ __ __ __ __ __ __ __ ## #_ ''' : '.', ''' __###___ _#_#_##_ _##__##_ ##____## #_____#_ ##____## #_____#_ ##____## #_____#_ _##__#_# _##_###_ __##_#__ ''' : '0', ''' ___## __#_# _###_ #__## #__#_ ___## ___#_ ___## ___#_ ___## ___#_ ___## ''' : '1', ''' __###___ _#_#_##_ ##____## #_____#_ ______## _____#__ ____###_ ___#_#__ __##____ _#______ #######_ #_#_#_## ''' : '2', ''' __###_#_ _#_#_### ##____#_ ______## ___##_#_ ___#_##_ ______## ______#_ ##____## #_#___#_ _######_ ___#_#__ ''' : '3', ''' _____##_ ____#_#_ ____##__ ___#_##_ __##_#__ __#__##_ _#___#__ ##___##_ #_###_## ##_#_##_ _____#__ _____##_ ''' : '4', ''' _____##_ ____#_#_ ____##__ ___#_##_ __##_#__ ___#_##_ _##__#__ #____##_ ####_#_# #_#_#### _____#__ _____##_ ''' : '4', ''' _###_##_ _#_###__ _#______ _#______ ###_##__ #_###_#_ ##____## ______#_ ##____## #_#___#_ _######_ ___#_#__ ''' : '5', ''' __###_#_ _#_#_### _##___#_ #_______ ##_###__ #_#_#_#_ ##____## #_____#_ ##____## _##___#_ _#_##_#_ __#_##__ ''' : '6', ''' ###_#### #_###_#_ _____##_ ____#___ ____##__ ___#____ ___##___ ___#____ ___#____ __##____ __#_____ __##____ ''' : '7', ''' __####__ _#_#_##_ ##____## #______# ##____## _#####__ __#_#_#_ ##____## #_____#_ ##____## _####_#_ ___#_#__ ''' : '8', ''' __###___ _#_#_##_ ##___##_ #_____## ##_____# #_____## _#####_# __#_#_## ______#_ ##___#__ #_##_##_ _##_##__ ''' : '9', ''' __###___ _#_#_##_ ##___##_ #_____## ##_____# #_____## _#####_# __#_#_## ______#_ ##___#__ #_##_##_ _#_###__ ''' : '9', }
Python
#!/usr/bin/env python # -*- coding: utf8 -*- ''' Created on 2011-8-16 @author: zhongfeng ''' COO8_FEATURES_MAP = { ''' __ __ __ __ __ __ __ __ __ ## #_ ## ''' : '.', ''' __###_#__ _#____##_ _#_____#_ ##_____## #______#_ ##_____## #______#_ ##_____## #______#_ _#_____## _##___#__ __###_#__ ''' : '0', ''' __###_#__ _#____##_ #______#_ ##_____## #______#_ ##_____## #______#_ ##_____## #______#_ _#_____## _##___#__ __###_#__ ''' : '0', ''' __##__ __#___ #_##__ __#___ __##__ __#___ __##__ __#___ __##__ __#___ __##__ ##_### ''' : '1', ''' _####_#__ #_____##_ ##_____#_ _______## _______#_ ______#__ _____##__ ____#____ ___#_#___ __##_____ _#_______ #_####### ''' : '2', ''' ###_###__ #_____#__ ##_____## _______#_ ______##_ ___##_#__ ______##_ _______## ________# ##_____## #_____#__ _#####___ ''' : '3', ''' ______##__ _____#_#__ ____#_##__ ___#__#___ __#___##__ _#____#___ #_____##__ #####_#_## ______##__ ______#___ ______##__ ______#___ ''' : '4', ''' _###_#### _#_______ _##______ _#_______ _######__ ______#__ _______## _______#_ _______## ##_____#_ #_____#__ _####_#__ ''' : '5', ''' ___###_#_ __#______ _##______ #________ ##_####__ #_____#__ ##_____## #______#_ ##_____## #______#_ _##___#__ __###_#__ ''' : '6', ''' ###_####_ _______## ______#__ ______##_ _____#___ _____##__ ____#____ ____##___ ___#_____ ___##____ __#______ _###_____ ''' : '7', ''' __###_#__ _#____##_ ##_____## #_______# _##___##_ __###_#__ _#____##_ ##_____#_ #______## ##_____#_ _#____#__ __####___ ''' : '8', ''' __###_#__ _#____##_ ##_____#_ #______## ##_____#_ #______## _##____#_ __###__## _______#_ ______##_ _____#___ _###_#___ ''' : '9', }
Python
#!/usr/bin/env python # -*- coding: utf8 -*- ''' Created on 2011-7-26 京东价格图片识别模块 @author: zhongfeng ''' import ImageFilter, ImageChops from captcha_price import * from coo8.coo8_feature2 import COO8_FEATURES_MAP import Image import itertools import re import time try: import psyco psyco.full() except ImportError: pass class CaptchaProfile_coo8(CaptchaProfile): def __init__(self): pass def __new__(cls): ''' 单态实现,初始化一次 ''' if '_inst' not in vars(cls): cls.__catagory_FEATURES_MAP__ = dict([(feature_to_data(key),value) for key,value in COO8_FEATURES_MAP.iteritems()]) cls._inst = super(CaptchaProfile_coo8, cls).__new__(cls) return cls._inst def filter(self, im): return im.filter(ImageFilter.EDGE_ENHANCE_MORE).convert('L').convert('1') def split(self, im): xsize, ysize = im.size pixels = im.load() zeroArr = [] for x in xrange(xsize): flag = True for y in xrange(ysize): if pixels[x,y] != 255: flag = False break if flag: zeroArr.append(x) zeroArr = [(value - index ,value) for index,value in enumerate(zeroArr)] retd = [] for key, group in itertools.groupby(zeroArr, lambda x: x[0]): ret = [t[1] for t in group] retd.append((ret[0],ret[-1])) l = len(retd) i = 0 dd = [] while i < l - 1 : pre = retd[i][1] + 1 next = retd[i + 1][0] # if 2 < next - pre < 7: # nPre = retd[i + 1][1] # nNext = retd[i + 2][0] # if 2 < nNext - nPre < 7: # dd.append((pre,4,nNext,16)) # i = i + 2 # continue # print (pre,4,next,16) dd.append((pre,4,next,16)) i = i + 1 return (im.crop(idt) for idt in dd[1:]) def match(self, im): st = time.time() imageData = feature_to_data(CaptchaImageAlgorithm.GetBinaryMap(im)) result = self.__catagory_FEATURES_MAP__.get(imageData,None) if result != None: return result print CaptchaImageAlgorithm.GetBinaryMap(im),'\n' source = im.getdata() algorithm = CaptchaAlgorithm() minimal = min(COO8_FEATURES_MAP, key=lambda feature:algorithm.LevenshteinDistance(source, feature_to_data(feature))) return COO8_FEATURES_MAP[minimal] def captcha_coo8(filename): return captcha(filename, CaptchaProfile_coo8()) def test(): print CaptchaProfile_coo8(r'c:\gp359329,2.png') import os curModDir = os.path.dirname(os.path.abspath(__file__)) testFilePath = os.path.join(curModDir, 'test_resources') if __name__ == '__main__': fileName = os.path.join(testFilePath, "125487,1.png") print captcha_coo8(fileName) # it1 = im.crop((3, 4, 13, 16)) # print cia.GetBinaryMap(it1),'\n' # it2 = im.crop((15,4,24,16)) # print cia.GetBinaryMap(it2) # print '+++++++++' # it2 = im.crop((25, 4, 34, 16)) # it3 = im.crop ((36,4,45,16)) # #it3 = im.crop((35, 4, 37, 16)) # it4 = im.crop((38, 4, 47, 16)) # it5 = im.crop((48, 4, 57, 16)) # #it6 = im.crop((51, 3, 57, 11)) # #it7 = im.crop((59, 3, 65, 11)) # multilist = [[0 for col in range(5)] for row in range(3)] # print '\n'.join(( str(t) for t in multilist)) #profile = CaptchaProfile_360Buy() #print captcha_360buy(r'c:\6.png')
Python
#!/usr/bin/env python # -*- coding: utf8 -*- ''' Created on 2011-7-26 京东价格图片识别模块 @author: zhongfeng ''' import ImageFilter, ImageChops from captcha_price import * from coo8.coo8_feature2 import COO8_FEATURES_MAP import Image import itertools import re import time try: import psyco psyco.full() except ImportError: pass class CaptchaProfile_coo8(CaptchaProfile): def __init__(self): pass def __new__(cls): ''' 单态实现,初始化一次 ''' if '_inst' not in vars(cls): cls.__catagory_FEATURES_MAP__ = dict([(feature_to_data(key),value) for key,value in COO8_FEATURES_MAP.iteritems()]) cls._inst = super(CaptchaProfile_coo8, cls).__new__(cls) return cls._inst def filter(self, im): return im.filter(ImageFilter.EDGE_ENHANCE_MORE).convert('L').convert('1') def split(self, im): xsize, ysize = im.size pixels = im.load() zeroArr = [] for x in xrange(xsize): flag = True for y in xrange(ysize): if pixels[x,y] != 255: flag = False break if flag: zeroArr.append(x) zeroArr = [(value - index ,value) for index,value in enumerate(zeroArr)] retd = [] for key, group in itertools.groupby(zeroArr, lambda x: x[0]): ret = [t[1] for t in group] retd.append((ret[0],ret[-1])) l = len(retd) i = 0 dd = [] while i < l - 1 : pre = retd[i][1] + 1 next = retd[i + 1][0] # if 2 < next - pre < 7: # nPre = retd[i + 1][1] # nNext = retd[i + 2][0] # if 2 < nNext - nPre < 7: # dd.append((pre,4,nNext,16)) # i = i + 2 # continue # print (pre,4,next,16) dd.append((pre,4,next,16)) i = i + 1 return (im.crop(idt) for idt in dd[1:]) def match(self, im): st = time.time() imageData = feature_to_data(CaptchaImageAlgorithm.GetBinaryMap(im)) result = self.__catagory_FEATURES_MAP__.get(imageData,None) if result != None: return result print CaptchaImageAlgorithm.GetBinaryMap(im),'\n' source = im.getdata() algorithm = CaptchaAlgorithm() minimal = min(COO8_FEATURES_MAP, key=lambda feature:algorithm.LevenshteinDistance(source, feature_to_data(feature))) return COO8_FEATURES_MAP[minimal] def captcha_coo8(filename): return captcha(filename, CaptchaProfile_coo8()) def test(): print CaptchaProfile_coo8(r'c:\gp359329,2.png') import os curModDir = os.path.dirname(os.path.abspath(__file__)) testFilePath = os.path.join(curModDir, 'test_resources') if __name__ == '__main__': fileName = os.path.join(testFilePath, "125487,1.png") print captcha_coo8(fileName) # it1 = im.crop((3, 4, 13, 16)) # print cia.GetBinaryMap(it1),'\n' # it2 = im.crop((15,4,24,16)) # print cia.GetBinaryMap(it2) # print '+++++++++' # it2 = im.crop((25, 4, 34, 16)) # it3 = im.crop ((36,4,45,16)) # #it3 = im.crop((35, 4, 37, 16)) # it4 = im.crop((38, 4, 47, 16)) # it5 = im.crop((48, 4, 57, 16)) # #it6 = im.crop((51, 3, 57, 11)) # #it7 = im.crop((59, 3, 65, 11)) # multilist = [[0 for col in range(5)] for row in range(3)] # print '\n'.join(( str(t) for t in multilist)) #profile = CaptchaProfile_360Buy() #print captcha_360buy(r'c:\6.png')
Python
#!/usr/bin/env python # -*- coding: utf8 -*- ''' Created on 2011-8-1 @author: zhongfeng ''' from coo8.coo8pageparser import Coo8AllSortParser,Coo8Sort3PageParser,Coo8Sort4PageParser from pageparser import ObuyUrlSummary from spider import ObuySpider if __name__ == '__main__': parserDict = {0:Coo8AllSortParser,3:Coo8Sort3PageParser,4:Coo8Sort4PageParser} sort3 = ObuyUrlSummary(url = r'http://www.coo8.com/products/290-13980-0-0-0-0.html',name='coo8', isRecursed = True,catagoryLevel = 3) digitRoot = ObuyUrlSummary(url = r'http://www.360buy.com/products/652-653-659-0-0-0-0-0-0-0-1-1-2.html', name='digital',isRecursed = False,catagoryLevel = 4) Coo8Root = ObuyUrlSummary(url = r'http://www.coo8.com/allcatalog/',name='coo8', isRecursed = True,catagoryLevel = 0) pcare = ObuyUrlSummary(url = r'http://www.360buy.com/products/652-653-000.html', name='手机',isRecursed = False,catagoryLevel = 2) pdigital = ObuyUrlSummary(url = r'http://www.360buy.com/digital.html',name='digital',catagoryLevel = 1) pelectronic = ObuyUrlSummary(url = r'http://www.360buy.com/electronic.html',name='electronic',catagoryLevel = 1) pcomputer = ObuyUrlSummary(url = r'http://www.360buy.com/computer.html',name='computer',catagoryLevel = 1) includes = [pelectronic,pdigital,pcomputer] spider = ObuySpider(rootUrlSummary = Coo8Root,parserDict = parserDict,include = None,exclude = None,threadNum = 10) spider.spide()
Python
#!/usr/bin/env python # -*- coding: utf8 -*- ''' Created on 2011-8-16 @author: zhongfeng ''' COO8_FEATURES_MAP = { ''' __ __ __ __ __ __ __ __ __ ## #_ ## ''' : '.', ''' __###_#__ _#____##_ _#_____#_ ##_____## #______#_ ##_____## #______#_ ##_____## #______#_ _#_____## _##___#__ __###_#__ ''' : '0', ''' __###_#__ _#____##_ #______#_ ##_____## #______#_ ##_____## #______#_ ##_____## #______#_ _#_____## _##___#__ __###_#__ ''' : '0', ''' __##__ __#___ #_##__ __#___ __##__ __#___ __##__ __#___ __##__ __#___ __##__ ##_### ''' : '1', ''' _####_#__ #_____##_ ##_____#_ _______## _______#_ ______#__ _____##__ ____#____ ___#_#___ __##_____ _#_______ #_####### ''' : '2', ''' ###_###__ #_____#__ ##_____## _______#_ ______##_ ___##_#__ ______##_ _______## ________# ##_____## #_____#__ _#####___ ''' : '3', ''' ______##__ _____#_#__ ____#_##__ ___#__#___ __#___##__ _#____#___ #_____##__ #####_#_## ______##__ ______#___ ______##__ ______#___ ''' : '4', ''' _###_#### _#_______ _##______ _#_______ _######__ ______#__ _______## _______#_ _______## ##_____#_ #_____#__ _####_#__ ''' : '5', ''' ___###_#_ __#______ _##______ #________ ##_####__ #_____#__ ##_____## #______#_ ##_____## #______#_ _##___#__ __###_#__ ''' : '6', ''' ###_####_ _______## ______#__ ______##_ _____#___ _____##__ ____#____ ____##___ ___#_____ ___##____ __#______ _###_____ ''' : '7', ''' __###_#__ _#____##_ ##_____## #_______# _##___##_ __###_#__ _#____##_ ##_____#_ #______## ##_____#_ _#____#__ __####___ ''' : '8', ''' __###_#__ _#____##_ ##_____#_ #______## ##_____#_ #______## _##____#_ __###__## _______#_ ______##_ _____#___ _###_#___ ''' : '9', }
Python
#!/usr/bin/env python # -*- coding: utf8 -*- ''' Created on 2011-8-16 @author: zhongfeng ''' COO8_FEATURES_MAP = { ''' __ __ __ __ __ __ __ __ __ __ ## #_ ''' : '.', ''' __###___ _#_#_##_ _##__##_ ##____## #_____#_ ##____## #_____#_ ##____## #_____#_ _##__#_# _##_###_ __##_#__ ''' : '0', ''' ___## __#_# _###_ #__## #__#_ ___## ___#_ ___## ___#_ ___## ___#_ ___## ''' : '1', ''' __###___ _#_#_##_ ##____## #_____#_ ______## _____#__ ____###_ ___#_#__ __##____ _#______ #######_ #_#_#_## ''' : '2', ''' __###_#_ _#_#_### ##____#_ ______## ___##_#_ ___#_##_ ______## ______#_ ##____## #_#___#_ _######_ ___#_#__ ''' : '3', ''' _____##_ ____#_#_ ____##__ ___#_##_ __##_#__ __#__##_ _#___#__ ##___##_ #_###_## ##_#_##_ _____#__ _____##_ ''' : '4', ''' _____##_ ____#_#_ ____##__ ___#_##_ __##_#__ ___#_##_ _##__#__ #____##_ ####_#_# #_#_#### _____#__ _____##_ ''' : '4', ''' _###_##_ _#_###__ _#______ _#______ ###_##__ #_###_#_ ##____## ______#_ ##____## #_#___#_ _######_ ___#_#__ ''' : '5', ''' __###_#_ _#_#_### _##___#_ #_______ ##_###__ #_#_#_#_ ##____## #_____#_ ##____## _##___#_ _#_##_#_ __#_##__ ''' : '6', ''' ###_#### #_###_#_ _____##_ ____#___ ____##__ ___#____ ___##___ ___#____ ___#____ __##____ __#_____ __##____ ''' : '7', ''' __####__ _#_#_##_ ##____## #______# ##____## _#####__ __#_#_#_ ##____## #_____#_ ##____## _####_#_ ___#_#__ ''' : '8', ''' __###___ _#_#_##_ ##___##_ #_____## ##_____# #_____## _#####_# __#_#_## ______#_ ##___#__ #_##_##_ _##_##__ ''' : '9', ''' __###___ _#_#_##_ ##___##_ #_____## ##_____# #_____## _#####_# __#_#_## ______#_ ##___#__ #_##_##_ _#_###__ ''' : '9', }
Python
#/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2011-8-7 主要用于从网站上爬取信息后,抽取页面信息; @author: zhongfeng ''' from cStringIO import StringIO from coo8.image_price import captcha_coo8 from crawlerhttp import crawle from pageparser import * from threadpool import ThreadPool, WorkRequest import json import os import re import threading import urllib class Coo8AllSortParser(RootCatagoryPageParser): ''' 从http://www.coo8.com/allcatalog/获取所有的分类信息, 组合成ObuyUrlSummary ''' mainHost = r'http://www.coo8.com/' def __init__(self, dataStr, rootUrlSummary, include=None, exclude=None): super(Coo8AllSortParser, self).__init__(dataStr, rootUrlSummary, include, exclude) def getBaseSort3UrlSums(self): finalUrlList = [] allSort = self.soup.find(name='div', attrs={'class':'cateItems'}) for t in allSort.findAll(name='div', attrs={'class':re.compile('hd.*')}):#一级分类 sort_1 = t.find(name='h2') name = sort_1['id'] url = ''.join((self.mainHost,name,'/')) sort_1_urlsum = self.buildSort_N(url, name, self.rootUrlSummary, isCrawle=False) sort_2 = t.findNextSibling(name='div',attrs={'class':re.compile('bd.*')}) for tt in sort_2(name='dl'):#二级分类 name = tt.dt.h3.getText() url = ''.join((self.mainHost, sort_1_urlsum.name, name)) sort_2_urlsum = self.buildSort_N(url, name, sort_1_urlsum, isCrawle=False) for ttt in tt(name='dd'):#三级分类 name, url = ParserUtils.parserTag_A(ttt.a) sort_3_urlsum = self.buildSort_N(url, name, sort_2_urlsum) finalUrlList.append(sort_3_urlsum) return finalUrlList class Coo8Sort3PageParser(Sort3PageParser): ''' 三级页面解析类 ''' pricePageNum = 8 def __init__(self, dataStr, rootUrlSummary, include=None, exclude=None): super(Coo8Sort3PageParser, self).__init__(dataStr, rootUrlSummary, include, exclude) def nextPageUrlPattern(self): urlSegs = self.rootUrlSummary.url.rsplit('.', 1) pageSeg = '-0-0-0-{}-0-101101' return '%s%s.%s' % (urlSegs[0].replace('-0-0-0-0',''), pageSeg, urlSegs[1]) def getTotal(self): regx = u'共([0-9]*)页' p = re.compile(regx) pageSeg = self.soup.find(name='div', attrs={'class':'pageInfo'}) if pageSeg is None: return 1 pageNum = pageSeg.getText() return int(p.search(pageNum).group(1)) def parserPageInfos(self): def getProductPrice(*req): priceImgUrl = req[0] result = crawle(priceImgUrl) proc_normal_result(req, result) print 'Get price:%s' % priceImgUrl return result def proc_normal_result(req, result): args = req if result.code == 200: prodDetail = args[1] resultList = args[2] prodDetail.privPrice = captcha_coo8(StringIO(result.content)) resultList.append(prodDetail) else: print args[0] resultList = [] plist = self.soup.find(name='div', attrs={'class':'srchContent'}) if plist is None: raise Exception("Page Error") return resultList try: pool = ThreadPool(self.pricePageNum) for li in plist(name='li'): pNameSeg = li.find(name='p', attrs={'class':'name'}).a pName = pNameSeg['title'] pid = pNameSeg['href'].rsplit('/')[-1].split('.')[0] priceImgUrl = li.find(name='p', attrs={'class':'price'}).img['src'] prodDetail = ProductDetails(productId=pid, name=pName) req = WorkRequest(getProductPrice, [priceImgUrl, prodDetail, resultList, pool], None, callback=None) pool.putRequest(req) pool.wait() except Exception,e: raise e finally: pool.dismissWorkers(num_workers=self.pricePageNum) return resultList class Coo8Sort4PageParser(Coo8Sort3PageParser): ''' 分类四级页面为列表页面,只抽取Product信息 ''' def __init__(self, dataStr, rootUrlSummary, include=None, exclude=None): super(Coo8Sort4PageParser, self).__init__(dataStr, rootUrlSummary, include, exclude) def parserSubUrlSums(self): pass ''' test ''' curModDir = os.path.dirname(os.path.abspath(__file__)) testFilePath = os.path.join(curModDir, 'test_resources') def testAllSortPage(): fileName = os.path.join(testFilePath, 'allsort.htm') with open(fileName, 'r') as fInput: content = fInput.read() rootUrlSum = ObuyUrlSummary(url=r'http://www.coo8.com/allcatalog/', name='coo8') firstPage = Coo8AllSortParser(content, rootUrlSum) for sort_3 in firstPage.getBaseSort3UrlSums(): print sort_3.url def testSort3Page(): fileName = os.path.join(testFilePath, '280-0-0-0-0.html') with open(fileName, 'r') as fInput: content = fInput.read() sort_3_urlsum = ObuyUrlSummary(url=r'http://www.coo8.com/products/280-0-0-0-0.html', parentPath=[('test')], catagoryLevel=3) sort3Page = Coo8Sort3PageParser(content, sort_3_urlsum) for sort_4 in sort3Page.getSort4PageUrlSums(): print sort_4.url def testSort3Details(): fileName = os.path.join(testFilePath, '280-0-0-0-0.html') with open(fileName, 'r') as fInput: content = fInput.read() sort_3_urlsum = ObuyUrlSummary(url=r'http://www.coo8.com/products/280-0-0-0-0.html', parentPath=[('test')], catagoryLevel=3) sort3Page = Coo8Sort3PageParser(content, sort_3_urlsum) for prod in sort3Page.parserPageInfos(): print prod.logstr() if __name__ == '__main__': testAllSortPage() testSort3Page() testSort3Details()
Python
#!/usr/bin/env python # -*- coding: utf8 -*- ''' Created on 2011-8-1 @author: zhongfeng ''' from coo8.coo8pageparser import Coo8AllSortParser,Coo8Sort3PageParser,Coo8Sort4PageParser from pageparser import ObuyUrlSummary from spider import ObuySpider if __name__ == '__main__': parserDict = {0:Coo8AllSortParser,3:Coo8Sort3PageParser,4:Coo8Sort4PageParser} sort3 = ObuyUrlSummary(url = r'http://www.coo8.com/products/290-13980-0-0-0-0.html',name='coo8', isRecursed = True,catagoryLevel = 3) digitRoot = ObuyUrlSummary(url = r'http://www.360buy.com/products/652-653-659-0-0-0-0-0-0-0-1-1-2.html', name='digital',isRecursed = False,catagoryLevel = 4) Coo8Root = ObuyUrlSummary(url = r'http://www.coo8.com/allcatalog/',name='coo8', isRecursed = True,catagoryLevel = 0) pcare = ObuyUrlSummary(url = r'http://www.360buy.com/products/652-653-000.html', name='手机',isRecursed = False,catagoryLevel = 2) pdigital = ObuyUrlSummary(url = r'http://www.360buy.com/digital.html',name='digital',catagoryLevel = 1) pelectronic = ObuyUrlSummary(url = r'http://www.360buy.com/electronic.html',name='electronic',catagoryLevel = 1) pcomputer = ObuyUrlSummary(url = r'http://www.360buy.com/computer.html',name='computer',catagoryLevel = 1) includes = [pelectronic,pdigital,pcomputer] spider = ObuySpider(rootUrlSummary = Coo8Root,parserDict = parserDict,include = None,exclude = None,threadNum = 10) spider.spide()
Python
#!/usr/bin/env python # -*- encoding:utf8 -*- # protoc-gen-erl # Google's Protocol Buffers project, ported to lua. # https://code.google.com/p/protoc-gen-lua/ # # Copyright (c) 2010 , 林卓毅 (Zhuoyi Lin) netsnail@gmail.com # All rights reserved. # # Use, modification and distribution are subject to the "New BSD License" # as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. import sys import os.path as path from cStringIO import StringIO import plugin_pb2 import google.protobuf.descriptor_pb2 as descriptor_pb2 _packages = {} _files = {} _message = {} FDP = plugin_pb2.descriptor_pb2.FieldDescriptorProto if sys.platform == "win32": import msvcrt, os msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) class CppType: CPPTYPE_INT32 = 1 CPPTYPE_INT64 = 2 CPPTYPE_UINT32 = 3 CPPTYPE_UINT64 = 4 CPPTYPE_DOUBLE = 5 CPPTYPE_FLOAT = 6 CPPTYPE_BOOL = 7 CPPTYPE_ENUM = 8 CPPTYPE_STRING = 9 CPPTYPE_MESSAGE = 10 CPP_TYPE ={ FDP.TYPE_DOUBLE : CppType.CPPTYPE_DOUBLE, FDP.TYPE_FLOAT : CppType.CPPTYPE_FLOAT, FDP.TYPE_INT64 : CppType.CPPTYPE_INT64, FDP.TYPE_UINT64 : CppType.CPPTYPE_UINT64, FDP.TYPE_INT32 : CppType.CPPTYPE_INT32, FDP.TYPE_FIXED64 : CppType.CPPTYPE_UINT64, FDP.TYPE_FIXED32 : CppType.CPPTYPE_UINT32, FDP.TYPE_BOOL : CppType.CPPTYPE_BOOL, FDP.TYPE_STRING : CppType.CPPTYPE_STRING, FDP.TYPE_MESSAGE : CppType.CPPTYPE_MESSAGE, FDP.TYPE_BYTES : CppType.CPPTYPE_STRING, FDP.TYPE_UINT32 : CppType.CPPTYPE_UINT32, FDP.TYPE_ENUM : CppType.CPPTYPE_ENUM, FDP.TYPE_SFIXED32 : CppType.CPPTYPE_INT32, FDP.TYPE_SFIXED64 : CppType.CPPTYPE_INT64, FDP.TYPE_SINT32 : CppType.CPPTYPE_INT32, FDP.TYPE_SINT64 : CppType.CPPTYPE_INT64 } def printerr(*args): sys.stderr.write(" ".join(args)) sys.stderr.write("\n") sys.stderr.flush() class TreeNode(object): def __init__(self, name, parent=None, filename=None, package=None): super(TreeNode, self).__init__() self.child = [] self.parent = parent self.filename = filename self.package = package if parent: self.parent.add_child(self) self.name = name def add_child(self, child): self.child.append(child) def find_child(self, child_names): if child_names: for i in self.child: if i.name == child_names[0]: return i.find_child(child_names[1:]) raise StandardError else: return self def get_child(self, child_name): for i in self.child: if i.name == child_name: return i return None def get_path(self, end = None): pos = self out = [] while pos and pos != end: out.append(pos.name) pos = pos.parent out.reverse() return '.'.join(out) def get_global_name(self): return self.get_path() def get_local_name(self): pos = self while pos.parent: pos = pos.parent if self.package and pos.name == self.package[-1]: break return self.get_path(pos) def __str__(self): return self.to_string(0) def __repr__(self): return str(self) def to_string(self, indent = 0): return ' '*indent + '<TreeNode ' + self.name + '(\n' + \ ','.join([i.to_string(indent + 4) for i in self.child]) + \ ' '*indent +')>\n' class Env(object): filename = None package = None extend = None descriptor = None message = None context = None register = None def __init__(self): self.message_tree = TreeNode('') self.scope = self.message_tree def get_global_name(self): return self.scope.get_global_name() def get_local_name(self): return self.scope.get_local_name() def get_ref_name(self, type_name): try: node = self.lookup_name(type_name) except: # if the child doesn't be founded, it must be in this file return type_name[len('.'.join(self.package)) + 2:] if node.filename != self.filename: return node.filename + '_pb.' + node.get_local_name() return node.get_local_name() def lookup_name(self, name): names = name.split('.') if names[0] == '': return self.message_tree.find_child(names[1:]) else: return self.scope.parent.find_child(names) def enter_package(self, package): if not package: return self.message_tree names = package.split('.') pos = self.message_tree for i, name in enumerate(names): new_pos = pos.get_child(name) if new_pos: pos = new_pos else: return self._build_nodes(pos, names[i:]) return pos def enter_file(self, filename, package): self.filename = filename self.package = package.split('.') self._init_field() self.scope = self.enter_package(package) def exit_file(self): self._init_field() self.filename = None self.package = [] self.scope = self.scope.parent def enter(self, message_name): self.scope = TreeNode(message_name, self.scope, self.filename, self.package) def exit(self): self.scope = self.scope.parent def _init_field(self): self.descriptor = [] self.context = [] self.message = [] self.register = [] def _build_nodes(self, node, names): parent = node for i in names: parent = TreeNode(i, parent, self.filename, self.package) return parent class Writer(object): def __init__(self, prefix=None): self.io = StringIO() self.__indent = '' self.__prefix = prefix def getvalue(self): return self.io.getvalue() def __enter__(self): self.__indent += ' ' return self def __exit__(self, type, value, trackback): self.__indent = self.__indent[:-4] def __call__(self, data): self.io.write(self.__indent) if self.__prefix: self.io.write(self.__prefix) self.io.write(data) DEFAULT_VALUE = { FDP.TYPE_DOUBLE : '0.0', FDP.TYPE_FLOAT : '0.0', FDP.TYPE_INT64 : '0', FDP.TYPE_UINT64 : '0', FDP.TYPE_INT32 : '0', FDP.TYPE_FIXED64 : '0', FDP.TYPE_FIXED32 : '0', FDP.TYPE_BOOL : 'false', FDP.TYPE_STRING : '""', FDP.TYPE_MESSAGE : 'nil', FDP.TYPE_BYTES : '""', FDP.TYPE_UINT32 : '0', FDP.TYPE_ENUM : '1', FDP.TYPE_SFIXED32 : '0', FDP.TYPE_SFIXED64 : '0', FDP.TYPE_SINT32 : '0', FDP.TYPE_SINT64 : '0', } def code_gen_enum_item(index, enum_value, env): full_name = env.get_local_name() + '.' + enum_value.name obj_name = full_name.upper().replace('.', '_') + '_ENUM' env.descriptor.append( "local %s = protobuf.EnumValueDescriptor();\n"% obj_name ) context = Writer(obj_name) context('.name = "%s"\n' % enum_value.name) context('.index = %d\n' % index) context('.number = %d\n' % enum_value.number) env.context.append(context.getvalue()) return obj_name def code_gen_enum(enum_desc, env): env.enter(enum_desc.name) full_name = env.get_local_name() obj_name = full_name.upper().replace('.', '_') env.descriptor.append( "local %s = protobuf.EnumDescriptor();\n"% obj_name ) context = Writer(obj_name) context('.name = "%s"\n' % enum_desc.name) context('.full_name = "%s"\n' % env.get_global_name()) values = [] for i, enum_value in enumerate(enum_desc.value): values.append(code_gen_enum_item(i, enum_value, env)) context('.values = {%s}\n' % ','.join(values)) env.context.append(context.getvalue()) env.exit() return obj_name def code_gen_field(index, field_desc, env): full_name = env.get_local_name() + '.' + field_desc.name obj_name = full_name.upper().replace('.', '_') + '_FIELD' env.descriptor.append( "local %s = protobuf.FieldDescriptor();\n"% obj_name ) context = Writer(obj_name) context('.name = "%s"\n' % field_desc.name) context('.full_name = "%s"\n' % ( env.get_global_name() + '.' + field_desc.name)) context('.number = %d\n' % field_desc.number) context('.index = %d\n' % index) context('.label = %d\n' % field_desc.label) if field_desc.HasField("default_value"): context('.has_default_value = true\n') value = field_desc.default_value if field_desc.type == FDP.TYPE_STRING: context('.default_value = "%s"\n'%value) else: context('.default_value = %s\n'%value) else: context('.has_default_value = false\n') if field_desc.label == FDP.LABEL_REPEATED: default_value = "{}" elif field_desc.HasField('type_name'): default_value = "nil" else: default_value = DEFAULT_VALUE[field_desc.type] context('.default_value = %s\n' % default_value) if field_desc.HasField('type_name'): type_name = env.get_ref_name(field_desc.type_name).upper().replace('.', '_') if field_desc.type == FDP.TYPE_MESSAGE: context('.message_type = %s\n' % type_name) else: context('.enum_type = %s\n' % type_name) if field_desc.HasField('extendee'): type_name = env.get_ref_name(field_desc.extendee) env.register.append( "%s.RegisterExtension(%s)\n" % (type_name, obj_name) ) context('.type = %d\n' % field_desc.type) context('.cpp_type = %d\n\n' % CPP_TYPE[field_desc.type]) env.context.append(context.getvalue()) return obj_name def code_gen_message(message_descriptor, env, containing_type = None): env.enter(message_descriptor.name) full_name = env.get_local_name() obj_name = full_name.upper().replace('.', '_') env.descriptor.append( "local %s = protobuf.Descriptor();\n"% obj_name ) context = Writer(obj_name) context('.name = "%s"\n' % message_descriptor.name) context('.full_name = "%s"\n' % env.get_global_name()) nested_types = [] for msg_desc in message_descriptor.nested_type: msg_name = code_gen_message(msg_desc, env, obj_name) nested_types.append(msg_name) context('.nested_types = {%s}\n' % ', '.join(nested_types)) enums = [] for enum_desc in message_descriptor.enum_type: enums.append(code_gen_enum(enum_desc, env)) context('.enum_types = {%s}\n' % ', '.join(enums)) fields = [] for i, field_desc in enumerate(message_descriptor.field): fields.append(code_gen_field(i, field_desc, env)) context('.fields = {%s}\n' % ', '.join(fields)) if len(message_descriptor.extension_range) > 0: context('.is_extendable = true\n') else: context('.is_extendable = false\n') extensions = [] for i, field_desc in enumerate(message_descriptor.extension): extensions.append(code_gen_field(i, field_desc, env)) context('.extensions = {%s}\n' % ', '.join(extensions)) if containing_type: context('.containing_type = %s\n' % containing_type) env.message.append('%s = protobuf.Message(%s)\n' % (full_name, obj_name)) env.context.append(context.getvalue()) env.exit() return obj_name def write_header(writer): writer("""-- Generated By protoc-gen-lua Do not Edit """) def code_gen_file(proto_file, env, is_gen): filename = path.splitext(proto_file.name)[0] env.enter_file(filename, proto_file.package) includes = [] for f in proto_file.dependency: inc_file = path.splitext(f)[0] includes.append(inc_file) # for field_desc in proto_file.extension: # code_gen_extensions(field_desc, field_desc.name, env) for enum_desc in proto_file.enum_type: code_gen_enum(enum_desc, env) for enum_value in enum_desc.value: env.message.append('%s = %d\n' % (enum_value.name, enum_value.number)) for msg_desc in proto_file.message_type: code_gen_message(msg_desc, env) if is_gen: lua = Writer() write_header(lua) lua('local protobuf = require "protobuf"\n') for i in includes: lua('local %s_pb = require("%s_pb")\n' % (i, i)) lua("module('%s_pb')\n" % env.filename) lua('\n\n') map(lua, env.descriptor) lua('\n') map(lua, env.context) lua('\n') env.message.sort() map(lua, env.message) lua('\n') map(lua, env.register) _files[env.filename+ '_pb.lua'] = lua.getvalue() env.exit_file() def main(): plugin_require_bin = sys.stdin.read() code_gen_req = plugin_pb2.CodeGeneratorRequest() code_gen_req.ParseFromString(plugin_require_bin) env = Env() for proto_file in code_gen_req.proto_file: code_gen_file(proto_file, env, proto_file.name in code_gen_req.file_to_generate) code_generated = plugin_pb2.CodeGeneratorResponse() for k in _files: file_desc = code_generated.file.add() file_desc.name = k file_desc.content = _files[k] sys.stdout.write(code_generated.SerializeToString()) if __name__ == "__main__": main()
Python
#this code is used to select robots from the database and make them fight from robot import * from fight2 import * import pymysql def finalSel(): conn=pymysql.connect(host='www.freesqldatabase.com', port=3306, user='sql01_64191', passwd='**********', db='sql01_6419coadaf') cur=conn.cursor() cur2=conn.cursor() cur.execute("select * from final where GrandWinner is NULL") for row in cur: cur2.execute("select * from robots2 where id like %d"%row[1]) for l in cur2: wp1=Weapon(l[2]+1,l[3]+1,l[4]+1,1) hp1=Health(l[1]+1) r1=RobotC(l[0],random.randint(0,800),random.randint(0,600),0,hp1,wp1) cur2.execute("select * from robots2 where id like %d"%row[2]) for l in cur2: wp2=Weapon(l[2]+1,l[3]+1,l[4]+1,1) hp2=Health(l[1]+1) r2=RobotC(l[0],random.randint(0,800),random.randint(0,600),0,hp2,wp2) #r1.getDetails() #r2.getDetails() winner=fight(r1,r2) print "Match {0}: Grand winner is {1}".format(row[0],winner) cur2.execute("update final set GrandWinner={0} where id={1}".format(winner,row[0])) cur2.execute("update robots2 set GrandTitle=GrandTitle+1 where id={0}".format(winner,row[0]))
Python
from selector import * from finalSel import * from Tgenround1 import * from finalRound import * import pymysql conn=pymysql.connect(host='www.freesqldatabase.com', port=3306, user='sql01_64191', passwd='**********', db='sql01_6419coadaf') cur=conn.cursor() cur2=conn.cursor() def cont(): l1=cur.execute('select GrandWinner from final') if l1: print 'Tournament has ended!' else: #==============Check first round========= l1=cur.execute('select * from robots2') l2=cur2.execute('select * from round1') l1+=1 if l1/2==l2: print "Starting round 1...." selector("round1","robots2") else: print "Generating round 1..." round1('robots2','round1') print "Starting round 1...." selector("round1","robots2") #=============Check second round========== l1=cur.execute('select * from round1') l2=cur2.execute('select * from round2') l1+=1 if l1/2==l2: print "Starting round 2..." selector('round2','robots2') else: print "Generating round 2..." round1('round1','round2') print "Starting round 2..." selector('round2','robots2') #==============Check third round========== l1=cur.execute('select * from round2') l2=cur2.execute('select * from round3') l1+=1 if l1/2==l2: print "Starting round 3..." selector('round3','robots2') else: print "Generating round 3..." round1('round2','round3') print "Starting round 3..." selector('round3','robots2') #==============Check forth round========== l1=cur.execute('select * from round3') l2=cur2.execute('select * from round4') l1+=1 if l1/2==l2: print "Starting round 4..." selector('round4','robots2') else: print "Generating round 4..." round1('round3','round4') print "Starting round 4..." selector('round4','robots2') #===============Check fifth round========= l1=cur.execute('select * from round4') l2=cur2.execute('select * from round5') l1+=1 if l1/2==l2: print "Starting round 5..." selector('round5','robots2') else: print "Generating round 5..." round1('round4','round5') print "Starting round 5..." selector('round5','robots2') #===============Check sixth round========== l1=cur.execute('select * from round5') l2=cur2.execute('select * from round6') l1+=1 if l1/2==l2: print 'Starting semifinals...' selector('round6','robots2') else: print 'Generating semifinals...' round1('round5','round6') print 'Starting round 6...' selector('round6','robots2') #===============Check final round========== l1=cur.execute('select * from round6') l2=cur2.execute('select * from final') l1+=1 if l1/2==l2: print 'Starting final...' finalSel() else: print 'Generatin final...' finalRound() print 'Starting final...' finalSel()
Python
#this code is used to select robots from the database and make them fight from robot import * from fight2 import * import pymysql def selector(table1,table2): conn=pymysql.connect(host='www.freesqldatabase.com', port=3306, user='sql01_64191', passwd='**********', db='sql01_6419coadaf') cur=conn.cursor() cur2=conn.cursor() cur.execute("select * from {0} where winner is NULL".format(table1)) for row in cur: cur2.execute("select * from {0} where id like {1}".format(table2,row[1])) for l in cur2: wp1=Weapon(l[2]+1,l[3]+1,l[4]+1,1) hp1=Health(l[1]+1) r1=RobotC(l[0],random.randint(0,800),random.randint(0,600),0,hp1,wp1) cur2.execute("select * from {0} where id like {1}".format(table2,row[2])) for l in cur2: wp2=Weapon(l[2]+1,l[3]+1,l[4]+1,1) hp2=Health(l[1]+1) r2=RobotC(l[0],random.randint(0,800),random.randint(0,600),0,hp2,wp2) #r1.getDetails() #r2.getDetails() winner=fight(r1,r2) print "Match {0}: winner is {1}".format(row[0],winner) cur2.execute("update {0} set winner={1} where id={2}".format(table1,winner,row[0]))
Python
#!/usr/bin/env python class Health(object): def __init__(self,level): self.level=level self.chp=level def update(self,hit): self.chp=self.chp-hit if self.chp>=0: return 1 else: return 0 def getDet(self): print "Total Hp:{0}, Remaining Hp:{1}".format(self.level,self.chp)
Python
#!/usr/bin/env python class Weapon(object): def __init__(self,dmg,acc,range,rtime): self.dmg=dmg self.acc=acc self.range=range self.rtime=rtime def getDet(self): print "Dmg: {0}, Acc: {1}, Range:{2}, R-Time:{3}".format( self.dmg,self.acc,self.range,self.rtime)
Python
from Tkinter import * #import battlebots game logics from battleBots import * from updater import * from cont import * from start import * import sys from hof import * class GridApp: def __init__(self, parent=0): self.mainframe = Frame(parent) leftframe=Frame(self.mainframe) leftframe.grid(row=0,column=0) midframe=Frame(self.mainframe) midframe.grid(row=0,column=2) rightframe=Frame(self.mainframe) rightframe.grid(row=0,column=4) #Storage variables self.hp1=1 self.dmg1=1 self.acc1=2 self.range1=1 self.Rtime1=1 self.hp2=1 self.dmg2=1 self.acc2=2 self.range2=1 self.Rtime2=1 self.lock1=False self.lock2=False self.robWin='No battle yet' #Title widgets creation self.Robot1=Label(leftframe,text='Robot 1',background = 'WHITE') self.Robot2=Label(midframe,text='Robot 2',background = 'WHITE') self.Arena=Label(rightframe, text='BattleBots Arena',background = 'WHITE') self.tournament=Label(rightframe, text='Tournament', bg='WHITE') #Position title widgets self.Robot1.grid(row=0,column=0,columnspan=2, sticky=NSEW) self.Robot2.grid(row=0,column=0,columnspan=2, sticky=NSEW) self.Arena.grid(row=0,column=0,columnspan=5, sticky=NSEW) self.tournament.grid(row=4,column=0,columnspan=5,sticky=NSEW) #Buton and label widgets for robot1 self.hp1B=Button(leftframe,text='Hp:',command=self.hp1UP) self.hp1Value=Label(leftframe,text='%d'%(self.hp1)) self.dmg1B=Button(leftframe,text='Damage:',command=self.dmg1UP) self.dmg1Value=Label(leftframe,text='%d'%(self.dmg1)) self.acc1B=Button(leftframe,text='Accuracy:',command=self.acc1UP) self.acc1Value=Label(leftframe,text='%d'%(self.acc1)) self.range1B=Button(leftframe,text='Range:',command=self.range1UP) self.range1Value=Label(leftframe,text='%d'%(self.range1)) self.lock1B=Button(leftframe,text='Lock',command=self.lockR1,bg='red') self.reset1=Button(leftframe,text='Reset',command=self.reset1UP) self.pts1=self.hp1+self.dmg1+self.acc1+self.range1-4 self.points1=Label(leftframe,text='Points used: {0}\n Weapon load time: {1}'.format(self.pts1,self.Rtime1)) #Button and label widgets robot2 self.hp2B=Button(midframe,text='Hp:',command=self.hp2UP) self.hp2Value=Label(midframe,text='%d'%(self.hp2)) self.dmg2B=Button(midframe,text='Damage:',command=self.dmg2UP) self.dmg2Value=Label(midframe,text='%d'%(self.dmg2)) self.acc2B=Button(midframe,text='Accuracy:',command=self.acc2UP) self.acc2Value=Label(midframe,text='%d'%(self.acc2)) self.range2B=Button(midframe,text='Range:',command=self.range2UP) self.range2Value=Label(midframe,text='%d'%(self.range2)) self.lock2B=Button(midframe,text='Lock',command=self.lockR2,bg='red') self.reset2=Button(midframe,text='Reset',command=self.reset2UP) self.pts2=self.hp2+self.dmg2+self.acc2+self.range2-4 self.points2=Label(midframe,text='Points used: {0}\n Weapon load time: {1}'.format(self.pts2,self.Rtime2)) #Button and label widgets for Arena Control self.fight=Button(rightframe, text='Fight!',command=self.launch,bg='red') self.label1=Label(rightframe,text='--->') self.label2=Label(rightframe,text=' <--- ') self.exit=Button(rightframe, text=' Exit ',command=self.quitGame) self.winner=Label(rightframe,text=' Winner is: \n {0}'.format(self.robWin)) #Button widgets for Tournament self.Start=Button(rightframe,text='Start!',command=startT) self.Continue=Button(rightframe,text='Continue',command=cont) self.seeWinners=Button(rightframe,text='See winners',command=hof) #Position robot1 widgets self.hp1B.grid(row=1,column=0, sticky=NSEW) self.hp1Value.grid(row=1,column=1, sticky=NSEW) self.dmg1B.grid(row=2,column=0, sticky=NSEW) self.dmg1Value.grid(row=2,column=1, sticky=NSEW) self.acc1B.grid(row=3,column=0, sticky=NSEW) self.acc1Value.grid(row=3,column=1, sticky=NSEW) self.range1B.grid(row=4,column=0, sticky=NSEW) self.range1Value.grid(row=4,column=1, sticky=NSEW) self.points1.grid(row=5,column=0, columnspan=2) self.lock1B.grid(row=6,column=0, sticky=NSEW) self.reset1.grid(row=6,column=1, sticky=NSEW) #Position robot2 widgets self.hp2B.grid(row=1,column=0, sticky=NSEW) self.hp2Value.grid(row=1,column=1, sticky=NSEW) self.dmg2B.grid(row=2,column=0, sticky=NSEW) self.dmg2Value.grid(row=2,column=1, sticky=NSEW) self.acc2B.grid(row=3,column=0, sticky=NSEW) self.acc2Value.grid(row=3,column=1, sticky=NSEW) self.range2B.grid(row=4,column=0, sticky=NSEW) self.range2Value.grid(row=4,column=1, sticky=NSEW) self.points2.grid(row=5,column=0, columnspan=2) self.lock2B.grid(row=6,column=0, sticky=NSEW) self.reset2.grid(row=6,column=1, sticky=NSEW) #Position Arena widgets self.fight.grid(row=1,column=1,columnspan=3,sticky=NSEW) self.label1.grid(row=1,column=0,sticky=NSEW) self.exit.grid(row=2,column=1,columnspan=3,sticky=NSEW) self.label2.grid(row=1,column=4,sticky=NSEW) self.winner.grid(row=3,column=1,columnspan=3,sticky=NSEW) #Position Tournament Buttons self.Start.grid(row=5,column=0,columnspan=2,sticky=NSEW) self.Continue.grid(row=5,column=3,columnspan=2,sticky=NSEW) self.seeWinners.grid(row=6,column=1,columnspan=3, sticky=NSEW) # Position the widgets within the frame xsize, ysize = leftframe.grid_size() for i in range(0, ysize): leftframe.grid_rowconfigure(i, minsize=50, weight=1) midframe.grid_rowconfigure(i, minsize=50, weight=1) rightframe.grid_rowconfigure(i, minsize=50, weight=1) for i in range(xsize): leftframe.grid_columnconfigure(i, minsize=50, weight=1) midframe.grid_columnconfigure(i, minsize=50, weight=1) rightframe.grid_columnconfigure(i, minsize=50, weight=1) # set up the main window self.mainframe.grid() # set the title self.mainframe.master.title("Battle Bots Arena") #update functions for robot1 labels def hp1UP(self): if self.pts1<14: self.hp1+=1 self.hp1Value.configure(text='%d'%(self.hp1)) self.hp1Value.update_idletasks() self.points1UP() def dmg1UP(self): if self.pts1<14: self.dmg1+=1 self.dmg1Value.configure(text='%d'%(self.dmg1)) self.dmg1Value.update_idletasks() self.points1UP() def acc1UP(self): if self.pts1<14 and self.acc1<9: self.acc1+=1 self.acc1Value.configure(text='%d'%(self.acc1)) self.acc1Value.update_idletasks() self.points1UP() def range1UP(self): if self.pts1<14: self.range1+=1 self.range1Value.configure(text='%d'%(self.range1)) self.range1Value.update_idletasks() self.points1UP() def points1UP(self): self.pts1=self.hp1+self.dmg1+self.range1+self.acc1-4 if self.pts1>6: self.Rtime1=self.pts1-6+1 self.lock1Green() elif self.pts1==6: self.lock1Green() self.points1.configure(text='Points used: {0}\n Weapon load time: {1}'.format(self.pts1,self.Rtime1)) self.points1.update_idletasks() def reset1UP(self): self.hp1=1 self.dmg1=1 self.acc1=2 self.range1=1 self.Rtime1=1 self.lock1=False self.hp1Value.configure(text='%d'%(self.hp1)) self.hp1Value.update_idletasks() self.dmg1Value.configure(text='%d'%(self.dmg1)) self.dmg1Value.update_idletasks() self.acc1Value.configure(text='%d'%(self.acc1)) self.acc1Value.update_idletasks() self.range1Value.configure(text='%d'%(self.range1)) self.range1Value.update_idletasks() self.lock1B.configure(bg='red') self.lock1B.update_idletasks() self.fightUP() self.points1UP() def lock1Green(self): self.lock1B.configure(bg='green') self.lock1B.update_idletasks() #update functions for robot2 labels def hp2UP(self): if self.pts2<14: self.hp2+=1 self.hp2Value.configure(text='%d'%(self.hp2)) self.hp2Value.update_idletasks() self.points2UP() def dmg2UP(self): if self.pts2<14: self.dmg2+=1 self.dmg2Value.configure(text='%d'%(self.dmg2)) self.dmg2Value.update_idletasks() self.points2UP() def acc2UP(self): if self.pts2<14 and self.acc2<9: self.acc2+=1 self.acc2Value.configure(text='%d'%(self.acc2)) self.acc2Value.update_idletasks() self.points2UP() def range2UP(self): if self.pts2<14: self.range2+=1 self.range2Value.configure(text='%d'%(self.range2)) self.range2Value.update_idletasks() self.points2UP() def points2UP(self): self.pts2=self.hp2+self.dmg2+self.range2+self.acc2-4 if self.pts2>6: self.Rtime2=self.pts2-6+1 self.lock2Green() elif self.pts2==6: self.lock2Green() self.points2.configure(text='Points used: {0}\n Weapon load time: {1}'.format(self.pts2,self.Rtime2)) self.points2.update_idletasks() def reset2UP(self): self.hp2=1 self.dmg2=1 self.acc2=2 self.range2=1 self.Rtime2=1 self.lock2=False self.hp2Value.configure(text='%d'%(self.hp2)) self.hp2Value.update_idletasks() self.dmg2Value.configure(text='%d'%(self.dmg2)) self.dmg2Value.update_idletasks() self.acc2Value.configure(text='%d'%(self.acc2)) self.acc2Value.update_idletasks() self.range2Value.configure(text='%d'%(self.range2)) self.range2Value.update_idletasks() self.lock2B.configure(bg='red') self.lock2B.update_idletasks() self.fightUP() self.points2UP() def lock2Green(self): self.lock2B.configure(bg='green') self.lock2B.update_idletasks() #Fight button gets red after each fight def fightRed(self): self.fight.configure(bg='red') self.fight.update_idletasks() #Battle bots arena buttons functions def lockR1(self): if self.pts1>=6: wins,losses=checkR(self.hp1,self.dmg1,self.acc1,self.range1,self.Rtime1) setR1(self.hp1,self.dmg1,self.acc1,self.range1,self.Rtime1,wins,losses) self.lock1=True self.lock1B.configure(bg='yellow') self.lock1B.update_idletasks() self.fightUP() def lockR2(self): if self.pts2>=6: wins,losses=checkR(self.hp2,self.dmg2,self.acc2,self.range2,self.Rtime2) setR2(self.hp2,self.dmg2,self.acc2,self.range2,self.Rtime2,wins,losses) self.lock2=True self.lock2B.configure(bg='yellow') self.lock2B.update_idletasks() self.fightUP() def launch(self): if self.lock1==True and self.lock2==True: self.robWin=fightArena() if self.robWin=='Robot 1': updateWin(self.hp1,self.dmg1,self.acc1,self.range1) updateLoss(self.hp2,self.dmg2,self.acc2,self.range2) elif self.robWin=='Robot 2': updateWin(self.hp2,self.dmg2,self.acc2,self.range2) updateLoss(self.hp1,self.dmg1,self.acc1,self.range1) self.winner.configure(text=' Winner is: \n {0}'.format(self.robWin),bg='cyan') self.winner.update_idletasks() self.lock1=False self.lock2=False self.lock1Green() self.lock2Green() self.fightRed() def fightUP(self): if self.lock1==True and self.lock2==True: self.fight.configure(bg='green') else: self.fight.configure(bg='red') def quitGame(self): sys.exit() #instantiate the GridApp class app = GridApp() app.mainframe.mainloop()
Python
from robot import * import pygame import random w=800 h=600 WHITE=(255,255,255) BLACK=(0,0,0) clock=pygame.time.Clock() def fight(Rob1,Rob2): # wp1=Weapon(3,7,20,2) # wp2=Weapon(4,3,25,2) # hp1=Health(10,10) # hp2=Health(10,10) r1=Rob1 r2=Rob2 robots=(r1,r2) loop=True while loop: #Clear # if r1.loadWp()!=0: #follow enemy if weapon loaded # r1.step(r2.getPos()[0],r2.getPos()[1]) # else: #run if weapon is unloaded # r1.step(-r2.getPos()[0],-r2.getPos[1]) # if r1.loadWp()!=0: #follow enemy if weapon loaded # r2.step(r1.getPos()[0],r1.getPos()[1]) # else: #run if weapon is unloaded # r2.step(-r1.getPos()[0],-r1.getPos()[1]) #===================== Robot 1========================== if r1.inrange(r2.getPos()[0],r2.getPos()[1]): if r1.loadWp()!=0: #shoot enemy if in range bam=r1.shoot() if r2.hp.update(bam)==0: #end game if robot dead loop=False return r1.id # else : print "R2:%d"%(r2.hp.chp) else: #run if weapon is unloaded r1.step(-r2.x,-r2.y) else: if r1.loadWp()!=0: # followe enemy if weapon loaded r1.step(r2.getPos()[0],r2.getPos()[1]) else : r1.step(-r2.x,-r2.y) #===================== Robot 2 ========================== if r2.inrange(r1.getPos()[0],r1.getPos()[1]): if r2.loadWp()!=0: #shoot enemy if in range bom=r2.shoot() if r1.hp.update(bom)==0: #end game if roobot dead loop=False return r2.id # else : print "R1:%d"%(r1.hp.chp) else: #run if weapon is unloaded r2.step(-r1.x,-r1.y) else: if r2.loadWp()!=0: # followe enemy if weapon loaded r2.step(r1.getPos()[0],r1.getPos()[1]) else: r2.step(-r1.x,-r2.y) clock.tick(30)
Python
from selector import * from finalSel import * from Tgenround1 import * from finalRound import * def startT(): clearDB() print "Generating round 1..." round1('robots2','round1') print "Starting round 1..." selector("round1","robots2") print "Generating round 2..." round1('round1','round2') print "Starting round 2..." selector('round2','robots2') print "Generating round 3..." round1('round2','round3') print "Starting round 3..." selector('round3','robots2') print "Generating round 4..." round1('round3','round4') print "Starting round 4..." selector('round4','robots2') print "Generating round 5..." round1('round4','round5') print "Starting round 5..." selector('round5','robots2') print "Generating semifinals..." round1('round5','round6') print "Starting semifinals..." selector('round6','robots2') print "Generating Final..." finalRound() print "Starting Final..." finalSel()
Python
#================Tournament generator========= #Generate the matches for the robots import random import pymysql def check(l): ok=0 for i in l: if i==1: ok=1 return ok def generate(l,cur,lenght,table2,table1): #==================Robot1 ========================== r1=random.randint(1,lenght) if(l[r1]==1): #check oponent to see if available l[r1]=0 else: while (l[r1]==0): #keep looking for an available robot r1=random.randint(1,lenght) l[r1]=0 cur.execute("select winner from {0} where id={1}".format(table1,r1)) for idRob in cur: r1=idRob[0] #==================Robot2 ========================== if check(l)==0: r2=random.randint(1,lenght) else : r2=random.randint(1,lenght) if(l[r2]==1): #check oponent to see if available l[r2]=0 else: while (l[r2]==0): #keep looking for a second robot r2=random.randint(1,lenght) l[r2]=0 if table1!='robots2': cur.execute("select winner from {0} where id={1}".format(table1,r2)) for idRob in cur: r2=idRob[0] cur.execute("INSERT INTO {0} (id , robot1, robot2) VALUES (NULL, {1}, {2})".format(table2,r1,r2)) return check(l) def round1(table1,table2): conn=pymysql.connect(host='www.freesqldatabase.com', port=3306, user='sql01_64191', passwd='cr1mina', db='sql01_6419coadaf') cur=conn.cursor() lenght=cur.execute("select * from {0}".format(table1)) l=[1]*(lenght+1) #store if a robot has a match already planned l[0]=0 loop=generate(l,cur,lenght,table2,table1) while(loop): loop=generate(l,cur,lenght,table2,table1) print "===The END===" def clearDB(): conn=pymysql.connect(host='www.freesqldatabase.com', port=3306, user='sql01_64191', passwd='cr1mina', db='sql01_6419coadaf') cur=conn.cursor() cur.execute("TRUNCATE TABLE round1") cur.execute("TRUNCATE TABLE round2") cur.execute("TRUNCATE TABLE round3") cur.execute("TRUNCATE TABLE round4") cur.execute("TRUNCATE TABLE round5") cur.execute("TRUNCATE TABLE round6") cur.execute("TRUNCATE TABLE final")
Python
#k - skill variable(1 health, 2 damage, 3 range, 4 accuracy) #s - sum check import pymysql conn=pymysql.connect(host='www.freesqldatabase.com', port=3306, user='sql01_64191', passwd='**********', db='sql01_6419coadaf') cur=conn.cursor() def check(l): s=0 for j in l: s+=j if s==6: cur.execute("INSERT INTO robots2 (id ,health ,damage ,range ,accuracy)VALUES (NULL, %d, %d, %d, %d)"%(l[0],l[1],l[2],l[3])) def back(k,l): if(k<4): for i in range(0,7): l[k]=i check(l) back(k+1,l) return def main(): k=0 l=[0]*4 back(k,l) print 'Finish' return main() cur.close() conn.close()
Python
#!/usr/bin/python #battleBots.py #Based on battleBots.py by James Shuttleworth #If your robots are in "robots.py" use this line... from robot import * #or delete it and put your classes here instead #Change code below for the classes of your two robots #from pygame.locals import * import pygame import random #loading background image background = pygame.image.load("bg2.bmp") backgroundRect = background.get_rect() #loading robot image robo1=pygame.image.load("robo.png") robo2=pygame.image.load("robo2.png") w=800 h=600 WHITE=(255,255,255) BLACK=(0,0,0) GREEN=(0,255,0) RED=(255,0,0) clock=pygame.time.Clock() wp1=Weapon(2,3,1,1) wp2=Weapon(1,3,2,3) hp1=Health(10) hp2=Health(10) r1=RobotC(1,random.randint(0,w),random.randint(0,h),0,hp1,wp1,0,0) r2=RobotC(2,random.randint(0,w),random.randint(0,h),0,hp2,wp2,0,0) pause=False def setR1(hp,dmg,acc,range1,time,wins,losses): global wp1 global hp1 global r1 wp1=Weapon(dmg,acc,range1*20,time) hp1=Health(hp) r1=RobotC(1,random.randint(25,w),random.randint(125,h),0,hp1,wp1,wins,losses) def setR2(hp,dmg,acc,range2,time,wins,losses): global wp2 global hp2 global r2 wp2=Weapon(dmg,acc,range2*20,time) hp2=Health(hp) r2=RobotC(2,random.randint(25,w),random.randint(125,h),0,hp2,wp2,wins,losses) def printStats(r,labelfont,screen): robot='Robot %d'%(r.id) name=labelfont.render(robot,True,(255,255,255)) weaponDet='Weapon: {0} dmg, {1} range, {2}% acc, {3} load time'.format(r.wp.dmg,r.wp.range,r.wp.acc*10,r.wp.rtime) weapon=labelfont.render(weaponDet,True,(255,255,255)) hpDet='Hp: {0} total Hp, {1} current Hp'.format(r.hp.level,r.hp.chp) hp=labelfont.render(hpDet,True,(255,255,255)) statusDet='Status: {0}'.format(r.status) status=labelfont.render(statusDet,True,(255,255,255)) hitDet='Last atack: {0}'.format(r.hitStatus) hit=labelfont.render(hitDet,True,(255,255,255)) recordDet='Wins: {0}, Losses:{1}'.format(r.win,r.loss) record=labelfont.render(recordDet,True,(255,255,255)) if(r.id==1): screen.blit(name,(20,20)) screen.blit(weapon,(20,35)) screen.blit(hp,(20,50)) screen.blit(status,(20,65)) screen.blit(hit,(20,80)) screen.blit(record,(190,80)) else: screen.blit(name,(420,20)) screen.blit(weapon,(420,35)) screen.blit(hp,(420,50)) screen.blit(status,(420,65)) screen.blit(hit,(420,80)) screen.blit(record,(590,80)) def RunXY(l): run=random.randint(1,4) if run==1: l[0]=l[0]*2 #x l[1]=l[1]*2 #y elif run==2: l[0]=-l[0] #x l[1]=l[1]*2 #y elif run==3: l[0]=-l[0] #x l[1]=-l[1] #y else: l[0]=l[0]*2 #x l[1]=-l[1] #y return l def pauseState(state): global pause pause=state print "Pause:{0}".format(pause) def fightArena(): robots=(r1,r2) pygame.init() pygame.mixer.music.load('laser.wav') window = pygame.display.set_mode((w,h)) screen = pygame.display.get_surface() labelfont=pygame.font.Font("C:\\Windows\\Fonts\\ARIALN.TTF", 14) run1=0 # robot is not running run2=0 # robot is not running rob1Head=[0]*2 rob2Head=[0]*2 loop=True while loop: #Clear screen.fill(BLACK) screen.blit(background, backgroundRect) rob1Head[0]=r1.x+10 rob1Head[1]=r1.y+10 rob2Head[0]=r2.x+10 rob2Head[1]=r2.y+10 # if r1.loadWp()!=0: #follow enemy if weapon loaded # r1.step(r2.getPos()[0],r2.getPos()[1]) # else: #run if weapon is unloaded # r1.step(-r2.getPos()[0],-r2.getPos[1]) # if r1.loadWp()!=0: #follow enemy if weapon loaded # r2.step(r1.getPos()[0],r1.getPos()[1]) # else: #run if weapon is unloaded # r2.step(-r1.getPos()[0],-r1.getPos()[1]) #===================== Robot 1========================== if r1.inrange(r2.getPos()[0],r2.getPos()[1]): #check if enemy in range if r1.loadWp()!=0: #shoot enemy if in range run1=1 bam=r1.shoot() pygame.mixer.music.play(0,0) if bam: r1.hitStatus='Hit!' else: r1.hitStatus='Miss!' #Draw laser green pygame.draw.line(screen, GREEN, rob1Head, rob2Head,3) if r2.hp.update(bam)==0: #end game if robot dead loop=False pygame.quit() return 'Robot 1' elif run1==1 and r1.loadWp()==0: #run if weapon is unloaded r1.status='Run for my virtual life!' run1=0 #set the running state r1.runXY[0]=r1.x r1.runXY[1]=r1.y r1.runXY=RunXY(r1.runXY) r1.step(r1.runXY[0],r1.runXY[1]) else: #keep running r1.step(r1.runXY[0],r1.runXY[1]) else: if r1.loadWp()!=0: # follow enemy if weapon loaded r1.status='Chasing enemy!' r1.step(r2.getPos()[0],r2.getPos()[1]) elif run1==1: #run if weapon is unloaded run1=0 #set the running state r1.runXY[0]=r1.x r1.runXY[1]=r1.y r1.runXY=RunXY(r1.runXY) r1.step(r1.runXY[0],r1.runXY[1]) else: #keep running r1.step(r1.runXY[0],r1.runXY[1]) #===================== Robot 2 ========================== if r2.inrange(r1.getPos()[0],r1.getPos()[1]): if r2.loadWp()!=0: #shoot enemy if in range run2=1 bom=r2.shoot() pygame.mixer.music.play(0,0) if bom: r2.hitStatus='Hit!' else: r2.hitStatus='Miss!' #draw laser red pygame.draw.line(screen, RED, rob1Head, rob2Head,3) if r1.hp.update(bom)==0: #end game if roobot dead loop=False pygame.quit() return 'Robot 2' elif run2==1 and r2.loadWp()==0: #run if weapon is unloaded run2=0 #set the running state r2.status='Run for my virtual life!' r2.runXY[0]=r2.x r2.runXY[1]=r2.y r2.runXY=RunXY(r2.runXY) r2.step(r2.runXY[0],r2.runXY[1]) else: #keep running r2.step(r2.runXY[0],r2.runXY[1]) else: if r2.loadWp()!=0: # followe enemy if weapon loaded r2.status='Chasing enemy!' r2.step(r1.getPos()[0],r1.getPos()[1]) elif run2==1: #run if weapon is unloaded run2=0 #set the running state r2.runXY[0]=r2.x r2.runXY[1]=r2.y r2.runXY=RunXY(r2.runXY) r2.step(r2.runXY[0],r2.runXY[1]) else: #keep running r2.step(r2.runXY[0],r2.runXY[1]) for r in robots: if r.id==1: screen.blit(robo1,r.getPos()[:2]) else: screen.blit(robo2,r.getPos()[:2]) if r.x<=25: r.x=25 r.runXY[0]=-r.runXY[0] if r.x>=w-25: r.x=w-25 r.runXY[0]=-r.runXY[0] if r.y<=125: r.y=125 r.runXY[1]=-r.runXY[1] if r.y>=h-25: r.y=h-25 r.runXY[1]=-r.runXY[1] robot='Robot %d'%(r.id) name=labelfont.render(robot,True,(255,255,255)) screen.blit(name,(r.x,r.y+20)) printStats(r,labelfont,screen) pygame.display.flip() for event in pygame.event.get(): if event.type is pygame.QUIT: loop=False clock.tick(30) pygame.quit()
Python
import sys import pygame import pymysql conn=pymysql.connect(host='www.freesqldatabase.com', port=3306, user='sql01_64191', passwd='**********', db='sql01_6419coadaf') cur=conn.cursor() def listChampions(screen,labelfont): cur.execute("select * from robots2 where GrandTitle>0 order by GrandTitle desc LIMIT 0,3") i=0 for l in cur: i+=1 robot='Robot %d'%(l[0]) name=labelfont.render(robot,True,(255,255,255)) weaponDet='Weapon: {0} dmg, {1} range, {2}% acc, {3} seconds load time'.format(l[2]+1,l[3]+1,(l[4]+1)*10,1) weapon=labelfont.render(weaponDet,True,(255,255,255)) hpDet='Hp: {0} total Hp'.format(l[1]+1) hp=labelfont.render(hpDet,True,(255,255,255)) titleDet='Titles: {0} Tournament Titles'.format(l[5]) title=labelfont.render(titleDet,True,(255,255,255)) screen.blit(name,(20,i*100+40)) screen.blit(weapon,(20,i*100+55)) screen.blit(hp,(20,i*100+70)) screen.blit(title,(20,i*100+85)) def hof(): pygame.init() background = pygame.image.load("champs.bmp") backgroundRect = background.get_rect() size = (width, height) = background.get_size() screen = pygame.display.set_mode(size) labelfont=pygame.font.Font("C:\\Windows\\Fonts\\ARIALN.TTF", 14) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() screen.blit(background, backgroundRect) listChampions(screen,labelfont) pygame.display.flip()
Python
import pymysql conn=pymysql.connect(host='www.freesqldatabase.com', port=3306, user='sql01_64191', passwd='**********', db='sql01_6419coadaf') cur=conn.cursor() def checkR(hp,dmg,acc,range1,Rtime): l=cur.execute('select * from robots1 where health={0} and damage={1} and range={2} and accuracy={3}'.format(hp,dmg,range1,acc)) if l: for row in cur: return (row[6],row[7]) else: cur.execute('INSERT INTO robots1 (health, rtime, damage, range, accuracy) VALUES ({0},{1},{2},{3},{4})'.format(hp,Rtime,dmg,range1,acc)) return (0,0) def updateWin(hp,dmg,acc,range1): cur.execute("update robots1 set Wins=Wins+1 where health={0} and damage={1} and range={2} and accuracy={3}".format(hp,dmg,range1,acc)) def updateLoss(hp,dmg,acc,range1): cur.execute("update robots1 set Losses=Losses+1 where health={0} and damage={1} and range={2} and accuracy={3}".format(hp,dmg,range1,acc))
Python
#!/usr/bin/env python import math import random from time import clock, time from weapon import * from health import * class Robot(object): def __init__(self,id,x,y,angle,hp,wp,win=0,loss=0): self.id=id self.x=x self.y=y self.angle=angle self.hp=hp self.wp=wp self.time=0 self.runXY=[0]*2 self.status='Doing something' self.hitStatus='None' self.win=win self.loss=loss def getPos(self): return (self.x,self.y, self.angle) def forward(self,distance): #move forward 'distance' units along 'angle' #by default, an angle of '0' faces the bot to the right of the screen self.x=self.x+math.cos(self.angle)*distance self.y=self.y+math.sin(self.angle)*distance def inrange(self,x2,y2): #check to see if any of the bots are in range to shoot if math.sqrt(((self.x-x2)**2+(self.y-y2)**2))<self.wp.range: return 1 else: return 0 def loadWp(self): if int(time()-self.time)>self.wp.rtime: return 1 else : return 0 def shoot(self): if self.loadWp(): self.time=time() #store moment of shooting if random.randint(1,101)<self.wp.acc*10: return self.wp.dmg else: return 0 def distance(x1,y1,x2,y2): return math.sqrt(((x1-x2)**2+(y1-y2)**2)) class RobotC(Robot): def step(self,x,y): self.angle+=0.2*math.atan2(y-self.y,x-self.x) self.angle/=1.2 self.forward(2) def getName(self): return "Almost Perfect robot" def getDetails(self): print "ID:{0}".format(self.id) print "Weapon:" self.wp.getDet() print "Hp:" self.hp.getDet() print "\n"
Python
#================Tournament generator========= #Generate the matches for the robots import random import pymysql conn=pymysql.connect(host='www.freesqldatabase.com', port=3306, user='sql01_64191', passwd='**********', db='sql01_6419coadaf') cur=conn.cursor() cur2=conn.cursor() lenght=cur.execute("select * from round6") def check(l): ok=0 for i in l: if i==1: ok=1 return ok def generate(l): r1=random.randint(1,lenght) if(l[r1]==1): #check oponent to see if available l[r1]=0 else: while (l[r1]==0): #keep looking for an available robot r1=random.randint(1,lenght) l[r1]=0 cur2.execute("select winner from round6 where id={0}".format(r1)) for idRob in cur2: r1=idRob[0] r2=random.randint(1,lenght) if(l[r2]==1): #check oponent to see if available l[r2]=0 else: while (l[r2]==0): #keep looking for a second robot r2=random.randint(1,lenght) l[r2]=0 cur2.execute("select winner from round6 where id={0}".format(r2)) for idRob in cur2: r2=idRob[0] cur.execute("INSERT INTO final (robot1, robot2) VALUES (%d, %d)"%(r1,r2)) return check(l) def finalRound(): cur.execute("TRUNCATE TABLE final") l=[1]*(lenght+1) #store if a robot has a match already planned l[0]=0 loop=generate(l) while(loop): loop=generate(l) print "===The END==="
Python
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
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: 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/>. ## from handlers.AuthenticatedHandler import * class CommunityAddRelated(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/community/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/community/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/community/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/community.add.related?m=Already_exists') return if community_from is None: self.values['m'] = "Source community not found" self.render('templates/module/community/community-add-related.html') return if community_to is None: self.values['m'] = "Target community not found" self.render('templates/module/community/community-add-related.html') return self.create_related(community_from, community_to) self.create_related(community_to, community_from) self.redirect('/module/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> # 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> # (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