Пример #1
0
    def InitializeUser(self):
        # Get the owner of the app
        self.userprefs = UserPrefs.all().get()

        if not self.userprefs:
            # Create the owner of the app
            self.userprefs = UserPrefs(user=users.get_current_user())
            self.userprefs.put()
Пример #2
0
    def get(self, album_name=None):
        """Default method called upon entry to the app."""
        # Get the owner of the app
        if not self.userprefs:
            self.userprefs = UserPrefs.all().get()

        if not self.userprefs:
            # Redirect to the admin page
            self.redirect('/admin/')
            return
        
        backend = self.userprefs.GetPhotoBackend()
        
        # Reset template values with every new request.
        self.template_values = {
                'user': self.userprefs,
                'title': self.userprefs.site_title+" gallery",
                'albums': backend.GetFeaturedAlbums(self.userprefs.featured_albums),
                'debug': settings.DEBUG,
        }
        if users.is_current_user_admin():
            self.template_values['logout_url'] = users.create_logout_url('/')

        #album_name = self.request.get('album_name')
        if album_name:
            self.RenderAlbum(album_name)
        else:
            self.RenderHomepage()
Пример #3
0
    def post(self):

        picture = self.request.get('img')
        user = users.get_current_user()
        if user:

            user_id = user.user_id()
            q = UserPrefs.all()
            user_object = q.filter("user_id =",user_id).get()
            if user_object:
#                user_object.pic = db.Blob(picture)
                user_object.pic = picture
                user_object.put()

        # else: 
        #     "you need to login in order to upload a picture"
#        self.redirect(self.request.uri)
        self.redirect("/")
    def get(self):
        site_name = self.request.get('user')
        url, url_linktext = IsUserLoggedIn(self.request.uri)
        
        user = users.get_current_user()
        songList = UserPrefs.all().filter('user ='******'songs': songs,
            'url': url,
            'url_linktext': url_linktext,
        }
        
        path = os.path.join(os.path.dirname(__file__), 'usersongs.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        #check if the song was already liked
        user = users.get_current_user()
        s = Song.get(self.request.get('key'))
        currentUser = UserPrefs.all().filter('user ='******'/')
Пример #6
0
 def __init__(self):
     super(BaseController, self).__init__()
     self.c = {}
     self.c["user"] = users.get_current_user()
     if self.c["user"] is not None:
         self.c["prefs"] = UserPrefs.get_or_create(self.c["user"])
Пример #7
0
class AdminPage(BasePage):
    """Class to handle requests to the admin directory."""


    def RenderAdminPage(self):
        """Renders the admin page"""
        logging.info('RenderAdminPage called')
        
        self.template_values['title'] = self.userprefs.site_title+" gallery admin"
        self.template_values['album_name'] = "admin"
        self.template_values['logout_url'] = users.create_logout_url('/')
        if users.get_current_user() != self.userprefs.user:
            self.template_values['current_user'] = users.get_current_user()
        self.template_values['user'] = self.userprefs
        self.template_values['settings'] = settings
        self.template_values['debug'] = settings.DEBUG
        
        backend = self.userprefs.GetPhotoBackend()
        
        try:
            albums = backend.GetAllAlbums()
        except:
            albums = []
        album_list = []
        featured_albums = self.userprefs.featured_albums
        for a in albums:
            if a['title'] in featured_albums:
                a['featured'] = True
            else:
                a['featured'] = False
            album_list.append(a)
        album_list.append({'id': 'all', 'title': 'all', 'featured': ('all' in featured_albums)})
        
        self.template_values['all_albums'] = album_list
        path = os.path.join(os.path.dirname(__file__), 'admin.html')
        self.response.out.write(template.render(path, self.template_values))

    def InitializeUser(self):
        # Get the owner of the app
        self.userprefs = UserPrefs.all().get()

        if not self.userprefs:
            # Create the owner of the app
            self.userprefs = UserPrefs(user=users.get_current_user())
            self.userprefs.put()

    def get(self):
        """Default method called upon entry to the app."""

        self.InitializeUser()

        # Reset template values with every new request.
        self.template_values = {
        }

        self.RenderAdminPage()
    
    def post(self):
        """Save the admin settings."""
        
        self.InitializeUser()
        
        self.template_values = {
        }
        
        # Get the admin settings and save them
        try:
            if self.request.get('clear-cache'):
                backend = self.userprefs.GetPhotoBackend()
                
                backend.ClearCache()
                
                self.template_values['cache_cleared'] = True
            else:
                self.userprefs.photo_backend = int(self.request.get('backend'))
                self.userprefs.SetUsername(self.request.get('backend-id'))
                
                self.userprefs.site_title = self.request.get('site-title').strip()
                self.userprefs.site_header = self.request.get('site-header').strip()
                
                self.userprefs.thumb_size = int(self.request.get('thumb-size'))
                if self.userprefs.photo_backend == settings.PHOTO_BACKEND_FLICKR:
                    self.userprefs.thumb_size = 75
                elif self.userprefs.photo_backend == settings.PHOTO_BACKEND_PICASA and self.userprefs.thumb_size == 75:
                    self.userprefs.thumb_size = 72
                self.userprefs.thumb_cropped = bool(self.request.get('thumb-cropped'))
                self.userprefs.full_size = int(self.request.get('full-size'))
                self.userprefs.homepage_size = int(self.request.get('homepage-size'))
                
                backend = self.userprefs.GetPhotoBackend()
                
                homepage_album = self.request.get('homepage-album').strip()
                for album in backend.GetAllAlbums():
                    if album['title'] == homepage_album:
                        self.userprefs.homepage_album = homepage_album
                
                featured_albums = self.request.get('featured-album', allow_multiple=True)
                
                self.userprefs.featured_albums = featured_albums
                
                self.userprefs.merchant_id = self.request.get('merchant-id')
                self.userprefs.analytics_id = self.request.get('analytics-id')
                
                self.userprefs.put()
                
                self.template_values['saved'] = True
        except (TypeError, ValueError), e:
            self.template_values['error'] = True
            self.template_values['error_message'] = str(e)
        
        
        self.RenderAdminPage()
Пример #8
0
    def get(self): 
        #timeout = 0.2
        # logging.debug("a cold beer in the sun")
        user = users.get_current_user()
        if user:
            auth_url = users.create_logout_url(self.request.uri)
            auth_url_linktext = "Log Out"

            # storing the user to UserPrefs if we haven't already
            user_id = user.user_id()
#            pic = user.pic() googles innebygde userklasse har ikke pic, det er det din klasse som har.

            q = UserPrefs.all()
            user_object = q.filter("user_id =",user_id).get()

#            pic = user_object.pic() not callable
#            pic = user_object.nickname()

            if not user_object:
                user_object = UserPrefs() #need a new name, like UserObject.

            # else:
            #     if user_object.pic:
                    

            user_object.user_id = user_id
            user_object.nickname = user.nickname()
            user_object.email = user.email()
            user_object.put()

            



#         logging.debug("usr: %s", usr)
#         if False:
#             pass
# #         if usr:
# #             user_id = usr.user_id()
# #             nickname = usr.nickname()
# #             email = usr.email()

# #             auth_url = users.create_logout_url(self.request.uri)
# #             auth_url_linktext = "Logout"

# #             q = UserPrefs.all()
# #             q = q.filter("user_id =",user_id)
# # #            try: # if machine restarts, there will be nothing on localhost 
# #             [u] = q.fetch(1)

# #you need the try except or something similar because the db might be empty (restart machine local).

# #             nick = u.nickname # else, it's "" from above
# #             # except:
# #             #     u = 

# #             keys = u.companies
# #             companies = []
# #             for key in keys:
# #                 company = Company.get_by_id(int(key.id()))
# #                 companies.append(company)

# #             duplicates = []
# #             for company in u.companies:
# #                 if company in duplicates:
# #                     u.companies.remove(company)
# #                 else:
# #                     duplicates.append(company)

#         else:

#             auth_url = users.create_login_url(self.request.uri)
#             auth_url_linktext = "Login"

#             # q = Company.all() #you'll need a 'more' button to display more than these 20
#             # companies = q.fetch(1000) #fetch can't be async for now.
#             nick = ""

#             # u = UserPrefs()
#             # u.user_id = user_id
#             # u.nickname = nickname
#             # u.email = email
#             # u.put()

#         # company = Company()
#         # company.name = "Google Inc"
#         # company.name_lower = "google inc"
#         # company.ticker = "GOOG"
#         # company.ticker_lower = "goog"
#         # company.exchange = "NASDAQ"
#         # company.put()
#         # company = Company()
#         # company.name = "Apple Inc"
#         # company.name_lower = "apple inc"
#         # company.ticker = "AAPL"
#         # company.ticker_lower = "aapl"
#         # company.exchange = "NASDAQ"
#         # company.put()
#         # company = Company()
#         # company.name = "Facebook Inc"
#         # company.name_lower = "facebook inc"
#         # company.ticker = "FB"
#         # company.ticker_lower = "fb"
#         # company.exchange = "NASDAQ"
#         # company.put()

#         # u.companies = []
#         # u.put()


#         #dev only:
#         # c = Company.all().filter("ticker =","IBM").get()
#         # u.companies.remove(c.key())
#         # u.companies = []
#         # u.put()


#         # dupe check for subscribed companies:


#         # if u.companies == []: 
#         #     apple = Company.all().filter("name =","Apple Inc").get()
#         #     if apple == None:
#         #         apple = Company()
#         #         apple.name = "Apple Inc"
#         #         apple.name_lower = "apple inc"
#         #         apple.ticker = "AAPL"
#         #         apple.ticker_lower = "aapl"
#         #         apple.exchange = "NASDAQ"
#         #         apple.exchange_lower = "nasdaq"
#         #         apple.put()
#         #     else:
#         #         u.companies.append(apple.key())

#         #     google = Company.all().filter("name =","Google Inc").get()
#         #     if google == None:
#         #         google = Company()
#         #         google.name = "Google Inc"
#         #         google.name_lower = "google inc"
#         #         google.ticker = "GOOG"
#         #         google.ticker_lower = "goog"
#         #         google.exchange = "NASDAQ"
#         #         google.exchange_lower = "nasdaq"
#         #         google.put()
#         #     else:
#         #         u.companies.append(google.key())

#         #     facebook = Company.all().filter("name =","Facebook Inc").get()
#         #     if facebook == None:
#         #         facebook = Company()
#         #         facebook.name = "Facebook Inc"
#         #         facebook.name_lower = "facebook inc"
#         #         facebook.ticker = "FB"
#         #         facebook.ticker_lower = "fb"
#         #         facebook.exchange = "NASDAQ"
#         #         facebook.exchange_lower = "nasdaq"
#         #         facebook.put()
#         #     else:
#         #         u.companies.append(facebook.key())

#         #     u.put()

#         # company_names = []
#         # for company_key in u.companies:
#         #     company = Company.get_by_id(company_key.id())
#         #     # try: # in case there are zombie ids for that user:
#         #     company_names.append(company.name)
#         #     # except:
#         #     #     continue

# # #         # displaying all companies for debugging only:



# #         comp_keys_names = []
# #         for company in companies:




# # # her sjekker du en variabel som returneres av menyvalget. defaulten her er også week. 
# # # resultatet bestemmer hvilken ctr som blir ctr; if scope == "day": (pos_ctr = pos_ctr_day, neg_ctr = neg_ctr_day).


# #             # articles = [article for article in company.articles if article.clean]
# #             # [pos_rat,neg_rat] = utils.sentiment_count(articles)
# #             if company.pos_ctr > 0:
# #                 pos_arrow = "↑ "
# #                 pos_str = str(company.pos_ctr)
# #             else:
# #                 pos_arrow = ""
# #                 pos_str = ""
# #             if company.neg_ctr > 0:
# #                 neg_arrow = "↓ "
# #                 neg_str = str(company.neg_ctr)
# #             else:
# #                 neg_arrow = ""
# #                 neg_str = ""
# #             comp_keys_names.append([company.key(), company.ticker, pos_arrow, pos_str, neg_arrow, neg_str])

# # #         ##############db.delete(companies) don't do this either!

# # #         # you need a check here, to see what companies are already
# # #         # user companies!
# #         free_companies = ["Apple Inc", "Google Inc", "Facebook Inc"]

#         # for company in companies:
#         #     if company.ticker == "GE":
#         #         # company.name = "International Business Machines Corp."
#         #         # company.name_lower = "international business machines corp."
#         #         # company.ticker = "IBM"
#         #         # company.ticker_lower = "ibm"
#         #         company.exchange = "NYSE"
#         #         company.put()

# #             if comp.name in free_companies and comp.key() not in u.companies:
# #                 u.companies.append(comp.key())
# # # #                comp.user = u #why can't this be usr? usr is a UserPrefs object, isn't it???? No, it's a in-built user object.


# #                company.put()


# #                 u.put()

# #         q = article_objects = Article.all() # should be articles = company.articlestod
# #         q = q.order("-datetime")
# #         q = q.filter("clean =",True)
# #         article_objects = q.fetch(100)
# # #        article_objects = q # debug only
# #         ####db.delete(article_objects) stop doing this - delete attributes instead, run scripts to add new attributes
#         # keys_names = zip(u.companies,company_names)




#       #   self.response.out.write("""
#       #     <form action="/sign?%s" enctype="multipart/form-data" method="post">
#       #       <div><textarea name="content" rows="3" cols="60"></textarea></div>
#       #       <div><input type="submit" value="Sign Guestbook"></div>
#       #     </form>
#       #     <hr>
#       #     <form>Guestbook name: <input value="%s" name="guestbook_name">
#       #     <div><label>Avatar:</label></div>
#       #     <div><input type="file" name="img"/></div>
#       #     <input type="submit" value="switch"></form>
#       #   </body>
#       # </html>""" % (urllib2.urlencode({'guestbook_name': guestbook_name}),
#       #               cgi.escape(guestbook_name)))





            template_values = {
#            'nick' : nick,
#            'pic' : user_object.pic,
#            'pic' : user_object.key().id(),
                'user_key' : user_object.key(),
                'auth_url' : auth_url,
                'auth_url_linktext' : auth_url_linktext,
            }

        # if no user:
        else:
            auth_url = users.create_login_url(self.request.uri)
            auth_url_linktext = "Login"

            template_values = {
                'auth_url' : auth_url,
                'auth_url_linktext' : auth_url_linktext,
            }

        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))
Пример #9
0
  def get(self):
    user = self.current_user
    
    if user:
      userprefs = get_userprefs(user["id"])
      if not userprefs.acknowledged_terms:
        self.redirect('/profile?terms=1')
        return
    else:
      userprefs = None
    
    locations = dict()
    friends_count = 0
    friends_count_2 = 0
    if user:
      graph = facebook.GraphAPI(version=2.1,access_token=user["access_token"])

      friends = get_friends(graph)
      friends[:] = [friend for friend in friends if is_app_user(str(friend['id']))]
      for profile in friends:
        friends_count += 1
        friend_prefs = UserPrefs.get_by_key_name(str(profile['id']))
        location_name = friend_prefs.location_name
        location_lng = friend_prefs.location_lng
        location_lat = friend_prefs.location_lat
        location_id = (location_lat,location_lng)
        if (0,0) != location_id:
          if location_id not in locations:
            locations[location_id] = dict()
            locations[location_id]['name'] = location_name
            locations[location_id]['count'] = 1
            locations[location_id]['count_2'] = 0
            locations[location_id]['longitude'] = location_lng
            locations[location_id]['latitude'] = location_lat
          else:
            locations[location_id]['count'] += 1
        
        friend_user = User.get_by_key_name(str(profile['id']))
        if friend_user.offline_token_created + timedelta(2*365/12) < datetime.utcnow():
          logging.info('Friend ' + str(profile['id']) + ' access token expired') 
          continue
        graph_friend = facebook.GraphAPI(version=2.1,access_token=friend_user.offline_token)

        friends_2 = get_friends(graph_friend)
        friends_2[:] = [friend for friend in friends_2 if is_app_user(str(friend['id']))]
        friends_1_2_with_out_mutual = remove_profile_by_id(friends_2, [user['id']])
 
        for profile_2 in friends_1_2_with_out_mutual:
          # ignore mutual friend
          # FIXME inefficient, assumes 1st degree list is shorter than 2nd
          if any(f['id'] == profile_2['id'] for f in friends):
            continue
          # ignore "me"
          if str(profile_2['id']) == str(user['id']):
            continue
          friends_count_2 += 1
          friend_prefs_2 = UserPrefs.get_by_key_name(str(profile_2['id']))
          location_name = friend_prefs_2.location_name
          location_lng = friend_prefs_2.location_lng
          location_lat = friend_prefs_2.location_lat
          location_id = (location_lat,location_lng)
          if location_id not in locations:
            locations[location_id] = dict()
            locations[location_id]['name'] = location_name
            locations[location_id]['count'] = 0
            locations[location_id]['count_2'] = 1
            locations[location_id]['longitude'] = location_lng
            locations[location_id]['latitude'] = location_lat
          else:
            locations[location_id]['count_2'] += 1
    
    locations_list = sorted(locations.items(), key=lambda l: l[1]['name'])

    template = template_env.get_template('home.html')
    context = {
      'facebook_app_id': FACEBOOK_APP_ID,
      'user': user,
      'userprefs': userprefs,
      'locations': locations_list,
      'friends_count': friends_count,
      'friends_count_2': friends_count_2,
      'google_maps_api_key': GOOGLE_MAPS_API_KEY,
      'markers': json.encode(locations_list),
    }
    self.response.out.write(template.render(context))
Пример #10
0
def is_local(uid,latlng):
  userprefs = UserPrefs.get_by_key_name(uid)
  if not userprefs:
    return False
  return userprefs.location_lat == latlng[0] and userprefs.location_lng == latlng[1]
Пример #11
0
def is_app_user(uid):
  if User.get_by_key_name(uid) and UserPrefs.get_by_key_name(uid):
    return True
  else:
    return False