def get(self): ToBeAddedUserId = self.request.path[11:] ## Please be awared that ItemId here is a string! ToBeAddedUser = tarsusaUser.get_by_id(int(ToBeAddedUserId)) ## Get Current User. CurrentUser = self.get_user_db() #I can use a reduct here. AlreadyAddedAsFriend = False for eachFriend in CurrentUser.friends: if eachFriend == ToBeAddedUser.key(): AlreadyAddedAsFriend = True if ToBeAddedUser.key() != CurrentUser.key() and AlreadyAddedAsFriend == False: CurrentUser.friends.append(ToBeAddedUser.key()) CurrentUser.put() else: ## You can't add your self! and You can add a person twice! pass memcache.event('addfriend', CurrentUser.key().id()) self.redirect('/FindFriend')
def get(self): # Permission check is very important. ToBeRemovedUserId = self.request.path[14:] ## Please be awared that ItemId here is a string! ToBeRemovedUser = tarsusaUser.get_by_id(int(ToBeRemovedUserId)) # New CheckLogin code built in tarsusaRequestHandler if self.chk_login(): CurrentUser = self.get_user_db() AlreadyAddedAsFriend = False for eachFriend in CurrentUser.friends: if eachFriend == ToBeRemovedUser.key(): AlreadyAddedAsFriend = True if ToBeRemovedUser.key() != CurrentUser.key() and AlreadyAddedAsFriend == True: CurrentUser.friends.remove(ToBeRemovedUser.key()) CurrentUser.put() else: ## You can't remove your self! ## and You can not remove a person that are not your friend! pass memcache.event('removefriend', CurrentUser.key().id()) self.redirect('/FindFriend')
def DoneItem(ItemId, UserId, Misc): #DoneItem function specially designed for API calls. #Duplicated Code from tarsusaItemCore, refactor needed in the future. ## This function won't check permission for login, for external API usage. #Instead, you need to provide a userid, and the function will check wheather this user have the permission to do so. #Which indicates that you definately need a permission check mechanism when you calling this function from outside. DoneYesterdaysDailyRoutine = False if Misc == 'y': DoneYesterdaysDailyRoutine = True tItem = tarsusaItem.get_by_id(int(ItemId)) if tItem.usermodel.key().id() == int(UserId): ## Check User Permission to done this Item if tItem.routine == 'none': ## if this item is not a routine item. tItem.donedate = datetime.datetime.now() tItem.done = True tItem.put() memcache.event('doneitem', int(UserId)) else: ## if this item is a routine item. NewlyDoneRoutineItem = tarsusaRoutineLogItem(routine=tItem.routine) NewlyDoneRoutineItem.user = users.get_current_user() NewlyDoneRoutineItem.routineid = int(ItemId) if DoneYesterdaysDailyRoutine == True: NewlyDoneRoutineItem.donedate = datetime.datetime.now() - datetime.timedelta(days=1) #NewlyDoneRoutineItem.routine = tItem.routine # The done date will be automatically added by GAE datastore. #To Check whether this routine item was done today. #Prevention to add duplicate tarsusaRoutineLogItem. one_day = datetime.timedelta(days=1) yesterday = datetime.datetime.combine(datetime.date.today() - one_day, datetime.time(0)) if DoneYesterdaysDailyRoutine == False: tarsusaRoutineLogItemCollection_CheckWhetherBeDone = db.GqlQuery("SELECT * FROM tarsusaRoutineLogItem WHERE routineid = :1 and donedate > :2 and donedate < :3", int(ItemId), yesterday + one_day ,datetime.datetime.now()) memcache.event('doneroutineitem_daily_today', int(UserId)) else: tarsusaRoutineLogItemCollection_CheckWhetherBeDone = db.GqlQuery("SELECT * FROM tarsusaRoutineLogItem WHERE routineid = :1 and donedate > :2 and donedate < :3", int(ItemId), yesterday - one_day , datetime.datetime.combine(datetime.date.today(), datetime.time(0)) - datetime.timedelta(seconds=1)) memcache.event('doneroutineitem_daily_yesterday', int(UserId)) if not tarsusaRoutineLogItemCollection_CheckWhetherBeDone.count() >= 1: NewlyDoneRoutineItem.put() memcache.event('refresh_dailyroutine', int(UserId)) return 0 #self.write(tarsusaRoutineLogItemCollection_CheckWhetherBeDone.count()) else: return 1
def RemoveItem(ItemId, UserId, Misc): tItem = tarsusaItem.get_by_id(int(ItemId)) if tItem is not None: if tItem.usermodel.key().id() == int(UserId): ## Check User Permission to undone this Item if tItem.public != 'none': memcache.event('deletepublicitem', int(UserId)) if tItem.routine == 'none': ## if this item is not a routine item. tItem.delete() memcache.event('deleteitem', int(UserId)) else: ## Del a RoutineLog item! ## All its doneRoutineLogWillBeDeleted! ## wether there will be another log for this? :-) for record nerd? ## This is a daily routine, and we are going to delete it. ## For DailyRoutine, now I just count the matter of deleting today's record. ## the code for handling the whole deleting routine( delete all concerning routine log ) will be added in future # GAE can not make dateProperty as query now! There is a BUG for GAE! # http://blog.csdn.net/kernelspirit/archive/2008/07/17/2668223.aspx tarsusaRoutineLogItemCollection_ToBeDeleted = db.GqlQuery("SELECT * FROM tarsusaRoutineLogItem WHERE routineid = :1", int(ItemId)) for result in tarsusaRoutineLogItemCollection_ToBeDeleted: result.delete() tItem.delete() memcache.event('deleteroutineitem_daily', int(UserId)) #ShardingCounter shardingcounter.increment("tarsusaItem", "minus") return 0 else: #Authentication Failed. return 1 else: #Authentication Failed. return 1
def AddItem(UserId, rawName, rawComment='', rawRoutine='', rawPublic='private', rawInputDate='', rawTags=None): CurrentUser = tarsusaUser.get_by_id(int(UserId)) #Check if comment property's length is exceed 500 try: if len(rawComment)>500: item_comment = rawComment[:500] else: item_comment = rawComment except: item_comment = '' try: # The following code works on GAE platform. # it is weird that under GAE, it should be without .decode, but on localhost, it should add them! item2beadd_name = cgi.escape(rawName) try: item2beadd_comment = cgi.escape(item_comment) except: item2beadd_comment = '' try: tarsusaItem_Tags = cgi.escape(rawTags).split(",") except: tarsusaItem_Tags = None #routine is a must provided in template, by type=hidden item2beadd_routine = cgi.escape(rawRoutine) first_tarsusa_item = tarsusaItem(user=CurrentUser.user, name=item2beadd_name, comment=item2beadd_comment, routine=rawRoutine) first_tarsusa_item.public = rawPublic first_tarsusa_item.done = False # DATETIME CONVERTION TRICKS from http://hi.baidu.com/huazai_net/blog/item/8acb142a13bf879f023bf613.html # The easiest way to convert this to a datetime seems to be; #datetime.date(*time.strptime("8/8/2008", "%d/%m/%Y")[:3]) # the '*' operator unpacks the tuple, producing the argument list. # also learned sth from: http://bytes.com/forum/thread603681.html # Logic: If the expectdate is the same day as today, It is none. try: expectdatetime = None expectdate = datetime.date(*time.strptime(rawInputDate,"%Y-%m-%d")[:3]) if expectdate == datetime.datetime.date(datetime.datetime.today()): expectdatetime == None else: currenttime = datetime.datetime.time(datetime.datetime.now()) expectdatetime = datetime.datetime(expectdate.year, expectdate.month, expectdate.day, currenttime.hour, currenttime.minute, currenttime.second, currenttime.microsecond) except: expectdatetime = None first_tarsusa_item.expectdate = expectdatetime ## the creation date will be added automatically by GAE datastore first_tarsusa_item.usermodel = CurrentUser #first_tarsusa_item.put() try: tarsusaItem_Tags = cgi.escape(rawTags).split(",") except: tarsusaItem_Tags = None except: #Something is wrong when adding the item. self.write("sth is wrong.") #memcache related. Clear ajax_DailyroutineTodayCache after add a daily routine item if item2beadd_routine == 'daily': memcache.event('addroutineitem_daily', CurrentUser.key().id()) else: memcache.event('additem', CurrentUser.key().id()) if cgi.escape(rawPublic) != 'private': memcache.event('addpublicitem', CurrentUser.key().id()) if tarsusaItem_Tags != None: for each_tag_in_tarsusaitem in tarsusaItem_Tags: ## It seems that these code above will create duplicated tag model. ## TODO: I am a little bit worried when the global tags are exceed 1000 items. catlist = db.GqlQuery("SELECT * FROM Tag WHERE name = :1 LIMIT 1", each_tag_in_tarsusaitem) try: each_cat = catlist[0] except: try: #added this line for Localhost GAE runtime... each_cat = Tag(name=each_tag_in_tarsusaitem.decode('utf-8')) each_cat.put() except: each_cat = Tag(name=each_tag_in_tarsusaitem) each_cat.put() first_tarsusa_item.tags.append(each_cat.key()) # To Check whether this user is using this tag before. tag_AlreadyUsed = False for check_whether_used_tag in CurrentUser.usedtags: item_check_whether_used_tag = db.get(check_whether_used_tag) if item_check_whether_used_tag != None: if each_cat.key() == check_whether_used_tag or each_cat.name == item_check_whether_used_tag.name: tag_AlreadyUsed = True else: if each_cat.key() == check_whether_used_tag: tag_AlreadyUsed = True if tag_AlreadyUsed == False: CurrentUser.usedtags.append(each_cat.key()) first_tarsusa_item.put() CurrentUser.put() #ShardingCounter shardingcounter.increment("tarsusaItem") return first_tarsusa_item.key().id()
def UndoneItem(ItemId, UserId, Misc): #UndoneItem function specially designed for API calls. #Duplicated Code from tarsusaItemCore, refactor needed in the future. ## This function won't check permission for login, for external API usage. #Instead, you need to provide a userid, and the function will check wheather this user have the permission to do so. #Which indicates that you definately need a permission check mechanism when you calling this function from outside. # Permission check is very important. UndoneYesterdaysDailyRoutine = False if Misc == 'y': UndoneYesterdaysDailyRoutine = True ## Please be awared that ItemId here is a string! tItem = tarsusaItem.get_by_id(int(ItemId)) if tItem.usermodel.key().id() == int(UserId): ## Check User Permission to undone this Item if tItem.routine == 'none': ## if this item is not a routine item. tItem.donedate = "" tItem.done = False tItem.put() #----- memcache.event('undoneitem', int(UserId)) #return 0 indicates it's ok. return 0 else: if tItem.routine == 'daily': if UndoneYesterdaysDailyRoutine != True: del tItem.donetoday tItem.put() memcache.event('undoneroutineitem_daily_today', int(UserId)) ## Please Do not forget to .put()! ## This is a daily routine, and we are going to undone it. ## For DailyRoutine, now I just count the matter of deleting today's record. ## the code for handling the whole deleting routine( delete all concerning routine log ) will be added in future # GAE can not make dateProperty as query now! There is a BUG for GAE! # http://blog.csdn.net/kernelspirit/archive/2008/07/17/2668223.aspx tarsusaRoutineLogItemCollection_ToBeDeleted = db.GqlQuery("SELECT * FROM tarsusaRoutineLogItem WHERE routineid = :1 and donedate < :2", int(ItemId), datetime.datetime.now()) #It has been fixed. For just deleting TODAY's routinelog. one_day = datetime.timedelta(days=1) yesterday = datetime.datetime.now() - one_day for result in tarsusaRoutineLogItemCollection_ToBeDeleted: if result.donedate < datetime.datetime.now() and result.donedate.date() != yesterday.date() and result.donedate > yesterday: result.delete() #return 0 indicates it's ok. return 0 else: # Undone Yesterday's daily routine item. memcache.event('undoneroutineitem_daily_yesterday', int(UserId)) try: del tItem.doneyesterday tItem.put() except: pass one_day = datetime.timedelta(days=1) yesterday = datetime.datetime.combine(datetime.date.today() - one_day,datetime.time(0)) tarsusaRoutineLogItemCollection_ToBeDeleted = db.GqlQuery("SELECT * FROM tarsusaRoutineLogItem WHERE routineid = :1 and donedate > :2 and donedate < :3", int(ItemId), yesterday, datetime.datetime.today()) ## CAUTION: SOME ITEM MAY BE DONE IN THE NEXT DAY, SO THE DONEDATE WILL BE IN NEXT DAY ## THEREFORE donedate>:2 and donedate<datetime.datetime.today() <--today() is datetime for result in tarsusaRoutineLogItemCollection_ToBeDeleted: if result.donedate < datetime.datetime.now() and result.donedate.date() == yesterday.date(): #and result.donedate.date() > datetime.datetime.date(datetime.datetime.now() - datetime.timedelta(days=2)): result.delete() else: pass return 0 else: #Authentication failed. return 1
def post(self): tItemId = self.request.path[10:] ## Please be awared that tItemId here is a string! tItem = tarsusaItem.get_by_id(int(tItemId)) #Check if comment property's length is exceed 500 if len(self.request.get('comment')) > 500: item_comment = self.request.get('comment')[:500] else: item_comment = self.request.get('comment') # Permission check is very important. # New CheckLogin code built in tarsusaRequestHandler if self.chk_login: CurrentUser = self.get_user_db() else: self.redirect('/') if tItem.user == users.get_current_user(): #Update Expectdate. if self.request.get('inputDate') == 'None': expectdatetime = None else: expectdate = datetime.date(*time.strptime( self.request.get('inputDate'), "%Y-%m-%d")[:3]) currenttime = datetime.datetime.time(datetime.datetime.now()) expectdatetime = datetime.datetime( expectdate.year, expectdate.month, expectdate.day, currenttime.hour, currenttime.minute, currenttime.second, currenttime.microsecond) tItem.expectdate = expectdatetime tItem.name = cgi.escape(self.request.get('name')) tItem.comment = cgi.escape(item_comment) tItem.routine = cgi.escape(self.request.get('routine')) tItem.public = cgi.escape(self.request.get('public')) tItem.usermodel = CurrentUser tItem.put() #memcache related. Clear ajax_DailyroutineTodayCache after add a daily routine item if cgi.escape(self.request.get('routine')) == 'daily': memcache.event('editroutineitem_daily', CurrentUser.key().id()) else: memcache.event('editroutineitem', CurrentUser.key().id()) if cgi.escape(self.request.get('public')) != 'none': memcache.event('editpublicitem', CurrentUser.key().id()) ## Deal with Tags. tarsusaItem_Tags = cgi.escape(self.request.get('tags')).split(",") # Hard to find a way to clear this list. tItem.tags = [] tItem.put() for each_tag_in_tarsusaitem in tarsusaItem_Tags: ## TODO: I am a little bit worried when the global tags are exceed 1000 items. catlist = db.GqlQuery( "SELECT * FROM Tag WHERE name = :1 LIMIT 1", each_tag_in_tarsusaitem) try: each_cat = catlist[0] except: each_cat = Tag(name=each_tag_in_tarsusaitem) each_cat.put() tItem.tags.append(each_cat.key()) # To Check whether this user is using this tag before. tag_AlreadyUsed = False for check_whether_used_tag in CurrentUser.usedtags: item_check_whether_used_tag = db.get( check_whether_used_tag) if item_check_whether_used_tag != None: if each_cat.key( ) == check_whether_used_tag or each_cat.name == item_check_whether_used_tag.name: tag_AlreadyUsed = True else: if each_cat.key() == check_whether_used_tag: tag_AlreadyUsed = True if tag_AlreadyUsed == False: CurrentUser.usedtags.append(each_cat.key()) tItem.put() CurrentUser.put() #Redirect specificly for mobile version. if re.search('/m/', self.referer): #self.write(self.referer) self.redirect("/i/" + str(tItem.key().id())) else: self.write('Sorry, Your session is out of time.')
def post(self): tItemId = self.request.path[10:] ## Please be awared that tItemId here is a string! tItem = tarsusaItem.get_by_id(int(tItemId)) #Check if comment property's length is exceed 500 if len(self.request.get('comment'))>500: item_comment = self.request.get('comment')[:500] else: item_comment = self.request.get('comment') # Permission check is very important. # New CheckLogin code built in tarsusaRequestHandler if self.chk_login: CurrentUser = self.get_user_db() else: self.redirect('/') if tItem.user == users.get_current_user(): #Update Expectdate. if self.request.get('inputDate') == 'None': expectdatetime = None else: expectdate = datetime.date(*time.strptime(self.request.get('inputDate'),"%Y-%m-%d")[:3]) currenttime = datetime.datetime.time(datetime.datetime.now()) expectdatetime = datetime.datetime(expectdate.year, expectdate.month, expectdate.day, currenttime.hour, currenttime.minute, currenttime.second, currenttime.microsecond) tItem.expectdate = expectdatetime tItem.name = cgi.escape(self.request.get('name')) tItem.comment = cgi.escape(item_comment) tItem.routine = cgi.escape(self.request.get('routine')) tItem.public = cgi.escape(self.request.get('public')) tItem.usermodel = CurrentUser tItem.put() #memcache related. Clear ajax_DailyroutineTodayCache after add a daily routine item if cgi.escape(self.request.get('routine')) == 'daily': memcache.event('editroutineitem_daily', CurrentUser.key().id()) else: memcache.event('editroutineitem', CurrentUser.key().id()) if cgi.escape(self.request.get('public')) != 'none': memcache.event('editpublicitem', CurrentUser.key().id()) ## Deal with Tags. tarsusaItem_Tags = cgi.escape(self.request.get('tags')).split(",") # Hard to find a way to clear this list. tItem.tags = [] tItem.put() for each_tag_in_tarsusaitem in tarsusaItem_Tags: ## TODO: I am a little bit worried when the global tags are exceed 1000 items. catlist = db.GqlQuery("SELECT * FROM Tag WHERE name = :1 LIMIT 1", each_tag_in_tarsusaitem) try: each_cat = catlist[0] except: each_cat = Tag(name=each_tag_in_tarsusaitem) each_cat.put() tItem.tags.append(each_cat.key()) # To Check whether this user is using this tag before. tag_AlreadyUsed = False for check_whether_used_tag in CurrentUser.usedtags: item_check_whether_used_tag = db.get(check_whether_used_tag) if item_check_whether_used_tag != None: if each_cat.key() == check_whether_used_tag or each_cat.name == item_check_whether_used_tag.name: tag_AlreadyUsed = True else: if each_cat.key() == check_whether_used_tag: tag_AlreadyUsed = True if tag_AlreadyUsed == False: CurrentUser.usedtags.append(each_cat.key()) tItem.put() CurrentUser.put() #Redirect specificly for mobile version. if re.search('/m/', self.referer): #self.write(self.referer) self.redirect("/i/" + str(tItem.key().id())) else: self.write('Sorry, Your session is out of time.')