Пример #1
0
    def get(self):
        
        latest_hash = self.request.get("latest",None)
        if not latest_hash:
            link = models.Link.gql("ORDER BY date_added ASC").get()
            latest_hash = link.key().name()
        else:
            link = models.Link.get_by_key_name(latest_hash)
        
        batch_size = 400
        memcache_key = "%s-%d" % (latest_hash,batch_size)

        as_json = memcache.get(memcache_key)
        if as_json is None:
            q = GqlQuery("SELECT __key__ FROM Link WHERE date_added > :1 ORDER BY date_added ASC",link.date_added)

            links = q.fetch(batch_size)
            as_json = simplejson.dumps(map(lambda x: x.name(),links))

            keep_time = 60 * 60
            if len(links) == batch_size:
                # this batch is cooked.
                keep_time = 0

            memcache.add(memcache_key,as_json,keep_time)

        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(as_json)
Пример #2
0
	def post(self, id):
		if bool(self.request.get('message')) == False:
			person = self.request.get('who')
			query = GqlQuery("SELECT *FROM Post ORDER BY date ASC")
			items = query.fetch(9999)
			posts = []
			for item in items:
				if item.discussion_id == id:
					posts.append(item)
			error_state = True
			values = {'posts' : posts, 'person': person, 'error_state': error_state}
			self.response.out.write(template.render("discussion.html", values))
		else:
			new_post = Post(message = self.request.get('message'), who = self.request.get('who'), discussion_id = id)
			new_post.put()
			person = self.request.get('who')
			query = GqlQuery("SELECT *FROM Post ORDER BY date ASC")
			items = query.fetch(9999)
			posts = []
			for item in items:
				if item.discussion_id == id:
					posts.append(item)
			error_state = False
			values = {'posts' : posts, 'person': person, 'error_state': error_state}
			self.response.out.write(template.render("discussion.html", values))
Пример #3
0
    def get(self):
        user = users.get_current_user()
        r = FlowerbedAdd()
        if self.request.get('lat') and self.request.get('lon'):
            #TODO: check if flowerbed is far enough from others
            #TODO: check if flowerbed is close enough to user
            lat = int(self.request.get('lat')) / 1000000.0
            lon = int(self.request.get('lon')) / 1000000.0
            gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())
            gamer_hash = hashlib.md5(user.user_id() + SALT).hexdigest()
            r.timestamp = int(time.time())
            #get backpack
            bp_beds = GqlQuery('SELECT * FROM Backpack WHERE ANCESTOR IS :1 AND name=:2', gamer_key, 'flowerbed').get()
            if bp_beds.amount:
                #lower backpack
                bp_beds.amount -= 1
                bp_beds.put()

                #add flowerbed
                point = GeoPt(lat, lon)
                cell = geocell.compute(point, RULES['GEO_RESOLUTION'])
                flowerbed = kloombaDb.Flowerbed(parent=Key.from_path(kloombaDb.Flowerbed.kind(), cell))
                flowerbed.point = point
                flowerbed.tile = cell
                flowerbed.owner = user.user_id()
                flowerbed.owner_public_id = gamer_hash
                flowerbed.put()

                #save to memcache
                memcache.set(str(flowerbed.key()), flowerbed)

                #add possession
                possession = kloombaDb.Possession(parent=gamer_key)
                possession.flowerbed = flowerbed
                possession.put()

                backpack = GqlQuery('SELECT * FROM Backpack WHERE ANCESTOR IS :1', gamer_key).run()

                #set timestamps
                r.flowerbed.timestamp = int(time.time())
                r.backpack.timestamp = int(time.time())

                #set flowerbed
                r.flowerbed.id = str(flowerbed.key())
                r.flowerbed.latitude = int(self.request.get('lat'))
                r.flowerbed.longitude = int(self.request.get('lon'))
                r.flowerbed.owner = gamer_hash
                r.flowerbed.flowers = 0

                #set backpack
                for i in backpack:
                    bp = r.backpack.item.add()
                    bp.name = i.name
                    bp.amount = i.amount


        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #4
0
 def get(self):
     str_id = self.request.get('id')
     message = self.request.get('message')
     
     if not str_id or not message:
         self.response.status_int = 400
         self.response.body = "Invalid or missing id and or message."
         return
         
     devices = GqlQuery('SELECT * FROM Device WHERE __key__ = :1',
                        Key.from_path('Device', str_id))
     
     if devices.count() < 1:
         self.response.status_int = 404
         self.response.body = "Target device not registered."
         return
     
     payload = {'registration_ids': [devices.get().token], 'data': {'message': message}}
     headers = {'Content-Type': 'application/json',
                'Authorization': 'key=' + API_KEY}
     result = urlfetch.fetch(url = ANDROID_GCM_URL,
                             payload = json.dumps(payload),
                             method = urlfetch.POST,
                             headers = headers)
     
     self.response.status_int = result.status_code
     self.response.body = result.content
Пример #5
0
    def get(self):
        r = BookmarkRemove()

        if not self.request.get('id'):
            return

        fb_key = self.request.get('id')
        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())

        #get bookmark
        bookmark = GqlQuery('SELECT * FROM Bookmark WHERE ANCESTOR IS :1 AND flowerbed=:2', gamer_key, Key(fb_key)).get()

        if not bookmark:
            return

        bookmark.delete()

        r.timestamp = int(time.time())
        r.id = fb_key

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #6
0
    def get(self):
        r = BookmarkRemove()

        if not self.request.get('id'):
            return

        fb_key = self.request.get('id')
        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())

        #get bookmark
        bookmark = GqlQuery(
            'SELECT * FROM Bookmark WHERE ANCESTOR IS :1 AND flowerbed=:2',
            gamer_key, Key(fb_key)).get()

        if not bookmark:
            return

        bookmark.delete()

        r.timestamp = int(time.time())
        r.id = fb_key

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #7
0
    def get(self, ruser):
        ruser = urllib.unquote(urllib.unquote(ruser))
        if self.request.GET:
            show = self.request.get('show')
            if show == '':
                show = 0
            else:
                show = Paging().Test_page(show)
        else:
            show = 0
        show = int(show)

        fotolist = GqlQuery("SELECT * FROM FotosDB2 WHERE user = '******' ORDER BY date DESC" % ruser)
        paging = Paging().page(fotolist, show, num = 12)
        fotolist = fotolist.fetch(12, show)
        
        if ruser == users.get_current_user().nickname():
            dell = True 
        else:
            dell = False
        
        template_values = {
            'upload_url':blobstore.create_upload_url('/uploadfoto'),
            'fotolist': fotolist,
            'paging':paging,
            'dell':dell,
            }
        self.generate('fotos.index.html', template_values, razdel = '', logo = 'logo', title = 'Фотоальбом %s' % ruser);
Пример #8
0
    def get(self, post_id):

        key = db.Key.from_path('Posts', int(post_id))
        post = db.get(key)

        keyTwo = db.Key.from_path('Users', int(post.owner))
        owner = db.get(keyTwo)

        comments = GqlQuery('select * from Comments where post_id = ' +
                            post_id)
        likes = GqlQuery('select * from PostLikes where post_id = ' + post_id)

        liked = 'no'

        for l in likes:
            if l.ownerName == self.user.username:
                liked = 'yes'

        if not post:
            self.error(404)
            return

        return self.render('blog-post.html',
                           post=post,
                           comments=comments,
                           likes=likes,
                           owner=owner,
                           liked=liked,
                           you=self.user)
Пример #9
0
def migrate_to_0_2(request):
    #added:
    #  page
    #  room.main_page
    #  content.page

    # 1. Add a main page to each room
    roomsQ = GqlQuery("SELECT * FROM Room")
    for room in roomsQ:
        mp = Page()
        mp.room = str(room.key())
        mp.title = "Home"
        mp.put()
        room.main_page = str(mp.key())
        room.put()
        # 2. set all content for that room to the page
        contentsQ = GqlQuery(
            "SELECT * FROM Content WHERE ANCESTOR is :room_key",
            room_key=room.key())
        for c in contentsQ:
            c.parent = room.main_page
            c.page = room.main_page
            c.room = None
            c.put()
    return HttpResponse('Migration to 0.2 Successful')
Пример #10
0
def _stats():
    if not (users.is_current_user_admin()
            or users.get_current_user().email().endswith('@fogcreek.com')
            or request.remote_addr in ['127.0.0.1', '71.190.247.30']):
        abort(404)

    user_count = GqlQuery('SELECT __key__ FROM UserSettings').count(None)
    site_count = GqlQuery(
        'SELECT __key__ FROM Site WHERE example=false').count(None)
    now = datetime.now()
    days = list(reversed([now - timedelta(days) for days in range(14)]))
    day_views = [
        get_period_and_count('css:all', PeriodType.DAY, day) for day in days
    ]
    day_users = [
        get_period_and_count('user:all', PeriodType.DAY, day) for day in days
    ]
    day_sites = [
        get_period_and_count('site:all', PeriodType.DAY, day) for day in days
    ]
    # overwrite today's cached numbers with the live count we just got from the database
    day_users[-1] = day_users[-1][0], user_count
    day_sites[-1] = day_sites[-1][0], site_count

    # get the top referrers
    period_type = PeriodType.DAY
    fetch_limit = 50
    query = LivecountCounter.all().order('-count')
    query.filter('period_type = ', period_type)
    query.filter('period = ', PeriodType.find_scope(period_type,
                                                    datetime.now()))
    top_counters = query.fetch(fetch_limit)
    top_referrers = []
    for counter in top_counters:
        name = counter.name
        if name.startswith('css:page') and not name.startswith(
                'css:page:www.webputty.net'):
            parts = name.split(':')
            page = None
            preview_size = 0
            published_size = 0
            try:
                page = Page.get(parts[3])
            except Exception:
                logging.warn("_stats counldn't find matching page: %s",
                             parts[3])
            if page:
                preview_size = len(page.compressed_css(True))
                published_size = len(page.compressed_css(False))
            top_referrers.append((parts[2], counter.count, parts[3],
                                  preview_size, published_size))

    return render_template('_stats.html',
                           user_count=user_count,
                           site_count=site_count,
                           day_views=day_views,
                           day_users=day_users,
                           day_sites=day_sites,
                           top_referrers=top_referrers)
Пример #11
0
 def get(self, email, id=''):
     if email != '':
         q = GqlQuery("SELECT * FROM User where email=:emailid",
                      emailid=email)
         for auser in q.run(limit=1):
             return auser
         return None
     return User.get_by_key_name(id)
Пример #12
0
 def get_or_create(email):
     nl = GqlQuery("SELECT * FROM DBNewsletter WHERE email = :1", email).get()
     if nl is None:
         nl = DBNewsletter()
         nl.email = email
         nl.save()
         Pagination.add(nl,nl.is_enable)
     return nl
Пример #13
0
	def get(self, id):
		query = GqlQuery("SELECT *FROM Post ORDER BY date ASC")
		items = query.fetch(9999)
		posts = []
		for item in items:
			if item.discussion_id == id:
				posts.append(item)
		self.response.out.write(template.render("chatscreen.html", {'posts':posts}))
Пример #14
0
def stats_cron():
    current_user_count = GqlQuery('SELECT __key__ FROM UserSettings').count(None)
    current_site_count = GqlQuery('SELECT __key__ FROM Site WHERE example=false').count(None)
    now = datetime.now()
    saved_user_count = counter.load_and_get_count('user:all', period_type=PeriodType.DAY, period=now) or 0
    saved_site_count = counter.load_and_get_count('site:all', period_type=PeriodType.DAY, period=now) or 0
    count_view('user:all', delta=(current_user_count - saved_user_count), batch_size=None, period=now)
    count_view('site:all', delta=(current_site_count - saved_site_count), batch_size=None, period=now)
    return render_template('_stats_cron.html', current_user_count=current_user_count, current_site_count=current_site_count, saved_user_count=saved_user_count, saved_site_count=saved_site_count)
Пример #15
0
    def get(self):
        r = PossessionLost()
        to_delete = []
        poss = []

        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())
        possessions = GqlQuery(
            'SELECT * FROM Possession WHERE ANCESTOR IS :1 AND lost = TRUE',
            gamer_key).run()
        r.timestamp = int(time.time())
        for i in possessions:
            if int(time.time()) - int(time.mktime(i.timestamp.timetuple())
                                      ) > RULES['LOST_FLOWERBED_TIMEOUT']:
                to_delete.append(i.flowerbed.key())
            else:
                poss.append(i)

        deleted = db.delete_async(to_delete)

        if poss:
            keys = [
                kloombaDb.Possession.flowerbed.get_value_for_datastore(i)
                for i in poss
            ]
            flowerbeds = []

            for i in keys:
                fb = memcache.get(str(i))
                if not fb:
                    fb = GqlQuery('SELECT * FROM Flowerbed WHERE __key__=:1',
                                  i).get()
                    if fb and not memcache.add(str(i), fb):
                        logging.error('Memcache set failed')
                if fb:
                    flowerbeds.append(fb)

            for (p, f) in zip(poss, flowerbeds):
                if p and f:
                    fb = r.possession.add()
                    fb.timestamp = int(time.mktime(p.timestamp.timetuple()))
                    fb.flowerbed.timestamp = int(
                        time.mktime(f.timestamp.timetuple()))
                    fb.flowerbed.id = str(f.key())
                    fb.flowerbed.latitude = int(f.point.lat * 1000000)
                    fb.flowerbed.longitude = int(f.point.lon * 1000000)
                    fb.flowerbed.owner = f.owner_public_id
                    fb.flowerbed.flowers = f.flowers

        deleted.get_result()

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #16
0
    def deleteUser(self):
        htmlHelper.SetContentTypeToXml(self)
        user = datamodule.GetUser(self.request.get('userName'),
                                  self.request.get('password'))
        if (not user):
            self.response.out.write(
                htmlHelper.XmlDeclaration +
                '<error errorId="4">User not found</error>')
            return

        files = GqlQuery('SELECT __key__ FROM Files WHERE user = :1', user)
        db.delete(files.fetch(1000, 0))
        user.delete()
        self.response.out.write(htmlHelper.XmlDeclaration +
                                '<OK>User Deleted</OK>')
Пример #17
0
 def get(self):
     if self.user:
         userID = str(self.user.key().id())
         posts = GqlQuery('select * from Posts where owner = ' + userID)
         return self.render('profile.html', you=self.user, posts=posts)
     else:
         return self.redirect('/login')
Пример #18
0
def admin_login():
    if request.method == 'POST':
        id = request.form['username']
        pw = request.form['password']
        print id, pw
        q = GqlQuery("SELECT * FROM User WHERE id = :1", id)
        check_user = q.get()

        print check_user.password

        if check_user != None:
            if check_password(check_user.password, pw):
                session['username'] = '******'
                return redirect(url_for('admin_juboam'))

    return render_template('admin_login.html')
Пример #19
0
    def addFile(self):
        htmlHelper.SetContentTypeToXml(self)
        currUser = datamodule.GetUser(self.request.get('userName'),
                                      self.request.get('password'))
        if (not currUser):
            self.response.out.write(
                htmlHelper.XmlDeclaration +
                '<error errorId="4">User not found</error>')
            return

        filename = self.request.get('fileName').strip()

        if len(filename) == 0:
            self.response.out.write(
                htmlHelper.XmlDeclaration +
                '<error errorId="5">File name required</error>')
            return

        existingFile = GqlQuery(
            'SELECT __key__ FROM Files WHERE user = :1 AND fileName = :2',
            currUser, filename).get()
        if existingFile:
            self.response.out.write(
                htmlHelper.XmlDeclaration +
                '<error errorId="6">File name not unique</error>')
            return

        file = datamodule.Files(user=currUser,
                                fileName=filename,
                                fileText=self.request.get('fileText'))
        file.put()
        self.response.out.write(htmlHelper.XmlDeclaration +
                                '<OK>File Added</OK>')
Пример #20
0
    def get(self):
        r = BookmarkList()
        keys = []

        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())
        bookmarks = GqlQuery('SELECT * FROM Bookmark WHERE ANCESTOR IS :1',
                             gamer_key).run()
        r.timestamp = int(time.time())
        for i in bookmarks:
            keys.append(i.flowerbed.key())

        flowerbeds = kloombaDb.Flowerbed.get(keys) if keys else []
        for i in flowerbeds:
            fb = r.flowerbed.add()
            fb.timestamp = int(time.mktime(i.timestamp.timetuple()))
            fb.id = str(i.key())
            fb.latitude = int(i.point.lat * 1000000)
            fb.longitude = int(i.point.lon * 1000000)
            fb.owner = i.owner_public_id
            fb.flowers = i.flowers

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #21
0
    def get(self):
        r = PossessionLost()
        to_delete = []
        poss = []

        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())
        possessions = GqlQuery('SELECT * FROM Possession WHERE ANCESTOR IS :1 AND lost = TRUE', gamer_key).run()
        r.timestamp = int(time.time())
        for i in possessions:
            if int(time.time()) - int(time.mktime(i.timestamp.timetuple())) > RULES['LOST_FLOWERBED_TIMEOUT']:
                to_delete.append(i.flowerbed.key())
            else:
                poss.append(i)

        deleted = db.delete_async(to_delete)

        if poss:
            keys = [kloombaDb.Possession.flowerbed.get_value_for_datastore(i) for i in poss]
            flowerbeds = []

            for i in keys:
                fb = memcache.get(str(i))
                if not fb:
                    fb = GqlQuery('SELECT * FROM Flowerbed WHERE __key__=:1', i).get()
                    if fb and not memcache.add(str(i), fb):
                        logging.error('Memcache set failed')
                if fb:
                    flowerbeds.append(fb)

            for (p, f) in zip(poss, flowerbeds):
                if p and f:
                    fb = r.possession.add()
                    fb.timestamp = int(time.mktime(p.timestamp.timetuple()))
                    fb.flowerbed.timestamp = int(time.mktime(f.timestamp.timetuple()))
                    fb.flowerbed.id = str(f.key())
                    fb.flowerbed.latitude = int(f.point.lat * 1000000)
                    fb.flowerbed.longitude = int(f.point.lon * 1000000)
                    fb.flowerbed.owner = f.owner_public_id
                    fb.flowerbed.flowers = f.flowers

        deleted.get_result()

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #22
0
    def get(self):
        image_url = self.request.get('image_url')
        width = int(self.request.get('width'))
        name = self.request.get('name')

        savedimages = GqlQuery(
            "SELECT * FROM Image WHERE url = :1 and width = :2", image_url,
            width)
        image = savedimages.get()
        if image:
            image_url = image.url
            tinyname = image.name
        else:
            import random
            import string
            image_re = re.compile(r'http://([\w\d\_\=\?\-\.\/\&\;\%]+)')
            if image_re.search(image_url):
                domain = image_re.search(image_url).group(0)
                ext = domain[-3:].lower()
                if ext == "jpg" or ext == "png" or ext == "gif":
                    mime = ext
                    if ext == "jpg":
                        mime = "jpeg"
                    parts = domain.split("/")
                    filename = parts[len(parts) - 1]
                    #get image
                    image_content = urlfetch.fetch(image_url).content
                    thumb = images.resize(image_content, width, width)
                    tinyname = ''.join(random.sample(string.letters * 2, 10))

                    if thumb:
                        image = Image()
                        image.url = image_url
                        image.width = width
                        image.name = tinyname
                        image.content = db.Blob(image_content)
                        image.thumb = db.Blob(thumb)
                        image.put()

        template_values = {
            'image_url': image_url,
            'width': width,
            'name': tinyname
        }
        path = os.path.join(os.path.dirname(__file__),
                            'templates/thumbnails.html')
        self.response.out.write(template.render(path, template_values))
Пример #23
0
 def fetch2(self, gql, *args, **kwargs):
     limit = kwargs.get('limit', 100)
     start_time = time.time()
     self.keys2 = GqlQuery(gql, *args).fetch(limit)
     self.seconds2 = time.time() - start_time
     self.names2 = [key.name() for key in self.keys2]
     self.gql2 = '%s LIMIT %d' % (replace_args(gql, *args), limit)
     self.result2 = ' '.join(self.names2)
Пример #24
0
    def get(self, task):
        task_method_name = 'get_' + task
        if task_method_name in dir(self) and task_method_name not in dir(
                super):
            method = getattr(self, task_method_name)
            return method()

        report_log_total = GqlQuery("SELECT __key__ FROM ReportLog").count()
        report_log_committed = GqlQuery(
            "SELECT __key__ FROM ReportLog WHERE commit = True").count()

        self.response.out.write(
            template.render(
                'admin.html', {
                    'report_log_total': report_log_total,
                    'report_log_committed': report_log_committed
                }))
Пример #25
0
 def get_by_num(cls, num, key_only=True):
     if not num:
         return None
     if key_only:
         sql = 'select __key__ from %s where num = :1' % cls.__name__
     else:
         sql = 'select * from %s where num = :1' % cls.__name__
     return GqlQuery(sql, num).get()
Пример #26
0
	def get(self):
		image_url = self.request.get('image_url')
		width = int(self.request.get('width'))
		name=self.request.get('name')
		
		
		savedimages = GqlQuery("SELECT * FROM Image WHERE url = :1 and width = :2", image_url, width)
		image = savedimages.get()
		if image:
			image_url=image.url
			tinyname=image.name
		else:
			import random
			import string
			image_re = re.compile(r'http://([\w\d\_\=\?\-\.\/\&\;\%]+)')
			if image_re.search(image_url):
				domain=image_re.search(image_url).group(0)
				ext = domain[-3:].lower()
				if ext == "jpg" or ext == "png" or ext == "gif":
					mime=ext
					if ext=="jpg":
						mime="jpeg"
					parts=domain.split("/")
					filename=parts[len(parts)-1]
					#get image 
					image_content = urlfetch.fetch(image_url).content
					thumb = images.resize(image_content, width, width)
					tinyname= ''.join(random.sample(string.letters*2, 10)) 

					if thumb:
						image=Image()
						image.url=image_url
						image.width=width
						image.name=tinyname
						image.content = db.Blob(image_content)
						image.thumb = db.Blob(thumb)
						image.put()
						
		template_values={
			'image_url': image_url,
			'width': width,
			'name': tinyname
		}
		path = os.path.join(os.path.dirname(__file__), 'templates/thumbnails.html')
		self.response.out.write(template.render(path, template_values))
Пример #27
0
 def has_write_access(self, user_key):
     try:
         if self.owner == user_key:
             return True
         if self.public_readwrite:
             return True
         if self.group_write:
             #group_write means you need to be abuddy
             room_k = str(self.key())
             roomyQ = GqlQuery(
                 "SELECT * FROM RoomUser WHERE room = :room_key AND user =:p_user_key ",
                 room_key=room_k,
                 p_user_key=user_key)
             if roomyQ.get():
                 return True
         return False
     except:
         return False
Пример #28
0
 def fetch1(self, gql, *args, **kwargs):
     self.messages = []
     limit = kwargs.get('limit', 100)
     start_time = time.time()
     self.keys1 = GqlQuery(gql, *args).fetch(limit)
     self.seconds1 = time.time() - start_time
     self.names1 = [key.name() for key in self.keys1]
     self.gql1 = '%s LIMIT %d' % (replace_args(gql, *args), limit)
     self.result1 = ' '.join(self.names1)
Пример #29
0
 def get(self, name):
     images = GqlQuery("SELECT * FROM Image WHERE name = :1", name)
     image = images.get()
     if image:
         mime = "jpeg"
         self.response.headers['Content-Type'] = "image/%s" % mime
         self.response.out.write(image.thumb)
         self.response.out.write(image.content)
     else:
         self.error(404)
         self.redirect("/static/nopic.png")
Пример #30
0
    def get(self):
        #Get the latest count
        Count.setAllFrontComments(FrontComment.all().count())
        Count.setAllSnakeComments(SnakeComment.all().count())
        Count.setAllRegisteredUsers(User.all().count())
        logged_out = self.request.get('logged_out')
        logged_in = self.request.get('logged_in')
        registered = self.request.get('registered')
        all_comments = self.request.get('allComments')

        if all_comments == 'True':
            comments = GqlQuery("SELECT * FROM FrontComment ORDER BY created DESC")
        else:
            comments = GqlQuery("SELECT * FROM FrontComment ORDER BY created DESC LIMIT 4")

        if self.format == 'html':
            self.render('front.html', frontComments=comments, logged_in=logged_in, logged_out=logged_out,
                        registered=registered)
        else:
            return self.render_json([p.as_dict() for p in comments])
Пример #31
0
 def get(self):
     str_id = self.request.get('id')
     token = self.request.get('token')
     
     if not str_id or not token:
         self.response.status_int = 400
         self.response.body = "Invalid or missing id and or token."
         return
         
     objects = GqlQuery('SELECT * FROM Device WHERE __key__ = :1',
                        Key.from_path('Device', str_id))
     
     if objects.count() < 1:
         obj = Device(key=Key.from_path('Device', str_id), token=token)
     else:
         obj = objects.get()
     
     obj.put()
     
     self.response.status_int = 200
     self.response.body = "OK"
Пример #32
0
 def exercise_progress(self, usuario):
     
     x_vid = array([0.0, 25.0, 50.0, 75.0, 100.0])
     y_vid = array([0.0, 40.0, 65.0, 85.0, 100.0])
     
     pol_exercise_progress = Polynomial.fit(x_vid, y_vid, 5)
     
     subject_exercises = GqlQuery("SELECT * FROM ViewerExercise")
     
     exercise_progress = 0
     
     for subject_exercise in subject_exercises:
         userExercise = GqlQuery("SELECT * FROM UserExercise WHERE exercise_model = :1 AND user = :2", subject_exercise.exercise, usuario.user).get()
         
         if(userExercise != None):
             if(userExercise._progress == 1.0):
                 exercise_progress += 100
             else:
                 exercise_progress += pol_exercise_progress(userExercise._progress*100)
                 
     return int(exercise_progress/subject_exercises.count())
Пример #33
0
 def get_room_list(self):
     q = GqlQuery("SELECT * FROM RoomUser "
                  "WHERE user = :1 ", str(self.key()))
     result = []
     try:
         for room_user in q:
             room_key = room_user.room
             room = Room().get(room_key)
             room_name = room.key().name()
             result.append(room_name)
     finally:
         return result
Пример #34
0
    def has_read_access(self, user):
        try:
            if self.public_read:
                return True
            if user == None:
                return False
            user_key = str(user.key())
            if self.owner == user_key:
                return True

            room_k = str(self.key())
            roomyQ = GqlQuery(
                "SELECT * FROM RoomUser WHERE room = :room_key AND user =:p_user_key ",
                room_key=room_k,
                p_user_key=user_key)
            if roomyQ.get():
                return True
            else:
                return False
        except:
            return False
Пример #35
0
def index(request):
    user = users.get_current_user()
    admin = users.is_current_user_admin()
#    query = db.GqlQuery("SELECT * FROM Course WHERE content_count > :1 OR creator = :2 ",
#                    10, users.get_current_user())
    style = request.GET.get('style') or 'pop'
    #logging('request style is=>'+style)
    if style=='pop':
        query = GqlQuery("SELECT * FROM Course WHERE ready = :1 ORDER BY rating",True)
        #q=Course.objects.all().filter("content_count >",10).order('rating')
    elif style=='rec':
        query = GqlQuery("SELECT * FROM Course WHERE ready = :1 ORDER BY created_at DESC",True)
        #q=Course.objects.all().filter("content_count >",10).order('-created_at')
    elif style=='self':
        query = Course.all().filter("creator =",users.get_current_user())
    elif style=='admin' and admin:
        query = Course.all()
    else:
        query = GqlQuery("SELECT * FROM Course WHERE ready = :1 ORDER BY rating",True)
        style="pop"
    return render_to_response('courses/index.html',{'courses':query.fetch(10),'style':style,'user':user,'admin':admin})
Пример #36
0
 def evaluationMeasureOLD(self, measure):
     path = os.path.join(os.path.dirname(__file__), 'viewer_templates/class_profile_evaluation.html')
     
     userProfiles = GqlQuery("SELECT * FROM UserProfile") 
    
     exerciseThereshold = 50
     videoThereshold = 70
    
     exercisePass = 0
     videoPass = 0
     userPassCourse = 0
     
     pass_course_users = []
     fail_course_users = []
 
     for userProfile in userProfiles:
         if(userProfile.evaluation_exercise >= exerciseThereshold):
             exercisePass += 1
        
         if(userProfile.evaluation_video >= videoThereshold):
             videoPass += 1
            
         if(userProfile.evaluation_video >= videoThereshold and userProfile.evaluation_exercise >= exerciseThereshold):
             userPassCourse += 1
             pass_course_users.append(userProfile)
         else:
             fail_course_users.append(userProfile)
             
     template_values = {'exercisePass': exercisePass,
                        'exerciseFail': userProfiles.count() - exercisePass,
                        'videoPass': videoPass,
                        'videoFail': userProfiles.count() - videoPass,
                        'userPassCourse': userPassCourse,
                        'userFailCourse': userProfiles.count() - userPassCourse,
                        'measureList': Utils().getMeasureList(),
                        'passCourseUsers': pass_course_users,
                        'failCourseUsers': fail_course_users
                       }
     
     self.response.out.write(template.render(path, template_values))
Пример #37
0
    def get(self):
        r = FlowerbedExplore()

        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())
        gamer = GqlQuery('SELECT * FROM Gamer WHERE ANCESTOR IS :1', gamer_key).get()

        if self.request.get('lat') and self.request.get('lon'):
            r.timestamp = int(time.time())
            lat = float(self.request.get('lat')) / 1000000
            lon = float(self.request.get('lon')) / 1000000
            gamer.point = GeoPt(lat, lon) #update user position
            #take adjacent tiles
            tiles = []
            requests = []
            tile = geocell.compute(GeoPt(lat, lon), RULES['GEO_RESOLUTION'])
            tiles.append(tile)
            tiles.extend(geocell.all_adjacents(tile))

            kind = kloombaDb.Flowerbed.kind()
            #prepare async requests
            for i in tiles:
                request = GqlQuery('SELECT * FROM Flowerbed WHERE ANCESTOR IS :1', Key.from_path(kind, i)).run()
                requests.append(request)
            for i in requests:
                for j in i:
                    fb = r.flowerbed.add()
                    fb.timestamp = int(time.mktime(j.timestamp.timetuple()))
                    fb.id = str(j.key())
                    fb.latitude = int(j.point.lat * 1000000)
                    fb.longitude = int(j.point.lon * 1000000)
                    fb.owner = j.owner_public_id
                    fb.flowers = j.flowers

        gamer.put()

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #38
0
    def correct_exercise_efficiency(self, usuario):
        subject_exercises = GqlQuery("SELECT * FROM ViewerExercise")
        totalEfficiency = 0
        totalExercises= 0 
        for subject_exercise in subject_exercises:
            problemLogs = GqlQuery("SELECT * FROM ProblemLog WHERE exercise = :1 AND user = :2 ORDER BY time_done ASC", subject_exercise.name, usuario.user)
            
            if(problemLogs.count() > 0 ):
                totalExercises += 1
                problemsTime = 0
                problemsAttempt = 0
                exerciseCorrect = False
                
                for problemLog in problemLogs:
                    problemsTime += problemLog.time_taken
                    problemsAttempt += problemLog.count_attempts
                    if(problemLog.correct == True):
                        exerciseCorrect = True
                        break

                if(exerciseCorrect == True):
                    if(problemsTime < 10):
                        totalEfficiency += 50
                    elif(problemsTime > 100):
                        totalEfficiency += 0
                    else:
                        totalEfficiency += (1 - (problemsTime/100))*50
                        
                    if(problemsAttempt > 6):
                        totalEfficiency += 0
                    else:
                        totalEfficiency += (1 - ((problemsAttempt-1)/5))*50                    
        
        if (totalExercises == 0):
            totalEfficiency  = 0
        else:
            totalEfficiency = int(totalEfficiency/totalExercises) 
            
        return totalEfficiency               
Пример #39
0
    def _checkProposedScheduleValidity(self, proposedStartTS, req=''):

        proposedStartTS = int(proposedStartTS)
        logging.info(proposedStartTS)
        q = GqlQuery(
            "SELECT * FROM Repair where status=:astatus and isScheduled=:isTrue and scheduleStart<:psTS order by scheduleStart desc",
            psTS=proposedStartTS,
            astatus='INCOMPLETE',
            isTrue=True)

        isOk = True
        prevRepair = None
        for arepair in q.run(limit=1):
            prevRepair = arepair
            if proposedStartTS - arepair.scheduleStart < REPAIRSLOTTIME:
                isOk = False

        q = GqlQuery(
            "SELECT * FROM Repair where status=:astatus and isScheduled=:isTrue and scheduleStart>=:psTS order by scheduleStart asc",
            psTS=proposedStartTS,
            astatus='INCOMPLETE',
            isTrue=True)

        tuples = []

        for arepair in q.run(limit=24):
            tuples.append(arepair)

        if len(tuples) > 0:
            if tuples[0].scheduleStart - proposedStartTS < REPAIRSLOTTIME:
                isOk = False

        logging.info(len(tuples))
        if isOk:
            return 'OK'

        for k in range(1, len(tuples)):
            if tuples[k].scheduleStart - tuples[
                    k - 1].scheduleStart >= REPAIRSLOTTIME:
                nextSlot = self._getnextAvailableSlot(tuples[k -
                                                             1].scheduleStart)
                logging.info('in next poo')
                logging.info(nextSlot)
                return 'Next available slot is from ' + nextSlot

        if len(tuples) < 24 and len(tuples) > 0:
            nextSlot = self._getnextAvailableSlot(tuples[len(tuples) -
                                                         1].scheduleStart)
            logging.info('in next')
            logging.info(nextSlot)
            return 'Next available slot is from ' + nextSlot

        if len(tuples) == 0:
            nextSlot = self._getnextAvailableSlot(prevRepair.scheduleStart)
            logging.info('in prev')
            logging.info(nextSlot)
            return 'Next available slot is from ' + nextSlot

        return 'No available slot withing 24 hours from proposed slot'
Пример #40
0
 def video_progress(self, usuario):
     
     x_vid = array([0.0, 50.0, 75.0, 100.0])
     y_vid = array([0.0, 30.0, 55.0, 100.0])
     
     pol_video_progress = Polynomial.fit(x_vid, y_vid, 5)
     
     total_video_progress = 0
     
     subject_videos = GqlQuery("SELECT * FROM ViewerVideo")
     
     for subject_video in subject_videos:
             
         userVideo = GqlQuery("SELECT * FROM UserVideo WHERE video = :1 AND user = :2", subject_video.video, usuario.user).get()
         
         if(userVideo != None):
             porcentajeVideo = (userVideo.seconds_watched/userVideo.duration)*100
             if(porcentajeVideo >= 100):
                 total_video_progress += 100
             else:
                 total_video_progress += pol_video_progress(porcentajeVideo)
                     
     return int(total_video_progress/subject_videos.count())
Пример #41
0
    def get(self, username):
        if self.user:
            user = Users.byUsername(username)
            if not user:
                return self.render('error.html', msg='User Not Found...')

            userID = str(user.key().id())
            posts = GqlQuery('select * from Posts where owner = ' + userID)
            return self.render('user.html',
                               you=self.user,
                               user=user,
                               posts=posts)
        else:
            return self.redirect('/login')
Пример #42
0
    def get(self):
        users = GqlQuery("SELECT * FROM User")

        users = list(users)
        logging.log(40, "Users: " + repr(users))

        points = filter(None, (u.coords for u in users))
        logging.log(40, "Points: " + repr(points))

        img_url = None
        if points:
            img_url = gmaps_img(points)

        self.render('google-maps.html', img_url=img_url, users=users)
Пример #43
0
    def get(self, ruser):
        ruser = urllib.unquote(urllib.unquote(ruser))
        if self.request.GET:
            show = self.request.get('show')
            if show == '':
                show = 0
            else:
                show = Paging().Test_page(show)
        else:
            show = 0
        show = int(show)
        
        nump = 12
        if self.take_browser() == 'm/':
            nump = 5

        fotolist = GqlQuery("SELECT * FROM FotosDB WHERE user = '******' ORDER BY date DESC" % ruser)
        paging = Paging().page(fotolist, show, num = nump)
        fotolist = fotolist.fetch(nump, show)
        

        if ruser == users.get_current_user().nickname():
            dell = True 
        else:
            dell = False
        
        template_values = {
            'upload_url':'/uploadfoto',
            'table':self.table_create(fotolist),
            'paging':paging,
            'dell':dell,
            'fotolist': fotolist,
            }
        if self.take_browser() == 'm/':
            item = { }
            template_values.update(item)
        self.generate('fotos.index.html', template_values, razdel = '', logo = 'logo', title = 'Фотоальбом %s' % ruser);
Пример #44
0
    def post(self):
        #TODO: add comments
        user = cgi.escape(self.request.get('username'))
        q = GqlQuery("SELECT artist, time FROM Listen WHERE user = '******'")
        
        if q.count(limit=1) == 0:
            logging.info('Fetching data for user: %s', user)
            taskqueue.add(url='/fetchdata', params={'username': user})
            self.response.write('Fetching data for user ' + user + '. Please wait')
            return
        else:
            logging.info('Already have data for user %s in datastore. Not' + \
            ' fetching any new data from Last.fm', user)
        
        for y in range(1, 13):
            logging.info('Getting stats for month ' + str(y))
            plays = 0
            artists = dict()
            
            for x in q:
                if x.time.month == y:
                    plays += 1
                    if x.artist not in artists:
                        artists[x.artist] = 1
                    else:
                       artists[x.artist] += 1

            self.response.write('<b>' + calendar.month_name[y] + '</b>')
            self.response.write('<br>Total plays: ' + str(plays))
            self.response.write('<br>Total artists: ' + str(len(artists)))
            self.response.write('<br><br>Top artists:<br>')
            
            sorted_artists = sorted(artists, key=artists.get, reverse=True)
            for z in range(0, 10):
                self.response.write(str(z+1) + '. ' + sorted_artists[z].encode('utf-8') + ': ' + \
                str(artists[sorted_artists[z]]) + '<br>')
            self.response.write('<br><br>')
Пример #45
0
    def roomy_list(self):
        list = []
        try:
            logger = logging.getLogger("canvasLogger")
            #roomuser has string key for users in it, convert to obj list of users
            roomyQ = GqlQuery("SELECT * FROM RoomUser WHERE room = :room_key",
                              room_key=str(self.key()))
            for ru in roomyQ:
                roomy = User().get(ru.user)
                list.append(roomy)
        except:
            if logger:
                logger.error("Room.roomy_list: exception")

        return list
Пример #46
0
    def get(self, *args):
        rent = GqlQuery("SELECT * FROM DBRent Where is_enable = True And in_trash_can = False ORDER BY sort desc")
        self.rent = rent.fetch(100,0)

        news = GqlQuery("SELECT * FROM DBNews Where is_enable = True And in_trash_can = False ORDER BY sort desc")
        self.news = news.fetch(100,0)

        buy = GqlQuery("SELECT * FROM DBBuy Where is_enable = True And in_trash_can = False ORDER BY sort desc")
        self.buy = buy.fetch(100,0)
        self.render("sitemap.html")
Пример #47
0
    def get(self):
        r = BookmarkAdd()

        if not self.request.get('id'):
            return

        fb_key = self.request.get('id')
        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())

        #get flowerbed
        flowerbed = GqlQuery('SELECT * FROM Flowerbed WHERE __key__=:1',
                             fb_key).get()
        if not flowerbed:
            return  #no such flowerbed
        #check bookmark
        bookmark = GqlQuery(
            'SELECT * FROM Bookmark WHERE ANCESTOR IS :1 AND flowerbed=:2',
            gamer_key, Key(fb_key)).get()
        if bookmark:
            return  #bookmark allready exist

        bookmark = kloombaDb.Bookmark(parent=gamer_key)
        bookmark.owner = user.user_id()
        bookmark.flowerbed = flowerbed
        bookmark.put()

        r.timestamp = int(time.time())
        fb = r.flowerbed
        fb.timestamp = int(time.mktime(flowerbed.timestamp.timetuple()))
        fb.id = str(flowerbed.key())
        fb.latitude = int(flowerbed.point.lat * 1000000)
        fb.longitude = int(flowerbed.point.lon * 1000000)
        fb.owner = flowerbed.owner_public_id
        fb.flowers = flowerbed.flowers

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #48
0
def index():
    user = users.get_current_user()
    if user:
        if not UserSettings.has_seen_example() and GqlQuery(
                'SELECT __key__ FROM Site WHERE owner=:1 AND example=true',
                user).count(1) == 0:
            _create_example_site(user)
            UserSettings.mark_example_as_seen()
        sites = Site.gql('WHERE users=:1 ORDER BY name', user)
        site_form = PageForm()
        page_form = PageForm()
        return render_template('index.html',
                               sites=sites,
                               new_site_form=site_form,
                               page_form=page_form)
    else:
        return home()
Пример #49
0
    def get(self, table):
        if table in dir(kloombaDb):
            i = 0
            request = GqlQuery('SELECT * FROM ' + table).run()
            for item in request:
                i += 1
                if 'timestamp' in dir(item):
                    kloombaDb.__dict__[table].__dict__['timestamp'].__dict__[
                        'auto_now'] = False
                if 'lastActiveTimestamp' in dir(item):
                    kloombaDb.__dict__[table].__dict__[
                        'lastActiveTimestamp'].__dict__['auto_now'] = False
                item.put()
            memcache.flush_all()

            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write("Updated table: %s\nUpdated entitys: %d" %
                                    (table, i))
Пример #50
0
    def post(self):
        name_html = self.get_user()
        score_html = self.request.get('highscore_get')
        speed_html = self.request.get('speed_get')
        multiplier_html = self.request.get('multiplier_get')
        hash_client = self.request.get('hash_get')

        hash_server = hashlib.sha256(
            str(score_html) + str(speed_html) + str(multiplier_html) +
            secret).hexdigest()

        if not name_html:
            self.render('tetris.html', error="You are not logged in.")
        elif hash_server != hash_client:
            self.render(
                'tetris.html',
                error="Screw you Espen! Now you can't cheat your way up!")
        else:
            try_highscore = Highscore(name=name_html,
                                      highscore=float(score_html),
                                      speed=float(speed_html),
                                      multiplier=float(multiplier_html),
                                      parent=k)
            all_highscores = GqlQuery(
                "SELECT * FROM Highscore WHERE ANCESTOR IS :1", k)

            count = 0
            for highscore in all_highscores:
                if highscore.name == name_html:
                    count += 1
                    if try_highscore.highscore > highscore.highscore:
                        highscore.delete()
                        try_highscore.put()

            if count == 0:
                try_highscore.put()

            self.redirect('/tetris')
Пример #51
0
    def get(self):
        r = BookmarkAdd()

        if not self.request.get('id'):
            return

        fb_key = self.request.get('id')
        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())

        #get flowerbed
        flowerbed = GqlQuery('SELECT * FROM Flowerbed WHERE __key__=:1', fb_key).get()
        if not flowerbed:
            return #no such flowerbed
        #check bookmark
        bookmark = GqlQuery('SELECT * FROM Bookmark WHERE ANCESTOR IS :1 AND flowerbed=:2', gamer_key, Key(fb_key)).get()
        if bookmark:
            return #bookmark allready exist

        bookmark = kloombaDb.Bookmark(parent=gamer_key)
        bookmark.owner = user.user_id()
        bookmark.flowerbed = flowerbed
        bookmark.put()

        r.timestamp = int(time.time())
        fb = r.flowerbed
        fb.timestamp = int(time.mktime(flowerbed.timestamp.timetuple()))
        fb.id = str(flowerbed.key())
        fb.latitude = int(flowerbed.point.lat * 1000000)
        fb.longitude = int(flowerbed.point.lon * 1000000)
        fb.owner = flowerbed.owner_public_id
        fb.flowers = flowerbed.flowers

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #52
0
	def get(self):
		import random
		import string
		
		image_url = self.request.get('image_url')

		width=self.request.get('width')
		if width:
			width = int(self.request.get('width'))
		else:
			width=60
	
		tinyname= ''.join(random.sample(string.letters*2, 10))
		
		if not width or (width < 10 or width > 1200):
			width = 90
		
		savedimages = GqlQuery("SELECT * FROM Image WHERE url = :1 and width = :2", image_url, width)
		
		image = savedimages.get()
		
		if image:
			ext=image.name[-3:]
			mime=ext
			if ext=="jpg":
				mime="jpeg"
			self.response.headers['Content-Type'] = "image/%s" % mime
			self.response.out.write(image.thumb)
			self.response.out.write(image.content)
			return
		
		image_re = re.compile(r'http://([\w\d\_\=\?\-\.\/\&\;\%]+)')
		
		if image_re.search(image_url):
			domain=image_re.search(image_url).group(0)
			ext = domain[-3:].lower()
			
			if ext == "jpg" or ext == "png" or ext == "gif":
				
				mime=ext
				if ext=="jpg":
					mime="jpeg"
				
				parts=domain.split("/")
				filename=parts[len(parts)-1]
	
				#get image 
				image_content = urlfetch.fetch(image_url).content
				thumb = images.resize(image_content, width, width)
	
				if thumb:
					image=Image()
					image.url=image_url
					image.width=width
					image.name=tinyname
					image.content = db.Blob(image_content)
					image.thumb = db.Blob(thumb)
					image.put()

					self.response.headers['Content-Type'] = "image/%s" % mime
					self.response.out.write(thumb)
				else:
					self.error(404)
Пример #53
0
 def cognitiveModel(self, usuario):
     
     hintAvoidance = 0
     videoAvoidance = 0
     unreflectiveUser = 0
     hintAbuser = 0
     
     totalDifferentExercises = 0
     
     subject_exercises = GqlQuery("SELECT * FROM ViewerExercise")
     
     for subject_exercise in subject_exercises:
         problemLogs = GqlQuery("SELECT * FROM ProblemLog WHERE exercise = :1 AND user = :2 ORDER BY time_done ASC", subject_exercise.name, usuario.user)
         
         if(problemLogs.count() > 0 ):
             
             totalDifferentExercises += 1
             
             exercisesSameKind = 0
             hintAvoidPoints = 0
             videoAvoidPoints = 0
             unreflectivePoints = 0
             hintAbusePoints = 0
         
             exerciseVideo = GqlQuery("SELECT * FROM ExerciseVideo WHERE exercise = :1", subject_exercise.exercise).get()                
             userVideo = GqlQuery("SELECT * FROM UserVideo WHERE video = :1 AND user= :2", exerciseVideo.video, usuario.user).get()
             videoDate = datetime.datetime.now()
             if(userVideo != None):
                 videoDate = userVideo.backup_timestamp
             
             
             for problemLog in problemLogs:
                 
                 exercisesSameKind += 1
                 
                 # Video Avoidance
                 if(problemLog.correct == False and (problemLog.time_done < videoDate)):
                     videoAvoidPoints += 1
                                             
                 # Hint Avoidance                    
                 if(problemLog.correct == False and problemLog.count_hints == 0):
                     hintAvoidPoints += 1
                 if(problemLog.correct == False and problemLog.count_hints == 1):    
                     hintAvoidPoints += 0.5
                     
                 # Calculamos el no reflexionador
                 if(problemLog.correct == False):
                     intentoAnterior = 0
                     listaIntentos = problemLog.time_taken_attempts
                     listaIntentos.sort()
                     
                     for intento in listaIntentos:
                         diferenciaTemporal = math.fabs(intento-intentoAnterior)
                         intentoAnterior = intento
                         #Comprobamos que sea menor de 10 segundos para considerar abuso
                         if(diferenciaTemporal < 10):
                             unreflectivePoints += 1
                             break
                 #Fin no reflexionador
                 
                 #Calculo pide pistas demasiado rapido
                 if(problemLog.count_hints > 0):
                     pistaAnterior = 0
                     listaPistas = problemLog.hint_time_taken_list
                     listaPistas.sort()
                     
                     for pista in listaPistas:
                         diferenciaTemporal = math.fabs(pista-pistaAnterior)
                         pistaAnterior = pista
                         #Comprobamos que sea menor de 10 segundos para considerar abuso
                         if(diferenciaTemporal < 10):
                             hintAbusePoints += 1
                             break
                 #Fin abusor pistas
                 
                 if(problemLog.correct == True):
                     break
                 else:
                     continue
                                     
             hintAvoidance += ((hintAvoidPoints/exercisesSameKind)*100)
             videoAvoidance += ((videoAvoidPoints/exercisesSameKind)*100)
             unreflectiveUser += ((unreflectivePoints/exercisesSameKind)*100)
             hintAbuser += ((hintAbusePoints/exercisesSameKind)*100)
             
     if(totalDifferentExercises != 0):
         hintAvoidanceFinal = int(hintAvoidance/totalDifferentExercises)
         videoAvoidanceFinal = int(videoAvoidance/totalDifferentExercises)
         unreflectiveUserFinal = int(unreflectiveUser/totalDifferentExercises)
         hintAbuserFinal = int(hintAbuser/totalDifferentExercises)
         
         return [hintAvoidanceFinal, videoAvoidanceFinal,
                 unreflectiveUserFinal, hintAbuserFinal]
     else:
         return [0,0,0,0]
             
Пример #54
0
    def get_profile_mean(self, profileName):
        
        queryUserProfile = GqlQuery("SELECT * FROM UserProfile")       

        if(profileName == viewer_code.viewer_consts.EXERCISE_VIDEO_EVALUATION):
            evaluation_exercise_suma = 0
            evaluation_video_suma = 0
            
            for userProfile in queryUserProfile:
                evaluation_exercise_suma += userProfile.evaluation_exercise
                evaluation_video_suma += userProfile.evaluation_video
            
            evaluation_exercise_mean = int(evaluation_exercise_suma / (queryUserProfile.count()))
            evaluation_video_mean = int(evaluation_video_suma / (queryUserProfile.count()))
            
            return [evaluation_exercise_mean, evaluation_video_mean]
        
        elif(profileName == viewer_code.viewer_consts.USE_OF_PLATFORM):
            exercise_explorer_suma = 0
            video_explorer_suma = 0
            exercise_abandon_suma = 0
            video_abandon_suma = 0
            optional_suma = 0
            one_correct_suma = 0
            focus_videos_suma = 0
            focus_exercises_suma = 0
            
            for userProfile in queryUserProfile:
                exercise_explorer_suma += userProfile.exercise_explorer
                video_explorer_suma += userProfile.video_explorer
                exercise_abandon_suma += userProfile.exercise_abandon
                video_abandon_suma += userProfile.video_abandon
                optional_suma += userProfile.optional_elements
                one_correct_suma += userProfile.exercise_one_correct
                focus_videos_suma += userProfile.focus_videos
                focus_exercises_suma += userProfile.focus_exercises
            
            exercise_explorer_mean = int(exercise_explorer_suma / (queryUserProfile.count()))
            video_explorer_mean = int(video_explorer_suma / (queryUserProfile.count()))
            exercise_abandon_mean = int(exercise_abandon_suma / (queryUserProfile.count()))
            video_abandon_mean = int(video_abandon_suma / (queryUserProfile.count()))
            optional_mean = int(optional_suma / (queryUserProfile.count()))
            one_correct_mean = int(one_correct_suma / (queryUserProfile.count()))
            focus_exercises_mean = int(focus_exercises_suma / (queryUserProfile.count()))
            focus_videos_mean = int(focus_videos_suma / (queryUserProfile.count()))
            
            return [exercise_explorer_mean, video_explorer_mean,
                    exercise_abandon_mean, video_abandon_mean,
                    optional_mean, one_correct_mean,
                    focus_exercises_mean, focus_videos_mean]
            
        elif(profileName == viewer_code.viewer_consts.CORRECT_PROGRESS):
            
            video_efficiency_suma = 0
            exercise_efficiency_suma = 0
            video_progress_suma = 0
            exercise_progress_suma = 0
            correct_exercise_suma = 0
            efficiency_proficiencies_suma = 0
            correct_solving_efficiency_suma = 0
            
            for userProfile in queryUserProfile:
                video_efficiency_suma += userProfile.video_efficiency
                exercise_efficiency_suma += userProfile.correct_exercise_effiency
                video_progress_suma += userProfile.video_progress
                exercise_progress_suma += userProfile.exercise_progress
                correct_exercise_suma += userProfile.correct_exercises
                efficiency_proficiencies_suma += userProfile.efficiency_proficiencies
                correct_solving_efficiency_suma += userProfile.correct_exercise_solving_efficiency
                
            video_efficiency_mean = int(video_efficiency_suma / (queryUserProfile.count()))
            exercise_efficiency_mean = int(exercise_efficiency_suma / (queryUserProfile.count()))
            video_progress_mean = int(video_progress_suma / (queryUserProfile.count()))
            exercise_progress_mean = int(exercise_progress_suma / (queryUserProfile.count()))
            correct_exercise_mean = int(correct_exercise_suma / (queryUserProfile.count()))
            efficiency_proficiencies_mean = int(efficiency_proficiencies_suma / (queryUserProfile.count()))
            correct_solving_efficiency_mean = int(correct_solving_efficiency_suma / (queryUserProfile.count()))
            
            return [exercise_efficiency_mean, video_efficiency_mean,
                    exercise_progress_mean, video_progress_mean,
                    correct_exercise_mean, efficiency_proficiencies_mean,
                    correct_solving_efficiency_mean]
                        
        elif(profileName == viewer_code.viewer_consts.TIME_DISTRIBUTION):
            
            time_morning_suma = 0
            time_afternoon_suma = 0
            time_night_suma = 0
            morning_efficiency_suma = 0
            afternoon_efficiency_suma = 0
            night_efficiency_suma = 0
            
            constancy_mean_suma = 0
            constancy_var_suma = 0
            
            morning_efficiency_counter = 0
            afternoon_efficiency_counter = 0
            night_efficiency_counter = 0
            
            for userProfile in queryUserProfile:
                time_morning_suma += userProfile.time_schedule_morning
                time_afternoon_suma += userProfile.time_schedule_afternoon
                time_night_suma += userProfile.time_schedule_night
                constancy_mean_suma += userProfile.constancy_mean
                constancy_var_suma += userProfile.constancy_variance
                if(userProfile.morning_schedule_efficiency != 0):                    
                    morning_efficiency_suma += userProfile.morning_schedule_efficiency
                    morning_efficiency_counter += 1
                    
                if(userProfile.afternoon_schedule_efficiency != 0):                    
                    afternoon_efficiency_suma += userProfile.afternoon_schedule_efficiency
                    afternoon_efficiency_counter += 1
                    
                if(userProfile.night_schedule_efficiency != 0):                    
                    night_efficiency_suma += userProfile.night_schedule_efficiency
                    night_efficiency_counter += 1
                 
            time_morning_mean = int(time_morning_suma / (queryUserProfile.count()))
            #time_afternoon_mean = int(time_afternoon_suma / (queryUserProfile.count()))
            time_night_mean = int(time_night_suma / (queryUserProfile.count()))
            time_afternoon_mean = 100 - time_morning_mean - time_night_mean
            constancy_mean_mean = int(constancy_mean_suma / (queryUserProfile.count()))
            constancy_var_mean = int(constancy_var_suma / (queryUserProfile.count()))
            
            if(morning_efficiency_counter == 0):
                morning_efficiency_mean = 0
            else:
                morning_efficiency_mean = int(morning_efficiency_suma/morning_efficiency_counter)
                
            if(afternoon_efficiency_counter == 0):
                afternoon_efficiency_mean = 0
            else:
                afternoon_efficiency_mean = int(afternoon_efficiency_suma/afternoon_efficiency_counter)
            
            if(night_efficiency_counter == 0):
                night_efficiency_mean = 0
            else:
                night_efficiency_mean = int(night_efficiency_suma/night_efficiency_counter)
            
            return [time_morning_mean, time_afternoon_mean, time_night_mean,
                    constancy_mean_mean, constancy_var_mean,
                    morning_efficiency_mean, afternoon_efficiency_mean, night_efficiency_mean]
              
        elif(profileName == viewer_code.viewer_consts.EXERCISE_SOLVING_HABITS):
            
            recommendation_listener_suma = 0
            forgetful_exercises_suma = 0
            hint_avoidance_suma = 0
            video_avoidance_suma = 0
            unreflective_user_suma = 0
            hint_abuser_suma = 0
            
            for userProfile in queryUserProfile:
                recommendation_listener_suma += userProfile.recommendation_listener
                forgetful_exercises_suma += userProfile.forgetful_exercises
                hint_avoidance_suma += userProfile.hint_avoidance
                video_avoidance_suma += userProfile.video_avoidance
                unreflective_user_suma += userProfile.unreflective_user
                hint_abuser_suma += userProfile.hint_abuser
                
            recommendation_listener_mean = int(recommendation_listener_suma / (queryUserProfile.count()))
            forgetful_exercises_mean = int(forgetful_exercises_suma / (queryUserProfile.count()))
            hint_avoidance_mean = int(hint_avoidance_suma / (queryUserProfile.count()))
            video_avoidance_mean = int(video_avoidance_suma / (queryUserProfile.count()))
            unreflective_user_mean = int(unreflective_user_suma / (queryUserProfile.count()))
            hint_abuser_mean = int(hint_abuser_suma / (queryUserProfile.count()))
            
            return [recommendation_listener_mean, forgetful_exercises_mean,
                    hint_avoidance_mean, video_avoidance_mean,
                    unreflective_user_mean, hint_abuser_mean]
            
        elif(profileName == viewer_code.viewer_consts.GAMIFICATION_HABITS):
            
            badge_over_time_suma = 0
            badge_percentage_suma = 0
            
            for userProfile in queryUserProfile:
                badge_over_time_suma += userProfile.badge_over_time
                badge_percentage_suma += userProfile.badge_point_percentage
                
            badge_over_time_mean = int(badge_over_time_suma / (queryUserProfile.count()))
            badge_percentage_mean = int(badge_percentage_suma / (queryUserProfile.count()))
            
            return [badge_over_time_mean, badge_percentage_mean]
queryUserData = models.UserData.all()

usuarios =  GqlQuery("SELECT * FROM UserProfile ORDER BY user_id ASC")

for usuarioID in usuarios:
    
    #print usuarioID
    userData = GqlQuery("SELECT * FROM UserData WHERE user_id = :1", usuarioID).get()

    #print userData.user_id
    
    exerciseUserBadgesNoTematic = GqlQuery("SELECT * FROM UserBadge WHERE badge_name IN :1 AND user = :2", listaBadgesEjerciciosNoTematicos, userData.user)
    exerciseUserBadgesTematic = GqlQuery("SELECT * FROM UserBadge WHERE badge_name IN :1 AND user = :2", listaBadgesEjerciciosTematicos, userData.user)    
    allExerciseUserBadges = list(exerciseUserBadgesNoTematic) + list(exerciseUserBadgesTematic)    
    
    videoUserBadges = GqlQuery("SELECT * FROM UserBadge WHERE badge_name IN :1 AND user = :2", listaBadgesVideos, userData.user)
    
    allUserBadges = GqlQuery("SELECT * FROM UserBadge WHERE user = :1", userData.user)
    
    
    tiempoEnEjercicios = 0
    tiempoEnVideos = 0
    
    videos = models.VideoLog.all().filter('user ='******'user =', userData.user)
    
    for ejercicio in ejercicios:
Пример #56
0
    def oldEvaluation(self):
        
        user_id = self.request.get('userId')
        usuario = ViewerUser.get_by_key_name(user_id)
        
        ejerciciosMin3 = 0
        videosMin50 = 0
        
        # Ejercicios y videos de la asignatura
        subject_videos = GqlQuery("SELECT * FROM ViewerVideo")
        subject_exercises = GqlQuery("SELECT * FROM ViewerExercise")

        # Para cada video de la asignatura
        for subject_video in subject_videos:
            # Coge los ejercicios asociados a dicho video
            exerciseVideos = GqlQuery("SELECT * FROM ExerciseVideo where video = :1", subject_video.video)
            
            # Si encuentra el ejercicio asociado a dicho video
            if(exerciseVideos != None):
                for exerciseVideo in exerciseVideos:
                    # Coge el UserExercise de dicho ejercicio
                    userExercise = GqlQuery("SELECT * FROM UserExercise WHERE exercise_model = :1 AND user = :2", exerciseVideo.exercise, usuario.user).get()
                    
                    # Si no ha encontrado el ejercicio asociado al video, mira directamente el video
                    if(userExercise == None):
                        
                        userVideo = GqlQuery("SELECT * FROM UserVideo WHERE video = :1 AND user = :2", subject_video.video, usuario.user).get()
                        
                        if(userVideo != None):
                            porcentaje = userVideo.seconds_watched/userVideo.duration
                            if(porcentaje >= 0.5):                
                                if(subject_video.youtube_id == 'WKR3h7vBxtU' or subject_video.youtube_id == 'NwZqpCAf6o8' or subject_video.youtube_id == 'ESSg3pdsSqA'):
                                    videosMin50 += 1/3
                                elif(subject_video.youtube_id == 'EQ4JVdRLxlU'):
                                    videosMin50 += 1/4
                                elif(subject_video.youtube_id == '7jj6zSWEEgk'):
                                    videosMin50 += 1/2
                                else:
                                    videosMin50 += 1
                            
                    # Si ha encontrado el ejercicio asociado al video, comprueba primero si el ejercicio esta bien hecho
                    else:
                        # Si tiene mas de 3 correctos, sumamos directamente ejercicio y video
                        if(userExercise.total_correct >= 3):
                            ejerciciosMin3 += 1
                            if(subject_video.youtube_id == 'WKR3h7vBxtU' or subject_video.youtube_id == 'NwZqpCAf6o8' or subject_video.youtube_id == 'ESSg3pdsSqA'):
                                videosMin50 += 1/3
                            elif(subject_video.youtube_id == 'EQ4JVdRLxlU'):
                                videosMin50 += 1/4
                            elif(subject_video.youtube_id == '7jj6zSWEEgk'):
                                videosMin50 += 1/2
                            else:
                                videosMin50 += 1  
                        # Si tiene menos de 3 correctos, NO sumamos ejercicio y miramos video                  
                        else:
                            userVideo = GqlQuery("SELECT * FROM UserVideo WHERE video = :1 AND user = :2", subject_video.video, usuario.user).get()
                        
                            if(userVideo != None):
                                porcentaje = userVideo.seconds_watched/userVideo.duration
                                if(porcentaje >= 0.5):                
                                    if(subject_video.youtube_id == 'WKR3h7vBxtU' or subject_video.youtube_id == 'NwZqpCAf6o8' or subject_video.youtube_id == 'ESSg3pdsSqA'):
                                        videosMin50 += 1/3
                                    elif(subject_video.youtube_id == 'EQ4JVdRLxlU'):
                                        videosMin50 += 1/4
                                    elif(subject_video.youtube_id == '7jj6zSWEEgk'):
                                        videosMin50 += 1/2
                                    else:
                                        videosMin50 += 1
                
            # Si el video no tiene un ejercicio asociado, mira directamente el video
            else:
                userVideo = GqlQuery("SELECT * FROM UserVideo WHERE video = :1 AND user = :2", subject_video.video, usuario.user).get()
                    
                if(userVideo != None):
                    porcentaje = userVideo.seconds_watched/userVideo.duration
                    if(porcentaje >= 0.5):                
                        videosMin50 += 1
        
        ejerciciosMin3 = int((ejerciciosMin3/subject_exercises.count())*100)
        videosMin50 = int((videosMin50/subject_videos.count())*100)
                 
        userProfile = UserProfile.get_by_key_name(user_id)
        
        if(userProfile == None):
            userProfile = UserProfile(key_name = user_id, user = usuario.user, user_nickname = usuario.user_nickname, 
                                      user_id = usuario.user_id,
                                      evaluation_exercise = ejerciciosMin3,  evaluation_video = videosMin50)
        else:    
            userProfile.evaluation_exercise = ejerciciosMin3
            userProfile.evaluation_video = videosMin50

        userProfile.put()        
        
listaBadgesTematicas = []

for badge in util_badges.badges_tematicas_no_maestro():
    #print badge.exercise_names_required
    listaBadgesTematicas.append(badge.name)
    
usuarios =  GqlQuery("SELECT * FROM UserProfile ORDER BY user_id ASC")

for usuarioID in usuarios:
    
    #print usuarioID
    userData = GqlQuery("SELECT * FROM UserData WHERE user_id = :1", usuarioID).get()

    #print userData.user_id
    topicUserBadges = GqlQuery("SELECT * FROM UserBadge WHERE badge_name IN :1 AND user = :2 ORDER BY date ASC", listaBadgesTematicas, userData.user)
    
    percentageSumForAllTematicBadges = 0
    numberTematicBadges = topicUserBadges.count(1000)
    #print "Tematic Badges %d" % numberTematicBadges

    startDate = datetime.datetime(2013,8,1,0,0,1)
    endDate = None
    for topicUserBadge in topicUserBadges:
        
        #print topicUserBadge

        endDate = topicUserBadge.date
        badge_requisites = ""
        
        for topicBadge in util_badges.badges_tematicas_no_maestro():
Пример #58
0
    def accounts_page(self):
        user = users.get_current_user()

        if user and (user.email() in ACTIVE_USER_EMAILS or users.is_current_user_admin()):
            reloadPage = False
            simpleText = False
            usedby = {}
            user_amount_map = {}
            user_adjustment = {}
            paymentMap = {}
            error_message = ""
            calculation_error = ""
            total_amount = 0
            
            if(self.request.get('simpletext') and self.request.get('simpletext') == "True"):
                simpleText = True
                
                
            # split month into tokens
            month = self.request.get('month') if (self.request.get('month') and not self.request.get('month') == "")  else datetime.date.today().replace(day=1).strftime("%Y-%m-%d")
            # if there's a cmd param
            if(self.request.get('cmd')):
                if(self.request.get('cmd') == "delete"):
                    eid = long(self.request.get('eid'))
                    entry = Accounts.get_by_id(eid)
                    entry.deleted = True
                    entry.put()
                    self.redirect('/accounts')
                    return
                else:
                    description = self.request.get('description') if  (self.request.get('description') and not self.request.get('description') == "") else False
                
                    error_messages = []
                    if(not description):
                        error_messages.append("Description is mandatory")
                    
                    amount = self.request.get('amount') if (self.request.get('amount') and not self.request.get('amount') == "") else False
                    if(not amount):
                        error_messages.append("Amount is mandatory")
                    try:
                        int(amount)
                    except:
                        error_messages.append("Amount should be a number")
                    
                    expenseby = self.request.get('expenseby') if (self.request.get('expenseby') and not self.request.get('expenseby') == "") else False
                    if(not expenseby):
                        error_messages.append("Expense by is mandatory")
    
                    # TODO: fix this
                    expenseby = User(expenseby)
                    
                    count = 0
                    user_objects = {}
    
                    for email in ACTIVE_USER_EMAILS:
                        current_user = User(email)
                        user_objects[email] = current_user
                        usedby[email] = 1 if (self.request.get(email) and self.request.get(email) == "on") else 0
                        if(usedby[email] == 1):
                            count += 1
                        
                        
                    
    #                 all = 1 if (self.request.get('all') and self.request.get('all') == "on") else 0
                    if(count == 0):
                        error_messages.append("Atleast one person should be selected")
                    
                    if(len(error_messages) == 0):
                        amount = int(amount)
                        individual_amount = amount / count
                        # #Add new entry 
                        newAccountEntry = Accounts()
                        newAccountEntry.expenseby = expenseby
                        newAccountEntry.expensefor = description
                        newAccountEntry.expenseamount = amount
                        newAccountEntry.expensemonth = datetime.date.today().replace(day=1)
                        newAccountEntry.put()
                        
                        for email, current_user in user_objects.iteritems():
                            contribution = Contribution(account=newAccountEntry)
                            contribution.contributor = current_user
                            if(current_user == expenseby):
                                if(usedby[email] == 1):
                                    contribution.amount = float(individual_amount - amount)
                                else:
                                    contribution.amount = float(0 - amount)
                            else:
                                if(usedby[email] == 1):
                                    contribution.amount = float(individual_amount)
                                else:
                                    contribution.amount = float(0)
                            contribution.put()
                        """ 
                         description=""
                        amount=""
                        expenseby=""
                        usedby = [] """
                        reloadPage = True
                    else:
    
                        for error in error_messages:
                            error_message += "[x] " + error + "<br />"
                    
                    # GqlQuery("SELECT DISTINCT expensedate ")
                
                
            q = GqlQuery("SELECT DISTINCT expensemonth FROM Accounts")
            available_months = q.fetch(24)  # let's limit to 2 yrs
            expenses = Accounts.gql("WHERE expensemonth=DATE('" + month + "') ORDER BY expensedate DESC").fetch(1000)
            for expense in expenses:
                if not expense.deleted:
                    total_amount += expense.expenseamount
                for contribution in expense.contributions:
                    if not expense.deleted:
                        if(not contribution.contributor.email() in user_amount_map):
                            user_amount_map[contribution.contributor.email()] = 0
                        user_amount_map[contribution.contributor.email()] += contribution.amount
                    setattr(expense, contribution.contributor.email(), contribution.amount)
            if (total_amount > 0):
                user_adjustment = user_amount_map.copy()
                asc_adjustment_keys = get_sorted_keys(user_adjustment)
                desc_amount_keys = get_sorted_keys(user_amount_map, True)
                minUser = asc_adjustment_keys[0]
                
                for mapuser in desc_amount_keys:
                    if(user_adjustment[minUser] < 0 and not user_adjustment[mapuser] == 0 and mapuser != minUser):
                        # calcualte amount to pay
                        payamount = user_adjustment[mapuser]
                        user_adjustment[minUser] += payamount
                        user_adjustment[mapuser] = 0
                        paymentMap[mapuser] = [minUser, payamount]
                    elif int(user_adjustment[mapuser]) > 0:
                        logging.error("calculation error: " + str(user_adjustment[mapuser]) + " " + mapuser + "" + minUser)
                        calculation_error = "calculation error: " + str(user_adjustment[mapuser]) + " " + mapuser + "" + minUser
                        
                    asc_adjustment_keys = get_sorted_keys(user_adjustment)
                    minUser = asc_adjustment_keys[0]
            template_values = {
                               'page':{'title':"Accounts"},
                               'user':user,
                               'error_message': error_message,
                'simpleText': simpleText,
                'logout_url': users.create_logout_url("/"),
                'active_tab': "accounts",
                'reloadPage': reloadPage,
                'user_emails': ACTIVE_USER_EMAILS,
                'users': ACTIVE_USERS,
                'available_months': available_months,
                'usedby': usedby,
                'paymentMap': paymentMap,
                'expenses': expenses,
                'calculation_error':calculation_error,
                'totals': {'amount':total_amount, 'useramounts': user_amount_map}
            }
            template = JINJA_ENVIRONMENT.get_template('accounts/index.html')
            self.response.write(template.render(template_values))
        elif (user):
            template_values = {'logout_url': users.create_logout_url("/")}
            template = JINJA_ENVIRONMENT.get_template('403.html')
            self.response.write(template.render(template_values))
        else:
            self.redirect(users.create_login_url(self.request.uri))
Пример #59
0
    def get(self):
        r = Login()

        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())
        gamer = GqlQuery('SELECT * FROM Gamer WHERE ANCESTOR IS :1', gamer_key).get()
        if not gamer:
            #make new account
            gamer = kloombaDb.Gamer(parent=gamer_key)
            gamer.user_id = user.user_id()
            gamer.public_id = hashlib.md5(user.user_id() + SALT).hexdigest()
            gamer.name = user.nickname()
            gamer.put()
            #make new backpack
            backpack = []
            #add flowers
            bp = kloombaDb.Backpack(parent=gamer_key)
            bp.owner = user.user_id()
            bp.name = 'flower'
            bp.amount = 100
            bp.put()
            backpack.append(bp)
            #add flowerbeds
            bp = kloombaDb.Backpack(parent=gamer_key)
            bp.owner = user.user_id()
            bp.name = 'flowerbed'
            bp.amount = 100
            bp.put()
            backpack.append(bp)
            #set first_time
            r.first_time = True
        else:
            gamer.put()
            backpack = GqlQuery('SELECT * FROM Backpack WHERE ANCESTOR IS :1', gamer_key).run()


        #set user
        r.user.timestamp = int(time.mktime(gamer.lastActiveTimestamp.timetuple()))
        r.user.id = gamer.public_id
        r.user.name = gamer.name
        r.user.level = gamer.level
        r.user.experience = gamer.experience
        #set backpack
        r.user.backpack.timestamp = int(time.time())
        for i in backpack:
            bp = r.user.backpack.item.add()
            bp.name = i.name
            bp.amount = i.amount


        #TODO: replace with rules update timestamp
        #TODO: always return rules
        if True or int(self.request.get('ts', 0)) < 1339610761:
            #set rules
            r.rules.timestamp = 1339610761
            for (k, v) in RULES.items():
                rule = r.rules.item.add()
                rule.name = str(k)
                rule.value = str(v)


        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
Пример #60
0
    def get(self):
        r = FlowerbedTransfer()

        if not int(self.request.get('amount'), 0):
            return

        fb_id = self.request.get('id')
        amount = int(self.request.get('amount'))

        #get from memcache
        flowerbed = memcache.get(fb_id)
        if not flowerbed:
            flowerbed = GqlQuery('SELECT * FROM Flowerbed WHERE __key__=:1', Key(fb_id)).get()

        ts = time.time()
        if flowerbed:
            fb_flowers = flowerbed.flowers +\
                         int(floor(
                             (ts - time.mktime(flowerbed.timestamp.timetuple())) / RULES['TICK'] *\
                             RULES['FLOWERS_PER_TICK']
                         ))
            user = users.get_current_user()
            gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())
            gamer_hash = hashlib.md5(user.user_id() + SALT).hexdigest()
            bp_flowers = GqlQuery('SELECT * FROM Backpack WHERE ANCESTOR IS :1 AND name=:2', gamer_key, 'flower').get()

            #TODO: check if flowerbed is close to user
            if amount < 0: #from
                if flowerbed.owner != user.user_id():
                    return #not your flowerbed
                if fb_flowers < amount * -1:
                    return #not enough on flowerbed
                #ok, now subtract
                flowerbed.flowers = fb_flowers + amount
                flowerbed.put()
                memcache.set(str(flowerbed.key()), flowerbed)
                bp_flowers.amount -= amount
                bp_flowers.put()
            else: #to
                if bp_flowers.amount < amount:
                    return #not enough in backpack
                if flowerbed.owner == user.user_id():
                    #ok, it's mine
                    flowerbed.flowers = fb_flowers + amount
                    flowerbed.put()
                    memcache.set(str(flowerbed.key()), flowerbed)
                    bp_flowers.amount -= amount
                    bp_flowers.put()
                else: #ok, attack
                    if fb_flowers - amount >= 0:
                        #still the same owner
                        flowerbed.flowers = fb_flowers - amount
                        flowerbed.put()
                        memcache.set(str(flowerbed.key()), flowerbed)
                        bp_flowers.amount -= amount
                        bp_flowers.put()
                    else: #conquer
                        #set lost
                        lost = GqlQuery('SELECT * FROM Possession WHERE ANCESTOR IS :1 AND flowerbed=:2', Key.from_path(kloombaDb.Gamer.kind(), flowerbed.owner), flowerbed).get()
                        lost.lost = True
                        lost.put()
                        #set flowerbed
                        flowerbed.flowers = amount - fb_flowers
                        flowerbed.owner = user.user_id()
                        flowerbed.owner_public_id = gamer_hash
                        flowerbed.put()
                        memcache.set(str(flowerbed.key()), flowerbed)
                        #set backpack
                        bp_flowers.amount -= amount
                        bp_flowers.put()
                        #set conquer
                        possession = GqlQuery('SELECT * FROM Possession WHERE ANCESTOR IS :1 AND flowerbed=:2', gamer_key, flowerbed).get()
                        if not possession:
                            possession = kloombaDb.Possession(parent=gamer_key)
                            possession.flowerbed = flowerbed
                        possession.lost = False
                        possession.put()

            backpack = GqlQuery('SELECT * FROM Backpack WHERE ANCESTOR IS :1', gamer_key).run()

            #set timestamps
            r.flowerbed.timestamp = int(time.time())
            r.backpack.timestamp = int(time.time())

            #set flowerbed
            r.flowerbed.id = str(flowerbed.key())
            r.flowerbed.latitude = int(flowerbed.point.lat * 1000000)
            r.flowerbed.longitude = int(flowerbed.point.lon * 1000000)
            r.flowerbed.owner = flowerbed.owner_public_id
            r.flowerbed.flowers = flowerbed.flowers

            #set backpack
            for i in backpack:
                bp = r.backpack.item.add()
                bp.name = i.name
                bp.amount = i.amount

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())