Ejemplo n.º 1
0
def verify_UserApi(userid, userapikey):
    import hashlib
    import service
    #To Verify UserApi, the Authentication process.
    
    #To check whether this user is existed.
    ThisUser = tarsusaUser.get_by_id(userid)
    if ThisUser == None:
        return False

    #Check with API Usage.
    UserApiUsage = memcache.get_item("userapiusage", int(userid))
    if UserApiUsage >= global_vars['apilimit']:
        #Api Limitation exceed.
        #self.write('<h1>API Limitation exceed.</h1>')
        return False
    else:
        if hashlib.sha256(ThisUser.apikey).hexdigest() == userapikey:
            #Should use log to monitor API usage.
            #Also there should be limitation for the apicalls/per hour.
            if UserApiUsage == None:
                UserApiUsage = 0
            UserApiUsage += 1
            memcache.set_item("userapiusage", UserApiUsage, int(userid))
            return True
        else:
            #Authentication Failed.
            return False
Ejemplo n.º 2
0
    def get(self):
        ## Homepage for Non-Registered Users.
        ## Since this page will be shown often to the anonymous visitors, and the information can be shown in not actully real-time.
        ## Therefore Memcache implemented.
        ## I can't figure out how to use get_multi so I just cache the whole ajaxpage output. 
        
        ## Thinking of to have an implementation of such Global memcache items
        IsCachedAnonymousWelcomePage = memcache.get_item('strCachedAnonymousWelcomePage', 'global')
        
        if IsCachedAnonymousWelcomePage:
            
            strCachedAnonymousWelcomePage = IsCachedAnonymousWelcomePage

        else:

            ## the not equal != is not supported!
            tarsusaItemCollection_UserToDoItems = db.GqlQuery("SELECT * FROM tarsusaItem WHERE public = 'public' and routine = 'none' and done = False ORDER BY date DESC LIMIT 9")

            tarsusaItemCollection_UserDoneItems = db.GqlQuery("SELECT * FROM tarsusaItem WHERE public = 'public' and routine = 'none' and done = True ORDER BY donedate DESC LIMIT 9")

            template_values = {
                'UserNickName': '访客',
                'tarsusaItemCollection_UserToDoItems': tarsusaItemCollection_UserToDoItems,
                'tarsusaItemCollection_UserDoneItems': tarsusaItemCollection_UserDoneItems,
             }
            
            #Manupilating Templates 
            path = os.path.join(os.path.dirname(__file__), 'pages/ajaxpage_anonymousbottomcontents.html')   
            strCachedAnonymousWelcomePage = template.render(path, template_values)
            
            memcache.set_item("strCachedAnonymousWelcomePage", strCachedAnonymousWelcomePage, 'global')

        self.response.out.write(strCachedAnonymousWelcomePage)
Ejemplo n.º 3
0
    def get(self):
        if self.chk_login():
            CurrentUser = self.get_user_db()
        
        cachedUserItemlist = memcache.get_item("itemlist", CurrentUser.key().id())
        if cachedUserItemlist is not None:
            strcachedUserItemlist = cachedUserItemlist
        else:   
            tarsusaItemCollection_UserToDoItems = db.GqlQuery("SELECT * FROM tarsusaItem WHERE user = :1 and routine = 'none' and done = False ORDER BY date DESC LIMIT 6", users.get_current_user())
            tarsusaItemCollection_UserDoneItems = db.GqlQuery("SELECT * FROM tarsusaItem WHERE user = :1 and routine = 'none' and done = True ORDER BY donedate DESC LIMIT 6", users.get_current_user())                                    

            template_values = {
                'UserLoggedIn': 'Logged In',
                'UserNickName': cgi.escape(CurrentUser.dispname),
                'UserID': CurrentUser.key().id(),
                'htmltag_today': datetime.datetime.date(datetime.datetime.now()), 
                'tarsusaItemCollection_UserToDoItems': tarsusaItemCollection_UserToDoItems,
                'tarsusaItemCollection_UserDoneItems': tarsusaItemCollection_UserDoneItems,
            }

            #Manupilating Templates 
            path = os.path.join(os.path.dirname(__file__), 'pages/ajaxpage_bottomcontents.html')
            strcachedUserItemlist = template.render(path, template_values)  
            memcache.set_item("itemlist", strcachedUserItemlist, CurrentUser.key().id())
            
        self.response.out.write(strcachedUserItemlist)
Ejemplo n.º 4
0
    def get(self):

        # New CheckLogin code built in tarsusaRequestHandler 
        if self.chk_login():
            CurrentUser = self.get_user_db()
            
            cachedUserFriendsActivities = memcache.get_item("friendstats", CurrentUser.key().id())
            if cachedUserFriendsActivities is not None:
                template_values = {
                                'UserLoggedIn': 'Logged In',
                                'UserFriendsActivities': cachedUserFriendsActivities,
                }
            else:
                
                ## SHOW YOUR FRIENDs Recent Activities
                ## Show only 9 items because we don't want to see a very long frontpage.
                UserFriendsItem_List = tarsusaCore.get_UserFriendStats(CurrentUser.key().id(),"","",9)
                
                template_values = {
                    'UserLoggedIn': 'Logged In',
                    'UserFriendsActivities': UserFriendsItem_List,
                }
                
                if not memcache.set_item("friendstats" ,UserFriendsItem_List, CurrentUser.key().id()):
                    logging.error('Cache set failed: Users_FriendStats')

            #Manupilating Templates 
            path = os.path.join(os.path.dirname(__file__), 'pages/ajaxpage_friendstats.html')
            self.response.out.write(template.render(path, template_values))
Ejemplo n.º 5
0
 def test_memcache_set_item(self):
     #entity = model.MyEntity(name='Foo')
     #self.assertEqual('Foo', entity.name)
     CurrentUserID = self.setup_key.id()  #setup_key is already a key
     self.assertEqual(
         True, memcache.set_item("testkey", "testvalue", CurrentUserID,
                                 3600))
Ejemplo n.º 6
0
def get_count_UserItemStats(userid):    
    #tarsusaCore.get_count_UserItemStats returns a dictionarty with the following properties(all int):
    #'UserTotalItems', 'UserToDoItems', 'UserDoneItems', 'UserDonePercentage'
    CurrentUser = tarsusaUser.get_by_id(int(userid))

    # Count User's Todos and Dones
    cachedUserItemStats = memcache.get_item("itemstats", CurrentUser.key().id())
    if cachedUserItemStats is not None:
        template_values = cachedUserItemStats
    else:
        # Count User's Todos and Dones
        tarsusaItemCollection_UserDoneItems = db.GqlQuery("SELECT * FROM tarsusaItem WHERE user = :1 and routine = 'none' and done = True ORDER BY date DESC", users.get_current_user())                
        tarsusaItemCollection_UserTodoItems = db.GqlQuery("SELECT * FROM tarsusaItem WHERE user = :1 and routine = 'none' and done = False ORDER BY date DESC", users.get_current_user())               

        # For Count number, It is said that COUNT in GAE is not satisfied and accuracy.
        # SO there is implemented a stupid way.
        UserTotalItems = tarsusaItemCollection_UserDoneItems.count() + tarsusaItemCollection_UserTodoItems.count()
        UserToDoItems = 0
        UserDoneItems = 0

        UserDonePercentage = 0.00

        UserDoneItems = tarsusaItemCollection_UserDoneItems.count() 
        UserToDoItems = tarsusaItemCollection_UserTodoItems.count()

        if UserTotalItems != 0:
            UserDonePercentage = UserDoneItems *100 / UserTotalItems 
        else:
            UserDonePercentage = 0.00

        template_values = {
            'UserTotalItems': UserTotalItems,
            'UserToDoItems': UserToDoItems,
            'UserDoneItems': UserDoneItems,
            'UserDonePercentage': UserDonePercentage,
        }
        
        #Changed since r111,
        #Now cache the Results from DB.
        memcache.set_item("itemstats", template_values, CurrentUser.key().id())


    return template_values 
Ejemplo n.º 7
0
def verify_AppModel(apiappid, apiservicekey):
    import hashlib
    
    if apiappid == None or apiservicekey == None:
        return False
    
    #To Verify AppModel, Applications that uses CheckNerds API.
    ThisApp = AppModel.get_by_id(apiappid)
    if ThisApp == None:
        return False
    
    #At beginning, will not turn this on.
    #if ThisApp.enable == False:
    #   return False

    #Check with API Usage.
    AppApiUsage = memcache.get("appapiusage" + str(apiappid))   
    if AppApiUsage >= ThisApp.api_limit:
        #Api Limitation exceed.
        self.write('<h1>API Limitation exceed.</h1>')       
        logging.info("AppID:" + str(apiappid) + ":" + cgi.escape(ThisApp.name) + " has exceed its API limitation.")
        return False
    else:
        if hashlib.sha256(ThisApp.servicekey).hexdigest() == apiservicekey:
            #Accept this App
            #------------------------
            #Manipulating API calls count.
            if AppApiUsage == None:
                memkey = "appapiuseage" + str(apiappid)
                AppApiUsage = 0
            AppApiUsage += 1
            memcache.set_item("appapiusage", AppApiUsage, int(apiappid))
            #------------------------
            #Below line could be turned off.
            logging.info("AppID:" + str(apiappid) + ":" + cgi.escape(ThisApp.name) + " accessed via API")
            #------------------------
            return True
        else:
            #Authentication Failed.
            #Should return a status number in the future.
            return False
Ejemplo n.º 8
0
    def get(self):
        IsCachedRecentRegisteredUsers = memcache.get_item('strCachedRecentRegisteredUsers', 'global')
        
        if IsCachedRecentRegisteredUsers:
            strCachedRecentRegisteredUsers = IsCachedRecentRegisteredUsers
        else:

            tarsusaUserCollection = db.GqlQuery("SELECT * FROM tarsusaUser ORDER BY datejoinin DESC LIMIT 9")
            strRecentUsers = ''
            if tarsusaUserCollection: 
                for each_RecentUser in tarsusaUserCollection:
                    if each_RecentUser.avatar:
                        strRecentUsers += '<span ' + 'style="line-height: 2em;"><a href="/user/' + cgi.escape(str(each_RecentUser.key().id())) +  '"><img src=/image?avatar=' + str(each_RecentUser.key().id()) + " width=32 height=32>"
                    else:
                        ## Show Default Avatar
                        strRecentUsers += '<span ' + 'style="line-height: 2em;"><a href="/user/' + cgi.escape(str(each_RecentUser.key().id())) +  '">' + "<img src='/img/default_avatar.jpg' width=32 height=32>"

                    try:
                        strRecentUsers += cgi.escape(each_RecentUser.dispname) + '</a></span>'
                    except:
                        strRecentUsers += cgi.escape(each_RecentUser.user.nickname()) + '</a></span>'

                    #Complicatied TimeStamp needs to be done.
                    #UserFriends += str(datetime.datetime.now() - each_Friend.datejoinin) 
                    strRecentUsers += '<br />'


            template_values = {
                'UserNickName': '访客',
                'tarsusaUser_RecentRegistered': strRecentUsers,
             }
            
            #Manupilating Templates 
            path = os.path.join(os.path.dirname(__file__), 'pages/ajaxpage_anonymousrecentregisteredusers.html')    
            strCachedRecentRegisteredUsers = template.render(path, template_values)
            
            memcache.set_item("strCachedRecentRegisteredUsers", strCachedRecentRegisteredUsers, 'global')

        self.response.out.write(strCachedRecentRegisteredUsers)
Ejemplo n.º 9
0
    def post(self):
        if self.chk_login():
            CurrentUser = self.get_user_db()
        else:
            self.redirect('/')

        cachedUserDailyroutineToday = memcache.get_item("dailyroutine_today", CurrentUser.key().id())
        #if cachedUserDailyroutineToday is not None:
        if cachedUserDailyroutineToday == True:
            strcachedUserDailyroutineToday = cachedUserDailyroutineToday
        else:           
            tarsusaItemCollection_DailyRoutine = tarsusaCore.get_dailyroutine(CurrentUser.key().id())
            
            ## Output the message for DailyRoutine
            '''
            template_tag_donealldailyroutine = ''               
            if Today_DoneRoutine == int(tarsusaItemCollection_DailyRoutine_count) and Today_DoneRoutine != 0:
                template_tag_donealldailyroutine = '<img src="img/favb16.png">恭喜,你完成了今天要做的所有事情!'
            elif Today_DoneRoutine == int(tarsusaItemCollection_DailyRoutine_count) - 1:
                template_tag_donealldailyroutine = '只差一项,加油!'
            elif int(tarsusaItemCollection_DailyRoutine_count) == 0:
                template_tag_donealldailyroutine = '还没有添加每日计划?赶快添加吧!<br />只要在添加项目时,将“性质”设置为“每天要做的”就可以了!'
'''

            template_values = {
            'UserLoggedIn': 'Logged In',                
            'UserNickName': cgi.escape(CurrentUser.dispname),
            'UserID': CurrentUser.key().id(),                   
            'tarsusaItemCollection_DailyRoutine': tarsusaItemCollection_DailyRoutine,
            #'htmltag_DoneAllDailyRoutine': template_tag_donealldailyroutine,
            'htmltag_today': datetime.datetime.date(datetime.datetime.now()), 
            }

            #Manupilating Templates 
            path = os.path.join(os.path.dirname(__file__), 'pages/ajaxpage_dailyroutine.html')
            strcachedUserDailyroutineToday = template.render(path, template_values)
            if not memcache.set_item("dailyroutinetoday", strcachedUserDailyroutineToday, CurrentUser.key().id()):
                logging.error('Cache set failed: ajax_ShowUserDailyRoutineToday')

        self.write(strcachedUserDailyroutineToday)
Ejemplo n.º 10
0
 def test_memcache_set_item(self):
     #entity = model.MyEntity(name='Foo')
     #self.assertEqual('Foo', entity.name)
     CurrentUserID = self.setup_key.id() #setup_key is already a key
     self.assertEqual(True, memcache.set_item("testkey","testvalue",CurrentUserID,3600))
Ejemplo n.º 11
0
def get_UserFriendStats(userid, startdate='', lookingfor='next', maxdisplayitems=15):
    
    #Get user's FriendStats
    #SHOW YOUR FRIENDs Recent Activities
    
    #lookingfor = 'next' to get the records > startdate
    #             'previous' to get the records <= startdate
    #actully you can not decide how many items will be displayed here. 15 will be a fixed number, maybe less than 15 will be displayed.

    #Have to add this limit for GAE's CPU limitation.
    MaxDisplayedItems = maxdisplayitems
    ThisUser = tarsusaUser.get_by_id(int(userid))
    
    #---
    userid = ThisUser.key().id()

    tarsusaUserFriendCollection = ThisUser.friends
    DisplayedDonelogDays = 1 

    UserFriendsItem_List = []

    if tarsusaUserFriendCollection:
        #first of all, CurrentUser should have some friends
    
        cached_user_friendstatus = memcache.get_item("friendstatus", int(userid))

        if cached_user_friendstatus is not None:

            return cached_user_friendstatus[:maxdisplayitems]

        else:

            for each_FriendKey in tarsusaUserFriendCollection:
                UsersFriend =  db.get(each_FriendKey)                       
                
                #Due to usermodel and other are applied in a later patch, some tarsusaItem may not have that property.
                #There maybe need to extend if we need more property from tarsusaItem.usermodel
                UsersFriendid = UsersFriend.key().id()
                try:
                    UsersFriendDispname = UsersFriend.dispname
                except:
                    UsersFriendDispname = UsersFriend.user.nickname()


                tarsusaItemCollection_UserFriendsRecentItems = db.GqlQuery("SELECT * FROM tarsusaItem WHERE user = :1 ORDER BY date DESC LIMIT 50", UsersFriend.user)

                for tarsusaItem_UserFriendsRecentItems in tarsusaItemCollection_UserFriendsRecentItems:
                    ## Check whether should show this item.
                    if tarsusaItem_UserFriendsRecentItems.public != 'private':                      
                        #Output Avatar Information
                        UserAvatar = '/img/default_avatar.jpg'
                        #Some of the older items may not have the usermodel property
                        try:
                            if tarsusaItem_UserFriendsRecentItems.usermodel.avatar:
                                UserAvatar = '/image?avatar=' + str(tarsusaItem_UserFriendsRecentItems.usermodel.key().id())
                        except:
                            UserAvatar = '/img/default_avatar.jpg'

                        ## Check whether this item had done.
                        if tarsusaItem_UserFriendsRecentItems.done == True:
                                friend_Item = {'id' : str(tarsusaItem_UserFriendsRecentItems.key().id()), 'name' : tarsusaItem_UserFriendsRecentItems.name, 'date' : str(tarsusaItem_UserFriendsRecentItems.donedate), 'comment' : tarsusaItem_UserFriendsRecentItems.comment, 'category' : 'done', 'userdispname': UsersFriendDispname, 'userid': UsersFriendid, 'avatar': UserAvatar}
                        else:
                            friend_Item = {'id' : str(tarsusaItem_UserFriendsRecentItems.key().id()), 'name' : tarsusaItem_UserFriendsRecentItems.name, 'date' : str(tarsusaItem_UserFriendsRecentItems.date), 'comment' : tarsusaItem_UserFriendsRecentItems.comment, 'category' : 'todo', 'userdispname': UsersFriendDispname, 'userid': UsersFriendid, 'avatar': UserAvatar}

                        UserFriendsItem_List.append(friend_Item)

            #sort the results:
            #Sort Algorithms from
            #http://www.lixiaodou.cn/?p=12
            length = len(UserFriendsItem_List)
            for i in range(0,length):
                for j in range(length-1,i,-1):
                        #Convert string to datetime.date
                        #http://mail.python.org/pipermail/tutor/2006-March/045729.html  
                        time_format = "%Y-%m-%d %H:%M:%S"
                        if datetime.datetime.fromtimestamp(time.mktime(time.strptime(UserFriendsItem_List[j]['date'][:-7], time_format))) > datetime.datetime.fromtimestamp(time.mktime(time.strptime(UserFriendsItem_List[j-1]['date'][:-7], time_format))):
                            temp = UserFriendsItem_List[j]
                            UserFriendsItem_List[j]=UserFriendsItem_List[j-1]
                            UserFriendsItem_List[j-1]=temp

            memcache.set_item("friendstatus", UserFriendsItem_List, int(userid))
            return UserFriendsItem_List[:maxdisplayitems]

    else:
        return None #This User don't have any friends.
Ejemplo n.º 12
0
    def get(self):
        
        #RSS Feed Code, leart from Plog, using PyRSS2Gen Module.

        userid = urllib.unquote(cgi.escape(self.request.path[6:-5]))  ## Get the username in the URL string such as /user/1234/feed
        
        ## Get this user.
        ViewUser = tarsusaUser.get_by_id(int(userid))
            

        UserNickName = '访客'
        outputStringUserAvatar = ''

        if ViewUser != None:
            
            IsCachedUserFeed = memcache.get_item('UserPublicFeed', ViewUser.key().id())
                
            if IsCachedUserFeed:
                userfeed_publicitems = IsCachedUserFeed
            else:
    
                userfeed_publicitems = []
                
                #should look at the routinelog at first.
                #new feed output supports public daily routine.
                tarsusaItemCollection_RecentDoneDailyRoutines = db.GqlQuery("SELECT * FROM tarsusaRoutineLogItem ORDER by donedate DESC LIMIT 10")
                for each_DailyRoutineLogItem in tarsusaItemCollection_RecentDoneDailyRoutines:              
                    RoutineItem = tarsusaItem.get_by_id(each_DailyRoutineLogItem.routineid)
                    if RoutineItem.user == ViewUser.user and RoutineItem.public == 'public':
                        str_title = ViewUser.dispname + " 今天完成了 ".decode('utf-8') + tarsusaItem.get_by_id(each_DailyRoutineLogItem.routineid).name
                        item_url = '%s/item/%d' % (self.request.host_url, RoutineItem.key().id())
                        
                        str_title = ViewUser.dispname + " 今天完成了 ".decode('utf-8') + RoutineItem.name
                        try:
                            # some very old items may not have usermodel property 
                            str_author = RoutineItem.usermodel.dispname
                        except:
                            str_author = RoutineItem.user.nickname()

                        userfeed_publicitems.append({
                                        'title': str_title,
                                        'author': str_author,
                                        'link': item_url,
                                        'description': '每日任务'.decode('utf-8'), #Later will be comment for each dailydone. 
                                        'pubDate': each_DailyRoutineLogItem.donedate,
                                        'guid': PyRSS2Gen.Guid(str_title + str(each_DailyRoutineLogItem.donedate))
                                        #categories
                                        })      

                
                #There is a force 15 limits for RSS feed.
                #Plog is setting this as an option in setting.
                tarsusaItemCollection_UserRecentPublicItems = db.GqlQuery("SELECT * FROM tarsusaItem WHERE user = :1 and public = 'public' ORDER BY date DESC LIMIT 15", ViewUser.user)
                #the code block below is a little bit duplicated, will find a way to make it simple in future. TODO
                for each_Item in tarsusaItemCollection_UserRecentPublicItems:
                    
                    try:
                        # some very old items may not have usermodel property 
                        str_author = each_Item.usermodel.dispname
                    except:
                        str_author = each_Item.user.nickname()
                    
                    item_url = '%s/item/%d' % (self.request.host_url, each_Item.key().id())

                    if each_Item.done == True:
                        str_title = ViewUser.dispname + " 完成了 ".decode('utf-8') + each_Item.name
                    else:
                        str_title = ViewUser.dispname + " 要做 ".decode('utf-8') + each_Item.name
                    
                    userfeed_publicitems.append({
                                        'title': str_title,
                                        'author': str_author,
                                        'link': item_url,
                                        'description':each_Item.comment,
                                        'pubDate': each_Item.date,
                                        'guid': PyRSS2Gen.Guid(item_url)
                                        #categories
                                        })                  

                #sort the results:
                #Sort Algorithms from
                #http://www.lixiaodou.cn/?p=12
                length = len(userfeed_publicitems)
                for i in range(0,length):
                    for j in range(length-1,i,-1):
                        #Convert string to datetime.date
                        #http://mail.python.org/pipermail/tutor/2006-March/045729.html  
                        time_format = "%Y-%m-%d %H:%M:%S"
                        #if datetime.datetime.fromtimestamp(time.mktime(time.strptime(userfeed_publicitems[j]['pubDate'][:-7], time_format))) > datetime.datetime.fromtimestamp(time.mktime(time.strptime(userfeed_publicitems[j-1]['pubDate'][:-7], time_format))):
                        if userfeed_publicitems[j]['pubDate'] > userfeed_publicitems[j-1]['pubDate']:
                            temp = userfeed_publicitems[j]
                            userfeed_publicitems[j]=userfeed_publicitems[j-1]
                            userfeed_publicitems[j-1]=temp
                
                
                memcache.set_item("UserPublicFeed", userfeed_publicitems, ViewUser.key().id(), 1800)
                #cache it for at least half an hour.


            publicItems = []
            for each in userfeed_publicitems:
                publicItems.append(PyRSS2Gen.RSSItem(
                                title = each['title'],
                                author = each['author'],
                                link = each['link'],
                                description = each['description'],
                                pubDate = each['pubDate'],
                                guid = each['guid']
                                ))

            
            rss = PyRSS2Gen.RSS2(
                title = "CheckNerds - " + ViewUser.dispname,
                link = self.request.host_url + '/user/' + str(ViewUser.key().id()),
                description = ViewUser.dispname + '最新的公开事项,在线个人事项管理——欢迎访问http://www.checknerds.com'.decode('utf-8'),
                lastBuildDate = datetime.datetime.utcnow(),
                items = publicItems
                )

            self.response.headers['Content-Type'] = 'application/rss+xml; charset=utf-8'
            rss_xml = rss.to_xml(encoding='utf-8')
            self.write(rss_xml)
Ejemplo n.º 13
0
    def get(self):

        username = urllib.unquote(cgi.escape(self.request.path[6:]))  ## Get the username in the URL string such as /user/1234
        ViewUser = None
        
        try:
            ## After URL style changed, Now won't allow username in URL, only accept id in URL.
            
            ## Get this user.
            q = db.GqlQuery("SELECT * FROM tarsusaUser WHERE userid = :1 LIMIT 1", int(username))
            ViewUser = q.get()

            if ViewUser == None:
                q = tarsusaUser.get_by_id(int(username))
                ViewUser = q
        except:
            self.redirect('/')

        UserNickName = '访客'
        outputStringUserAvatar = ''

        UserNonPrivateItemsList = ''
        UserFriends = []

        if ViewUser != None:
        
            ## Preparation
            ## Will be useed
            if ViewUser.avatar:
                outputStringUserAvatar = "<img src='/image?avatar=" + str(ViewUser.key().id()) + "' width=64 height=64>"
            else:
                outputStringUserAvatar = "<img src='/img/default_avatar.jpg' width=64 height=64>"
                
            outputStringUserMainPageTitle = ViewUser.dispname + "公开的项目".decode("utf-8")

            #-------------------------------------
            if not self.chk_login():
            
                #Not a login user, show only the public items.
                UserNickName = "访客"
                logictag_OneoftheFriendsViewThisPage = False
                CurrentUserIsOneofViewUsersFriends = False
                statusUserFriends = 'NotLogin'
                #Above tag will be recognized by template
                ViewedUserIsOneofCurrentUsersFriends = False

                #Check Whether there is usermainPage_publicitems_anony
                cachedUserMainPagePublicItemsAnony = memcache.get_item("mainpage_publicitems_anony", ViewUser.key().id())
                if cachedUserMainPagePublicItemsAnony is not None:
                    UserNonPrivateItemsList = cachedUserMainPagePublicItemsAnony
                else:
                    UserNonPrivateItemsList = tarsusaCore.get_UserNonPrivateItems(ViewUser.key().id(), 'public')
                

                template_values = {
                    'PrefixCSSdir': "../",
                    
                    'ViewedUserNickName': ViewUser.dispname,

                    'UserAvatarImage': outputStringUserAvatar,
                    
                    'statusViewedUserFriends': statusUserFriends,   
                    'UserJoinInDate': datetime.datetime.date(ViewUser.datejoinin),
                    'UserWebsite': ViewUser.website,
                    'UserMainPageUserTitle': outputStringUserMainPageTitle,
                    'UserNonPrivateItemsList': UserNonPrivateItemsList,
                    
                    'outputFeed': True,
                    'outputFeedTitle': ViewUser.dispname,
                    'outputFeedURL': "/user/" + str(ViewUser.key().id()) + "/feed",
                }

            
            else:               
                #User Login.
                
                #Check Whether CurrerentUser is one of ViewUser's friends
                UserNickName = ViewUser.dispname
                CurrentUser = self.get_user_db()

                CurrentUserIsOneofViewUsersFriends = False

                for each_Friend_key in ViewUser.friends:
                    if each_Friend_key == CurrentUser.key():
                        CurrentUserIsOneofViewUsersFriends = True
                        logictag_OneoftheFriendsViewThisPage = True

                ## Check whether the ViewedUser is a friend of CurrentUser.
                ## For AddUserAsFriend button.
                ViewedUserIsOneofCurrentUsersFriends = False

                for each_Friend_key in CurrentUser.friends:
                    if each_Friend_key == ViewUser.key():
                        ViewedUserIsOneofCurrentUsersFriends = True
            
                # Get user friend list
                cachedUserMainPageFriends = memcache.get_item("mainpage_friends", ViewUser.key().id())
                if cachedUserMainPageFriends is not None:
                    UserFriends = cachedUserMainPageFriends
                else:
                    # This is shown to all logged in users.
                    #Check This Users Friends.
                    
                    UserFriends = tarsusaCore.get_UserFriends(ViewUser.key().id())
                    
                    #set cache item
                    memcache.set_item("mainpage_friends", UserFriends, ViewUser.key().id())
                    
                #----------------------------------------               
                if ViewedUserIsOneofCurrentUsersFriends == True:
                    #Check Whether there is usermainpage_publicitems
                    cachedUserMainPagePublicItems = memcache.get_item("mainpage_publicitems", ViewUser.key().id())
                    if cachedUserMainPagePublicItems is not None:
                        UserNonPrivateItemsList = cachedUserMainPagePublicItems
                    else:
                        UserNonPrivateItemsList = tarsusaCore.get_UserNonPrivateItems(ViewUser.key().id(), 'publicOnlyforFriends')
                        #about the property, it pass this one but actually it's going to digg publicwithPublicforFriends.
                        
                        #set cache item
                        memcache.set_item("mainpage_publicitems", UserNonPrivateItemsList, ViewUser.key().id())

                else:
                    #CurrentUser is not one of ViewUser's friends.

                    #Check Whether there is usermainPage_publicitems_anony
                    cachedUserMainPagePublicItemsAnony = memcache.get_item("mainpage_publicitems_anony", ViewUser.key().id())
                    if cachedUserMainPagePublicItemsAnony is not None:
                        UserNonPrivateItemsList = cachedUserMainPagePublicItemsAnony
                    else:
                        UserNonPrivateItemsList = tarsusaCore.get_UserNonPrivateItems(ViewUser.key().id(), 'public')

                        #set cache item
                        memcache.set_item("mainpage_publicitems_anony", UserNonPrivateItemsList, ViewUser.key().id())

                template_values = {
                    'PrefixCSSdir': "../",
                    
                    'UserLoggedIn': 'Logged In',

                    'UserID': CurrentUser.key().id(), #This indicates the UserSettingPage Link on the topright of the Page, so it should be CurrentUser

                    'ViewedUserNickName': UserNickName,
                    'UserNickName': CurrentUser.dispname,
                    'ViewedUser': ViewUser,

                    'ViewedUserFriends': UserFriends,   

                    'UserAvatarImage': outputStringUserAvatar,
                    
                    'UserJoinInDate': datetime.datetime.date(ViewUser.datejoinin),
                    'UserWebsite': ViewUser.website,
                    'UserMainPageUserTitle': outputStringUserMainPageTitle,
                
                    'ViewedUserIsOneofCurrentUsersFriends': ViewedUserIsOneofCurrentUsersFriends,
                    'UserNonPrivateItemsList': UserNonPrivateItemsList,

                    'outputFeed': True,
                    'outputFeedTitle': ViewUser.dispname,
                    'outputFeedURL': "/user/" + str(ViewUser.key().id()) + "/feed",
                }
            

            path = os.path.join(os.path.dirname(__file__), 'pages/usermainpage.html')
            
            self.response.out.write(template.render(path, template_values))

        else:
            #self.write('not found this user and any items')
            
            # Prompt 'Can not found this user, URL style have been changed since Dec.X 2008, Some of the old external links are invalid now.
            # But We offer you another options, You may check whether these Users, may be one of them is whom you are looking for.
            # Better UE idea!

            outputStringUserMainPageTitle = 'not found this user and any items'
            outputStringRoutineLog = 'None'
            self.error(404)
            self.redirect('/')  
Ejemplo n.º 14
0
    def get(self):

        #RSS Feed Code, leart from Plog, using PyRSS2Gen Module.

        userid = urllib.unquote(
            cgi.escape(self.request.path[6:-5])
        )  ## Get the username in the URL string such as /user/1234/feed

        ## Get this user.
        ViewUser = tarsusaUser.get_by_id(int(userid))

        UserNickName = '访客'
        outputStringUserAvatar = ''

        if ViewUser != None:

            IsCachedUserFeed = memcache.get_item('UserPublicFeed',
                                                 ViewUser.key().id())

            if IsCachedUserFeed:
                userfeed_publicitems = IsCachedUserFeed
            else:

                userfeed_publicitems = []

                #should look at the routinelog at first.
                #new feed output supports public daily routine.
                tarsusaItemCollection_RecentDoneDailyRoutines = db.GqlQuery(
                    "SELECT * FROM tarsusaRoutineLogItem ORDER by donedate DESC LIMIT 10"
                )
                for each_DailyRoutineLogItem in tarsusaItemCollection_RecentDoneDailyRoutines:
                    RoutineItem = tarsusaItem.get_by_id(
                        each_DailyRoutineLogItem.routineid)
                    if RoutineItem.user == ViewUser.user and RoutineItem.public == 'public':
                        str_title = ViewUser.dispname + " 今天完成了 ".decode(
                            'utf-8') + tarsusaItem.get_by_id(
                                each_DailyRoutineLogItem.routineid).name
                        item_url = '%s/item/%d' % (self.request.host_url,
                                                   RoutineItem.key().id())

                        str_title = ViewUser.dispname + " 今天完成了 ".decode(
                            'utf-8') + RoutineItem.name
                        try:
                            # some very old items may not have usermodel property
                            str_author = RoutineItem.usermodel.dispname
                        except:
                            str_author = RoutineItem.user.nickname()

                        userfeed_publicitems.append({
                            'title':
                            str_title,
                            'author':
                            str_author,
                            'link':
                            item_url,
                            'description':
                            '每日任务'.decode(
                                'utf-8'
                            ),  #Later will be comment for each dailydone. 
                            'pubDate':
                            each_DailyRoutineLogItem.donedate,
                            'guid':
                            PyRSS2Gen.Guid(
                                str_title +
                                str(each_DailyRoutineLogItem.donedate))
                            #categories
                        })

                #There is a force 15 limits for RSS feed.
                #Plog is setting this as an option in setting.
                tarsusaItemCollection_UserRecentPublicItems = db.GqlQuery(
                    "SELECT * FROM tarsusaItem WHERE user = :1 and public = 'public' ORDER BY date DESC LIMIT 15",
                    ViewUser.user)
                #the code block below is a little bit duplicated, will find a way to make it simple in future. TODO
                for each_Item in tarsusaItemCollection_UserRecentPublicItems:

                    try:
                        # some very old items may not have usermodel property
                        str_author = each_Item.usermodel.dispname
                    except:
                        str_author = each_Item.user.nickname()

                    item_url = '%s/item/%d' % (self.request.host_url,
                                               each_Item.key().id())

                    if each_Item.done == True:
                        str_title = ViewUser.dispname + " 完成了 ".decode(
                            'utf-8') + each_Item.name
                    else:
                        str_title = ViewUser.dispname + " 要做 ".decode(
                            'utf-8') + each_Item.name

                    userfeed_publicitems.append({
                        'title':
                        str_title,
                        'author':
                        str_author,
                        'link':
                        item_url,
                        'description':
                        each_Item.comment,
                        'pubDate':
                        each_Item.date,
                        'guid':
                        PyRSS2Gen.Guid(item_url)
                        #categories
                    })

                #sort the results:
                #Sort Algorithms from
                #http://www.lixiaodou.cn/?p=12
                length = len(userfeed_publicitems)
                for i in range(0, length):
                    for j in range(length - 1, i, -1):
                        #Convert string to datetime.date
                        #http://mail.python.org/pipermail/tutor/2006-March/045729.html
                        time_format = "%Y-%m-%d %H:%M:%S"
                        #if datetime.datetime.fromtimestamp(time.mktime(time.strptime(userfeed_publicitems[j]['pubDate'][:-7], time_format))) > datetime.datetime.fromtimestamp(time.mktime(time.strptime(userfeed_publicitems[j-1]['pubDate'][:-7], time_format))):
                        if userfeed_publicitems[j][
                                'pubDate'] > userfeed_publicitems[
                                    j - 1]['pubDate']:
                            temp = userfeed_publicitems[j]
                            userfeed_publicitems[j] = userfeed_publicitems[j -
                                                                           1]
                            userfeed_publicitems[j - 1] = temp

                memcache.set_item("UserPublicFeed", userfeed_publicitems,
                                  ViewUser.key().id(), 1800)
                #cache it for at least half an hour.

            publicItems = []
            for each in userfeed_publicitems:
                publicItems.append(
                    PyRSS2Gen.RSSItem(title=each['title'],
                                      author=each['author'],
                                      link=each['link'],
                                      description=each['description'],
                                      pubDate=each['pubDate'],
                                      guid=each['guid']))

            rss = PyRSS2Gen.RSS2(
                title="CheckNerds - " + ViewUser.dispname,
                link=self.request.host_url + '/user/' +
                str(ViewUser.key().id()),
                description=ViewUser.dispname +
                '最新的公开事项,在线个人事项管理——欢迎访问http://www.checknerds.com'.decode(
                    'utf-8'),
                lastBuildDate=datetime.datetime.utcnow(),
                items=publicItems)

            self.response.headers[
                'Content-Type'] = 'application/rss+xml; charset=utf-8'
            rss_xml = rss.to_xml(encoding='utf-8')
            self.write(rss_xml)
Ejemplo n.º 15
0
    def get(self):

        username = urllib.unquote(
            cgi.escape(self.request.path[6:])
        )  ## Get the username in the URL string such as /user/1234
        ViewUser = None

        try:
            ## After URL style changed, Now won't allow username in URL, only accept id in URL.

            ## Get this user.
            q = db.GqlQuery(
                "SELECT * FROM tarsusaUser WHERE userid = :1 LIMIT 1",
                int(username))
            ViewUser = q.get()

            if ViewUser == None:
                q = tarsusaUser.get_by_id(int(username))
                ViewUser = q
        except:
            self.redirect('/')

        UserNickName = '访客'
        outputStringUserAvatar = ''

        UserNonPrivateItemsList = ''
        UserFriends = []

        if ViewUser != None:

            ## Preparation
            ## Will be useed
            if ViewUser.avatar:
                outputStringUserAvatar = "<img src='/image?avatar=" + str(
                    ViewUser.key().id()) + "' width=64 height=64>"
            else:
                outputStringUserAvatar = "<img src='/img/default_avatar.jpg' width=64 height=64>"

            outputStringUserMainPageTitle = ViewUser.dispname + "公开的项目".decode(
                "utf-8")

            #-------------------------------------
            if not self.chk_login():

                #Not a login user, show only the public items.
                UserNickName = "访客"
                logictag_OneoftheFriendsViewThisPage = False
                CurrentUserIsOneofViewUsersFriends = False
                statusUserFriends = 'NotLogin'
                #Above tag will be recognized by template
                ViewedUserIsOneofCurrentUsersFriends = False

                #Check Whether there is usermainPage_publicitems_anony
                cachedUserMainPagePublicItemsAnony = memcache.get_item(
                    "mainpage_publicitems_anony",
                    ViewUser.key().id())
                if cachedUserMainPagePublicItemsAnony is not None:
                    UserNonPrivateItemsList = cachedUserMainPagePublicItemsAnony
                else:
                    UserNonPrivateItemsList = tarsusaCore.get_UserNonPrivateItems(
                        ViewUser.key().id(), 'public')

                template_values = {
                    'PrefixCSSdir': "../",
                    'ViewedUserNickName': ViewUser.dispname,
                    'UserAvatarImage': outputStringUserAvatar,
                    'statusViewedUserFriends': statusUserFriends,
                    'UserJoinInDate':
                    datetime.datetime.date(ViewUser.datejoinin),
                    'UserWebsite': ViewUser.website,
                    'UserMainPageUserTitle': outputStringUserMainPageTitle,
                    'UserNonPrivateItemsList': UserNonPrivateItemsList,
                    'outputFeed': True,
                    'outputFeedTitle': ViewUser.dispname,
                    'outputFeedURL':
                    "/user/" + str(ViewUser.key().id()) + "/feed",
                }

            else:
                #User Login.

                #Check Whether CurrerentUser is one of ViewUser's friends
                UserNickName = ViewUser.dispname
                CurrentUser = self.get_user_db()

                CurrentUserIsOneofViewUsersFriends = False

                for each_Friend_key in ViewUser.friends:
                    if each_Friend_key == CurrentUser.key():
                        CurrentUserIsOneofViewUsersFriends = True
                        logictag_OneoftheFriendsViewThisPage = True

                ## Check whether the ViewedUser is a friend of CurrentUser.
                ## For AddUserAsFriend button.
                ViewedUserIsOneofCurrentUsersFriends = False

                for each_Friend_key in CurrentUser.friends:
                    if each_Friend_key == ViewUser.key():
                        ViewedUserIsOneofCurrentUsersFriends = True

                # Get user friend list
                cachedUserMainPageFriends = memcache.get_item(
                    "mainpage_friends",
                    ViewUser.key().id())
                if cachedUserMainPageFriends is not None:
                    UserFriends = cachedUserMainPageFriends
                else:
                    # This is shown to all logged in users.
                    #Check This Users Friends.

                    UserFriends = tarsusaCore.get_UserFriends(
                        ViewUser.key().id())

                    #set cache item
                    memcache.set_item("mainpage_friends", UserFriends,
                                      ViewUser.key().id())

                #----------------------------------------
                if ViewedUserIsOneofCurrentUsersFriends == True:
                    #Check Whether there is usermainpage_publicitems
                    cachedUserMainPagePublicItems = memcache.get_item(
                        "mainpage_publicitems",
                        ViewUser.key().id())
                    if cachedUserMainPagePublicItems is not None:
                        UserNonPrivateItemsList = cachedUserMainPagePublicItems
                    else:
                        UserNonPrivateItemsList = tarsusaCore.get_UserNonPrivateItems(
                            ViewUser.key().id(), 'publicOnlyforFriends')
                        #about the property, it pass this one but actually it's going to digg publicwithPublicforFriends.

                        #set cache item
                        memcache.set_item("mainpage_publicitems",
                                          UserNonPrivateItemsList,
                                          ViewUser.key().id())

                else:
                    #CurrentUser is not one of ViewUser's friends.

                    #Check Whether there is usermainPage_publicitems_anony
                    cachedUserMainPagePublicItemsAnony = memcache.get_item(
                        "mainpage_publicitems_anony",
                        ViewUser.key().id())
                    if cachedUserMainPagePublicItemsAnony is not None:
                        UserNonPrivateItemsList = cachedUserMainPagePublicItemsAnony
                    else:
                        UserNonPrivateItemsList = tarsusaCore.get_UserNonPrivateItems(
                            ViewUser.key().id(), 'public')

                        #set cache item
                        memcache.set_item("mainpage_publicitems_anony",
                                          UserNonPrivateItemsList,
                                          ViewUser.key().id())

                template_values = {
                    'PrefixCSSdir': "../",
                    'UserLoggedIn': 'Logged In',
                    'UserID': CurrentUser.key().id(
                    ),  #This indicates the UserSettingPage Link on the topright of the Page, so it should be CurrentUser
                    'ViewedUserNickName': UserNickName,
                    'UserNickName': CurrentUser.dispname,
                    'ViewedUser': ViewUser,
                    'ViewedUserFriends': UserFriends,
                    'UserAvatarImage': outputStringUserAvatar,
                    'UserJoinInDate':
                    datetime.datetime.date(ViewUser.datejoinin),
                    'UserWebsite': ViewUser.website,
                    'UserMainPageUserTitle': outputStringUserMainPageTitle,
                    'ViewedUserIsOneofCurrentUsersFriends':
                    ViewedUserIsOneofCurrentUsersFriends,
                    'UserNonPrivateItemsList': UserNonPrivateItemsList,
                    'outputFeed': True,
                    'outputFeedTitle': ViewUser.dispname,
                    'outputFeedURL':
                    "/user/" + str(ViewUser.key().id()) + "/feed",
                }

            path = os.path.join(os.path.dirname(__file__),
                                'pages/usermainpage.html')

            self.response.out.write(template.render(path, template_values))

        else:
            #self.write('not found this user and any items')

            # Prompt 'Can not found this user, URL style have been changed since Dec.X 2008, Some of the old external links are invalid now.
            # But We offer you another options, You may check whether these Users, may be one of them is whom you are looking for.
            # Better UE idea!

            outputStringUserMainPageTitle = 'not found this user and any items'
            outputStringRoutineLog = 'None'
            self.error(404)
            self.redirect('/')
Ejemplo n.º 16
0
    def get(self):
    
        if users.get_current_user() != None:
            CurrentUser = self.get_user_db()
            
            if CurrentUser == None:
                # Create a User
                CurrentUser = tarsusaUser(user=users.get_current_user(), urlname=cgi.escape(users.get_current_user().nickname()))
                CurrentUser.put()

                ## Added userid property.
                CurrentUser.userid = CurrentUser.key().id()
                CurrentUser.dispname = users.get_current_user().nickname()
                CurrentUser.put()
                
                logging.info("New User, id:" + str(CurrentUser.key().id()) + " name:" + CurrentUser.dispname)

                #ShardingCounter
                import shardingcounter
                shardingcounter.increment("tarsusaUser")

            
            else:
                ## DB Model Patch
                ## These code for registered user whose information are not fitted into the new model setting.
                
                #Run DB Model Patch when User Logged in.
                #DBPatcher.chk_dbmodel_update(CurrentUser)
                #Run this at every ViewItem event

                ## Added userid here.
                if CurrentUser.userid == None:
                    CurrentUser.userid = CurrentUser.key().id()
                    CurrentUser.put()
                    

            
            ## Check usedtags as the evaluation for Tags Model
            ## TEMP CODE!
            UserTags = '<a href=/tag/>未分类项目</a>&nbsp;'.decode('utf-8')

            if CurrentUser.usedtags:
                CheckUsedTags = []
                for each_cate in CurrentUser.usedtags:
                    ## After adding code with avoiding add duplicated tag model, it runs error on live since there are some items are depending on the duplicated ones.
                    
                    try:
                            
                        ## Caution! Massive CPU consumption.
                        ## Due to former BUG, there might be duplicated tags in usertags.
                        ## TO Solve this.

                        DuplicatedTags = False
                        for each_cate_vaild in CheckUsedTags:
                            if each_cate.name == each_cate_vaild:
                                DuplicatedTags = True

                        CheckUsedTags.append(each_cate.name)

                        if DuplicatedTags != True:
                            try:
                                ## Since I have deleted some tags in CheckNerds manually, 
                                ## so there will be raise such kind of errors, in which the tag will not be found.
                                each_tag =  db.get(each_cate)
                                UserTags += '<a href="/tag/' + cgi.escape(each_tag.name) +  '">' + cgi.escape(each_tag.name) + '</a>&nbsp;'
                            except:
                                ## Tag model can not be found.
                                pass

                    except:
                        pass
                        UserTags += 'Error, On MainPage Tags Section.'


            template_values = {
                'UserLoggedIn': 'Logged In',
                
                'UserNickName': cgi.escape(CurrentUser.dispname),
                'UserID': CurrentUser.key().id(),
                
                'htmltag_today': datetime.datetime.date(datetime.datetime.now()), 

                'UserTags': UserTags,


            }

            #Manupilating Templates 
            path = os.path.join(os.path.dirname(__file__), 'pages/index.html')
            self.response.out.write(template.render(path, template_values))
            
        else:
            #WelcomePage for Non-registered Users.
            IsCachedWelcomePage = memcache.get_item('strCachedWelcomePage', 'global')
            
            if IsCachedWelcomePage:
                strCachedWelcomePage = IsCachedWelcomePage
            else:
                
                TotalUserCount = tarsusaCore.get_count_tarsusaUser()
                TotaltarsusaItem = tarsusaCore.get_count_tarsusaItem()

                ## Homepage for Non-Registered Users.

                template_values = {
                    'UserNickName': "访客",
                    'AnonymousVisitor': "Yes",
                    'htmltag_TotalUser': TotalUserCount,
                    'htmltag_TotaltarsusaItem': TotaltarsusaItem,
                }

                #Manupilating Templates 
                path = os.path.join(os.path.dirname(__file__), 'pages/welcome.html')
                strCachedWelcomePage = template.render(path, template_values)
                memcache.set_item("strCachedWelcomePage", strCachedWelcomePage, 'global')

            self.response.out.write(strCachedWelcomePage)
Ejemplo n.º 17
0
    def post(self):
        
        if self.chk_login():
            CurrentUser = self.get_user_db()
        else:
            self.redirect('/')

        cachedUserDailyroutineYesterday = memcache.get_item("dailyroutine_yesterday", CurrentUser.key().id())
        if cachedUserDailyroutineYesterday is not None:
            strcachedUserDailyroutineYesterday = cachedUserDailyroutineYesterday
        else:   
            # Show His Daily Routine.
            tarsusaItemCollection_DailyRoutine = db.GqlQuery("SELECT * FROM tarsusaItem WHERE user = :1 and routine = 'daily' ORDER BY date DESC", users.get_current_user())
            tarsusaItemCollection_DoneDailyRoutine = tarsusaRoutineLogItem 

            # GAE datastore has a gqlquery.count limitation. So right here solve this manully.
            tarsusaItemCollection_DailyRoutine_count = 0
            for each_tarsusaItemCollection_DailyRoutine in tarsusaItemCollection_DailyRoutine:
                tarsusaItemCollection_DailyRoutine_count += 1

            Yesterday_DoneRoutine = 0

            for each_tarsusaItemCollection_DailyRoutine in tarsusaItemCollection_DailyRoutine:
                
                #This query should effectively read out all dailyroutine done by today.
                #for the result will be traversed below, therefore it should be as short as possible.
                #MARK FOR FUTURE IMPROVMENT
                
                # GAE datastore has a gqlquery.count limitation. So right here solve this manully.
                #tarsusaItemCollection_DailyRoutine_count
                # Refer to code above.
                
                # LIMIT and OFFSET don't currently support bound parameters.
                # http://code.google.com/p/googleappengine/issues/detail?id=179
                # if this is realized, the code below next line will be used.

                #TODO: should add a time limitation to easier this query.
                tarsusaItemCollection_DoneDailyRoutine = db.GqlQuery("SELECT * FROM tarsusaRoutineLogItem WHERE user = :1 and routine = 'daily' and routineid = :2 ORDER BY donedate DESC ", users.get_current_user(), each_tarsusaItemCollection_DailyRoutine.key().id())
                
                ## traversed RoutineDaily
                
                ## Check whether this single item is done.
                DoneThisItemYesterday = False
                
                for tarsusaItem_DoneDailyRoutine in tarsusaItemCollection_DoneDailyRoutine:
                    if datetime.datetime.date(tarsusaItem_DoneDailyRoutine.donedate) == datetime.datetime.date(datetime.datetime.now() - datetime.timedelta(days=1)):
                        
                        #Check if the user had done all his routine today.
                        Yesterday_DoneRoutine += 1
                        DoneThisItemYesterday = True

                        # This routine have been done today.
                        
                        # Due to solve this part, I have to change tarsusaItemModel to db.Expando
                        # I hope there is not so much harm for performance.
                        each_tarsusaItemCollection_DailyRoutine.doneyesterday = 1
                        each_tarsusaItemCollection_DailyRoutine.put()

                    else:
                        ## The Date from RoutineLogItem isn't the same of Today's date
                        ## That means this tarsusaItem(as routine).donetoday should be removed.
                            
                        pass
                
                if DoneThisItemYesterday == False:
                        ## Problem solved by Added this tag. DoneThisItemYesterday
                        try:
                            del each_tarsusaItemCollection_DailyRoutine.doneyesterday
                            each_tarsusaItemCollection_DailyRoutine.put()
                        except:
                            pass

            ## Output the message for DailyRoutine
            template_tag_donealldailyroutine = ''
            
            if Yesterday_DoneRoutine == int(tarsusaItemCollection_DailyRoutine_count) and Yesterday_DoneRoutine != 0:
                template_tag_donealldailyroutine = '<img src="img/favb16.png">恭喜,你完成了昨天要做的所有事情!'
            elif Yesterday_DoneRoutine == int(tarsusaItemCollection_DailyRoutine_count) - 1:
                template_tag_donealldailyroutine = '只差一项,加油!'
            elif int(tarsusaItemCollection_DailyRoutine_count) == 0:
                template_tag_donealldailyroutine = '还没有添加每日计划?赶快添加吧!<br />只要在添加项目时,将“性质”设置为“每天要做的”就可以了!'

            template_values = {
            'UserLoggedIn': 'Logged In',
            'UserNickName': cgi.escape(CurrentUser.dispname),
            'UserID': CurrentUser.key().id(),
            'tarsusaItemCollection_DailyRoutine': tarsusaItemCollection_DailyRoutine,
            'htmltag_DoneAllDailyRoutine': template_tag_donealldailyroutine,
            'htmltag_today': datetime.datetime.date(datetime.datetime.now() - datetime.timedelta(days=1)), 
            }

            #Manupilating Templates 
            path = os.path.join(os.path.dirname(__file__), 'pages/ajaxpage_dailyroutine_yesterday.html')
            strcachedUserDailyroutineYesterday = template.render(path, template_values)
            memcache.set_item("dailyroutineyesterday", strcachedUserDailyroutineYesterday, CurrentUser.key().id())
        
        self.response.out.write(strcachedUserDailyroutineYesterday)
Ejemplo n.º 18
0
def get_dailyroutine(userid):

    ThisUser = tarsusaUser.get_by_id(int(userid))
    # Show His Daily Routine.
 
 
    cached_user_dailyroutine = memcache.get_item("dailyroutine_items", int(userid))
    if cached_user_dailyroutine is not None:
        return cached_user_dailyroutine
    else:

        # the return result
        Item_List = []      
        
        tarsusaItemCollection_DailyRoutine = db.GqlQuery("SELECT * FROM tarsusaItem WHERE user = :1 and routine = 'daily' ORDER BY date DESC", ThisUser.user)
        tarsusaItemCollection_DoneDailyRoutine = tarsusaRoutineLogItem 

        # GAE datastore has a gqlquery.count limitation. So right here solve this manully.
        tarsusaItemCollection_DailyRoutine_count = 0
        for each_tarsusaItemCollection_DailyRoutine in tarsusaItemCollection_DailyRoutine:
            tarsusaItemCollection_DailyRoutine_count += 1

        Today_DoneRoutine = 0

        for each_tarsusaItemCollection_DailyRoutine in tarsusaItemCollection_DailyRoutine:
            
            #This query should effectively read out all dailyroutine done by today.
            #for the result will be traversed below, therefore it should be as short as possible.
            #MARK FOR FUTURE IMPROVMENT
            
            # GAE datastore has a gqlquery.count limitation. So right here solve this manully.
            #tarsusaItemCollection_DailyRoutine_count
            # Refer to code above.
            
            # LIMIT and OFFSET don't currently support bound parameters.
            # http://code.google.com/p/googleappengine/issues/detail?id=179
            # if this is realized, the code below next line will be used.

            #OCt 19
            #shoudl be changed in to multiple gql, with each gets the latest doneroutine item for only one dailyroutine item.
            tarsusaItemCollection_DoneDailyRoutine = db.GqlQuery("SELECT * FROM tarsusaRoutineLogItem WHERE user = :1 and routine = 'daily' and routineid = :2 ORDER BY donedate DESC LIMIT 1", ThisUser.user, each_tarsusaItemCollection_DailyRoutine.key().id())
            
            ## traversed RoutineDaily
            
            ## Check whether this single item is done.
            DoneThisItemToday = False
                    
            for tarsusaItem_DoneDailyRoutine in tarsusaItemCollection_DoneDailyRoutine:
                if datetime.datetime.date(tarsusaItem_DoneDailyRoutine.donedate) == datetime.datetime.date(datetime.datetime.now()):
                    #Check if the user had done all his routine today.
                    Today_DoneRoutine += 1
                    DoneThisItemToday = True

                    # This routine have been done today.
                    
                    # Due to solve this part, I have to change tarsusaItemModel to db.Expando
                    # I hope there is not so much harm for performance.
                    each_tarsusaItemCollection_DailyRoutine.donetoday = 1
                    each_tarsusaItemCollection_DailyRoutine.put()

                else:
                    ## The Date from RoutineLogItem isn't the same of Today's date
                    pass
            
            if DoneThisItemToday == False:
                ## Problem solved by Added this tag. DoneThisItemToday
                try:
                    del each_tarsusaItemCollection_DailyRoutine.donetoday
                    each_tarsusaItemCollection_DailyRoutine.put()
                except:
                    pass

            #'tarsusaItemCollection_DailyRoutine': tarsusaItemCollection_DailyRoutine,
            this_item = {'id' : str(each_tarsusaItemCollection_DailyRoutine.key().id()), 'name' : each_tarsusaItemCollection_DailyRoutine.name, 'date' : each_tarsusaItemCollection_DailyRoutine.date, 'donedate': each_tarsusaItemCollection_DailyRoutine.donedate, 'expectdate': each_tarsusaItemCollection_DailyRoutine.expectdate, 'comment' : each_tarsusaItemCollection_DailyRoutine.comment, 'routine' : each_tarsusaItemCollection_DailyRoutine.routine, 'category' : each_tarsusaItemCollection_DailyRoutine.done, 'done':DoneThisItemToday}
            #originally, done should be done for item, but here done refers to daily done for a daily routine item.
            Item_List.append(this_item)


                
        ## Output the message for DailyRoutine
        '''template_tag_donealldailyroutine = ''               
        if Today_DoneRoutine == int(tarsusaItemCollection_DailyRoutine_count) and Today_DoneRoutine != 0:
            template_tag_donealldailyroutine = '<img src="img/favb16.png">恭喜,你完成了今天要做的所有事情!'
        elif int(tarsusaItemCollection_DailyRoutine_count) == 0:
            template_tag_donealldailyroutine = '还没有添加每日计划?赶快添加吧!<br />只要在添加项目时,将“性质”设置为“每天要做的”就可以了!'''
        memcache.set_item("dailyroutine_items", Item_List, int(userid))

        return Item_List