def upload(web, args=None): """ Upload a new book or update an old book info. If it's a new book, all followers are notified by email. Note: only first author can modify an existing book (owner). """ web.require_author() # if not web.logged_in: # raise Exception('Not login') paramkeys = ['bkid','title','status','logofile','intro','toc','notes','authors','zine','height','quests'] bkid,title,status,logo,intro,toc,notes,authors,zine,height,quests = web.get_params(paramkeys) newbook = False if bkid: bk = SuiBook.seek_by_id(bkid) if not bk: logging.warning('book %s not found'%bkid) web.redirect_with_msg('Invalid Book ID','book') return if web.user.key().name() != bk.authors[0]: web.redirect_with_msg('No permission','book') return else: madekey = db.Key.from_path('SuiBook',1) bkid = db.allocate_ids(madekey,1)[0] bk = SuiBook(key=db.Key.from_path('SuiBook',bkid)) bk.authors = [web.user.key().name()] if zine and zine!='none': bk.zine = zine bk newbook = True if title: bk.title = title if status: bk.status = status genres = web.request.get('genre', allow_multiple=True) if genres: bk.genre = list(set(genres)) if intro: bk.intro = join_lines(intro) if toc: bk.toc = join_lines(toc,'ul') if notes: bk.notes = join_lines(notes) if quests: bk.quests = validate_quests(quests) if height: try: bk.height = int(height) except: pass # if authors: # import re # aus = [s for s in re.split(r'[ ,;]',authors) if s] # aus = [s.key().name() for s in SuiAuthor.get_by_key_name(aus) if s] # if aus: # bk.authors = list(set(bk.authors + aus)) dbs = [bk] if logo: logofile = web.request.POST.get('logofile').filename #logging.debug('-=------- save logofile %s'%logofile) x = logofile.rfind('.') if x < 0: web.fail('Unknown image file') return ext = logofile[x+1:].lower() if ext in ['jpg','png']: from google.appengine.api import images m = images.Image(logo) w = h = 240 if m.width > 240 or m.height > 240: m.resize(240,240) w = m.width h = m.height if ext == 'png': oenc = images.PNG else: oenc = images.JPEG m = m.execute_transforms(oenc) else: m = logo if newbook: ms = MediaStore(key_name='bk_%s'%bkid) else: ms = MediaStore.get_by_key_name('bk_%s'%bkid) if ms: bk.version += 1 ms.decache() else: ms = MediaStore(key_name='bk_%s'%bkid) ms.book = '%s'%bkid ms.width = w ms.height = h ms.usage = 'BK' ms.stream = db.Blob(m) ms.format = ext dbs.append(ms) bk.version += 1 me = SuiAuthor.get_by_key_name(web.user.key().name()) if not me: logging.warning('Book editor is not in SuiAuthor %s'%web.user.key().name()) web.redirect_with_msg('You are not a registered author','book') return me.add_book(bk) dbs.append(me) try: db.put(dbs) me.recache() bk.decache_for_newbook() helper.to_cache('%s'%bkid, bk) if newbook: SuiLog.log_newbook(me,bkid) taskqueue.add(url='/task/genre/add_book',params={'genre':','.join(bk.genre),'bkid':bkid}) taskqueue.add(url='/task/feed/add_book',params={'uid':me.key().name(),'uname':me.name,'bkid':bkid,'title':bk.title,'intro':intro or ''}) #bdy='Good news! %s published a new book "%s". Visit <a href="http://suicomics.appspot.com">Suinova Comics</a> to check it out.'%(me.name,bk.title) #TODO: notify my fans about the new book #helper.notify_followers(me,'New book by %s'%me.name,bdy) #logging.info('followers notified if any') web.redirect('/book/'+bkid) except Exception,e: logging.error(e) web.redirect_with_msg('Error saving your item, retry later.','book')
def login(self, uid, access_token): """ Login routine. From FacebookRequest: login(facebook_uid """ self.sns = 'fb' ukey = '%s_%s' % (self.sns, uid) u = helper.from_cache(ukey) if not u: u = helper.get_user_by_key(ukey, False) #memcache=False if not u: graph = facebook.GraphAPI(access_token) profile = graph.get_object('me') u = helper.create_user(ukey, profile['name'], profile.get('email', None), False) #save=False if not u: logging.error( 'FacebookRequest.login: helper.create_user failed') self.redirect_with_msg( 'Server in maintenance, please try later, thank you.') self.get = self.post = (lambda *args: None) return u.access_token = access_token u.save() logging.debug('FacebookRequest.login: New User %s saved' % ukey) else: now = datetime.utcnow() u._cache_time = now if helper.to_cache( ukey, u, helper.PLAYER_CACHE_SECS ): #2 hours, if memcache fails, do not task/dau or send_email # if u.lastime.day != now.day or u.lastime.month != now.month: # taskqueue.add(url='/task/dau',params={'usr':ukey,'act':'login'}) taskqueue.add(url='/task/dau', params={ 'usr': ukey, 'act': 'login' }) if ukey not in [ 'fb_669391906', 'fb_1464710918', 'fb_1842536962', 'fb_1831016858' ]: helper.send_email( 'Login SuiComics: %s(%s) @ %s' % (u.name, ukey, now), 'OK') else: helper.send_email( 'Login SuiComics: %s(%s) @ %s' % (u.name, ukey, now), 'OK - to remove this') else: #got user from memcache if u.access_token != access_token: u.access_token = access_token u.save() logging.debug( 'FacebookRequest.login: access_token updated while %s still in memcache' % ukey) elif hasattr(u, '_cache_time'): if (datetime.utcnow() - u._cache_time).seconds >= 3600: u._cache_time = datetime.utcnow() helper.to_cache(ukey, u, helper.PLAYER_CACHE_SECS) if self.request.headers.get('User-Agent', '').find('MSIE') >= 0: #logging.debug('addHeader P3P for MSIE') #self.response.headers.add_header('P3P','CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"') self.response.headers.add_header('P3P', 'CP="SuiComics"') args = get_session_from_cookie(self.request.cookies) if not args or args['uid'] != ukey: put_cookie(self.response.headers, ukey, u.token, self.sns) self.user = u self.tempvars = { 'user': u, 'sns': 'fb', 'login': True, 'uname': u.name, 'onFacebook': True } if self.request.get('ref') == 'bookmarks': c = self.request.get('count') if c != '0': helper.clear_fb_count(uid)
def initialize(self, request, response): """ Authenticate through Google account. """ webapp.RequestHandler.initialize(self, request, response) from google.appengine.api import users user = users.get_current_user() if not user: logging.debug( 'GoogleRequest.initialize: not login, redirect to /gg') self.redirect(users.create_login_url("/gg/home")) self.get = (lambda *args: None) self.post = (lambda *args: None) else: #user logged in google account,check our cookie sns = 'gg' #Google: how to make use of GMail contact, chat etc? via OAuth uid = '%s_%s' % (sns, user.user_id()) logging.debug( 'GoogleRequest.initialize: %s visit via Google, try login' % uid) su = helper.from_cache(uid) if not su: su = helper.get_user_by_key(uid, False) #no memcache if su is None: logging.debug( 'GoogleRequest.initialize: New user, try create') em = user.email() name = em[:em.find('@')] su = helper.create_user(uid, name, em) #auto cached if successful if su is None: logging.error( 'GoogleRequest.initialize: create_user(%s,%s,%s) failed' % (uid, name, em)) self.response.out.write( 'Server in maintenance, please come back later. Thank you.' ) self.get = self.post = ( lambda *args: None) #stop calling request handler return else: logging.debug( 'GoogleRequest.initialize: new session today, try cache' ) su._cache_time = datetime.utcnow() if helper.to_cache(uid, su, helper.PLAYER_CACHE_SECS): logging.debug( 'GoogleRequest.initialize: Memcached, task dau and send email to admin' ) taskqueue.add(url='/task/dau', params={ 'usr': uid, 'act': 'login' }) #if uid not in ['gg_109722387073140662444','gg_108772542023352813713']: helper.send_email( 'Login SuiComics: %s(%s) @ %s' % (su.name, uid, datetime.utcnow()), 'OK') else: #in memcache logging.debug('GoogleRequest.initialize: in memcache, revisit') if hasattr(su, '_cache_time'): if (datetime.utcnow() - su._cache_time).seconds >= 3600: su._cache_time = datetime.utcnow() helper.to_cache(uid, su, helper.PLAYER_CACHE_SECS) self.tempvars = { 'user': su, 'sns': 'gg', 'login': True, 'uname': su.name, 'onFacebook': False } args = get_session_from_cookie(self.request.cookies) if not args: put_cookie(self.response.headers, uid, su.token, sns) #a generated random token else: self.tempvars.update(args) #['sns','uid','token'] self.sns = sns self.user = su
def upload(web, args=None): """ Upload a new book or update an old book info. If it's a new book, all followers are notified by email. Note: only first author can modify an existing book (owner). """ web.require_author() # if not web.logged_in: # raise Exception('Not login') paramkeys = [ 'bkid', 'title', 'status', 'logofile', 'intro', 'toc', 'notes', 'authors', 'zine', 'height', 'quests' ] bkid, title, status, logo, intro, toc, notes, authors, zine, height, quests = web.get_params( paramkeys) newbook = False if bkid: bk = SuiBook.seek_by_id(bkid) if not bk: logging.warning('book %s not found' % bkid) web.redirect_with_msg('Invalid Book ID', 'book') return if web.user.key().name() != bk.authors[0]: web.redirect_with_msg('No permission', 'book') return else: madekey = db.Key.from_path('SuiBook', 1) bkid = db.allocate_ids(madekey, 1)[0] bk = SuiBook(key=db.Key.from_path('SuiBook', bkid)) bk.authors = [web.user.key().name()] if zine and zine != 'none': bk.zine = zine bk newbook = True if title: bk.title = title if status: bk.status = status genres = web.request.get('genre', allow_multiple=True) if genres: bk.genre = list(set(genres)) if intro: bk.intro = join_lines(intro) if toc: bk.toc = join_lines(toc, 'ul') if notes: bk.notes = join_lines(notes) if quests: bk.quests = validate_quests(quests) if height: try: bk.height = int(height) except: pass # if authors: # import re # aus = [s for s in re.split(r'[ ,;]',authors) if s] # aus = [s.key().name() for s in SuiAuthor.get_by_key_name(aus) if s] # if aus: # bk.authors = list(set(bk.authors + aus)) dbs = [bk] if logo: logofile = web.request.POST.get('logofile').filename #logging.debug('-=------- save logofile %s'%logofile) x = logofile.rfind('.') if x < 0: web.fail('Unknown image file') return ext = logofile[x + 1:].lower() if ext in ['jpg', 'png']: from google.appengine.api import images m = images.Image(logo) w = h = 240 if m.width > 240 or m.height > 240: m.resize(240, 240) w = m.width h = m.height if ext == 'png': oenc = images.PNG else: oenc = images.JPEG m = m.execute_transforms(oenc) else: m = logo if newbook: ms = MediaStore(key_name='bk_%s' % bkid) else: ms = MediaStore.get_by_key_name('bk_%s' % bkid) if ms: bk.version += 1 ms.decache() else: ms = MediaStore(key_name='bk_%s' % bkid) ms.book = '%s' % bkid ms.width = w ms.height = h ms.usage = 'BK' ms.stream = db.Blob(m) ms.format = ext dbs.append(ms) bk.version += 1 me = SuiAuthor.get_by_key_name(web.user.key().name()) if not me: logging.warning('Book editor is not in SuiAuthor %s' % web.user.key().name()) web.redirect_with_msg('You are not a registered author', 'book') return me.add_book(bk) dbs.append(me) try: db.put(dbs) me.recache() bk.decache_for_newbook() helper.to_cache('%s' % bkid, bk) if newbook: SuiLog.log_newbook(me, bkid) taskqueue.add(url='/task/genre/add_book', params={ 'genre': ','.join(bk.genre), 'bkid': bkid }) taskqueue.add(url='/task/feed/add_book', params={ 'uid': me.key().name(), 'uname': me.name, 'bkid': bkid, 'title': bk.title, 'intro': intro or '' }) #bdy='Good news! %s published a new book "%s". Visit <a href="http://suicomics.appspot.com">Suinova Comics</a> to check it out.'%(me.name,bk.title) #TODO: notify my fans about the new book #helper.notify_followers(me,'New book by %s'%me.name,bdy) #logging.info('followers notified if any') web.redirect('/book/' + bkid) except Exception, e: logging.error(e) web.redirect_with_msg('Error saving your item, retry later.', 'book')