Ejemplo n.º 1
0
	def create( self ):
		content = self.request.get( 'content' );

		# content がなかったらエラー
		if content == "":
			message = "parameter missing"
			logging.warn( message )
			out = { "meta": functions.createMetaData( status="fail", code=400, message=message, method_name="showPosts" ) };
			self.response.out.write( json.encode(out) )
			return

		# 保存
		post = models.Post()
		post.content = content
		if self.user:
			post.user_key = self.user.key
		post.created_at = int(time())
		post.put();

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="createPost" ),
			"response": {
				"posts":[
					post.toDict(),
				],
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 2
0
	def create( self ):
		photo = self.request.get( "photo", None )

		# photo がなかったらエラー
		if photo is None:
			message = "parameter missing"
			logging.warn( message )
			out = { "meta": functions.createMetaData( status="fail", code=400, message=message, method_name="createPhoto" ) };
			self.response.out.write( json.encode(out) )
			return

		logging.info( "サイズは%d KB"%( len(photo)/1000 ) )

		# 保存
		entity = models.Photo()
		if self.isBase64( photo ) == True:
			logging.info( "Flashから渡ってきたので base64decode します" )
			photo_bin = base64.b64decode( photo )
			entity.setBlob( photo_bin )
		else:
			logging.info( "HTMLフォームから渡って来ました" )
			entity.setBlob( photo )
		entity.user_key = self.user.key if self.user else None
		entity.put();

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="createPhoto" ),
			"response": {
				"photos":[
					entity.toDict(),
				],
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 3
0
    def show(self, class_name):
        id = self.request.get("id", None)
        if id is None:
            out = {
                "meta": functions.createMetaData(
                    status="fail", code=400, method_name="showObjects", message="parameter missing"
                )
            }
            self.response.out.write(json.encode(out))
            return

            # 文字列からモデルクラス取得
        classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name)
        klass = webapp2.import_string(classPath_str)
        obj = klass.get_by_id(int(id))

        if obj and obj.is_deleted == False:
            out = {
                "meta": functions.createMetaData(status="ok", code=200, method_name="showObjects"),
                "response": {"objects": [obj.toDict(full=True)]},
            }
        else:
            out = {
                "meta": functions.createMetaData(
                    status="fail", code=400, method_name="showObjects", message="object not found"
                )
            }

        self.response.out.write(json.encode(out))
Ejemplo n.º 4
0
	def login( self ):
		login = self.request.get( 'login', None );
		password = self.request.get( 'password', None );
		logging.info( "login=%s password=%s" % (login,password) );

		# パラメータチェック
		if (login is None) or (password is None):
			out = { "meta": functions.createMetaData( status="fail", code=400, cc_code=1000, message="login and password required") };
			logging.error( "login and password required" );
			self.response.out.write( json.encode(out) )
			return

		# ログインしようとしているユーザーがメアドを verify 済みかチェック
		auth_id = "own:"+ login
		m = self.user_model
		q = m.query( m.auth_ids==auth_id, m.verified==True )
		result = q.get();
		if result is None:
			out = { "meta": functions.createMetaData( status="fail", code=400, cc_code=1000, message="ユーザーが存在しないか、メールアドレス認証が完了していません") };
			logging.error( "ユーザーが存在しないか、メールアドレス認証が完了していません" );
			self.response.out.write( json.encode(out) )
			return

		user = None
		userInfo = self.auth.get_user_by_password( "own:"+ login, password, True, True, True )

		# 2013/01/06 以前のバージョンは頭に「own:」がついてなかったので、それにも対応。	
		if userInfo is None:
			logging.info( "2013/01/06 以前のバージョン方式でログインします" );
			userInfo = self.auth.get_user_by_password( login, password, True, True, True )

		if userInfo is None:
			# ログイン失敗
			logging.error( "Invalid email/username or password." );
			out = {
				"meta": functions.createMetaData(
					status="fail", code=401, cc_code=1000, message="Invalid email/username or password."
				),
			};
			self.response.out.write( json.encode(out) )
			return
		
		# ログイン成功
		user = User.get_by_id( userInfo["user_id"] )
		sessionId = self.serialize_user_token( auth_info=userInfo )
		out = {
			"meta": {
				"status": "ok",
				"code": 200,
				"method_name": "loginUser",
				"session_id": sessionId,
			},
			"response":{
				"users": [
					user.toDict( full=True ),
				],
			},
		};	
		self.response.out.write( json.encode(out) )
Ejemplo n.º 5
0
	def create( self ):
		target_model = self.request.get( 'target_model', None );
		target_id = self.request.get( 'target_id', None );

		# パラメータが足りなかったらエラー
		if target_model is None or target_id is None:
			message = "parameter missing"
			logging.warn( message );
			out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createReport", message=message )};
			self.response.out.write( json.encode(out) )
			return

		# 文字列からターゲットのモデルクラス取得
		classPath_str = "models."+ target_model.capitalize()
		klass = webapp2.import_string( classPath_str )
		target_obj = klass.get_by_id( int(target_id) );

		# ターゲットオブジェクトがなければエラー	
		if target_obj is None:
			message = "target object not found"
			logging.warn( message );
			out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createReport", message=message )};
			self.response.out.write( json.encode(out) )
			return

		# 保存
		entity = models.Report()
		entity.target_key = target_obj.key
		entity.user_key = self.user.key if self.user else None
		entity.put();

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="createReport" ),
			"response": {
				"reports":[
					entity.toDict(),
				],
			},
		};
		self.response.out.write( json.encode(out) )

		# 管理者にメール
		sender_address = "*****@*****.**"
		recipient = "*****@*****.**"
		subject = "通報を確認してください。"
		targetKey_str = str( target_obj.key.id() )
		modelName = target_model.capitalize().encode()
		gql = "SELECT * FROM "+ modelName +" where __key__ = Key( '"+ modelName +"', "+ targetKey_str +" )"

		body = """
通報がありました。
ターゲットのkeyは %(targetKey_str)s です

検索用 GQL は以下のとおりです。
%(gql)s

""" % locals()
		mail.send_mail( sender_address, recipient, subject, body )
Ejemplo n.º 6
0
	def create( self ):
		target_model = self.request.get( 'target_model', None );
		target_id = self.request.get( 'target_id', None );

		# パラメータが足りなかったらエラー
		if target_model is None or target_id is None:
			message = "parameter missing"
			logging.warn( message );
			out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createLike", message=message )};
			self.response.out.write( json.encode(out) )
			return

		# ゲストならエラー
		if self.user is None:
			message = "login required"
			logging.warn( message );
			out = {"meta": functions.createMetaData( status="fail", code=401, method_name="createLike", message=message )};
			self.response.out.write( json.encode(out) )
			return

		# 文字列からターゲットのモデルクラス取得
		classPath_str = "models."+ target_model.capitalize()
		klass = webapp2.import_string( classPath_str )
		target_obj = klass.get_by_id( int(target_id) );

		# ターゲットオブジェクトがなければエラー	
		if target_obj is None:
			message = "target object not found"
			logging.warn( message );
			out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createLike", message=message )};
			self.response.out.write( json.encode(out) )
			return

		# 重複チェック
		query = models.Like.query( models.Like.target_key==target_obj.key, models.Like.user_key==self.user.key, models.Like.is_deleted==False )
		if query.get():
			message = "already liked"
			logging.warn( message );
			out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createLike", message=message )};
			self.response.out.write( json.encode(out) )
			return			

		# 保存
		entity = models.Like()
		entity.target_key = target_obj.key
		entity.user_key = self.user.key
		entity.put();

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="createLike" ),
			"response": {
				"likes":[
					entity.toDict(),
				],
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 7
0
	def create( self ):
		target_model = self.request.get( 'target_model', None );
		target_id = self.request.get( 'target_id', None );
		content = self.request.get( 'content', None );
		rating = self.request.get( 'rating', None );


		# パラメータが足りなかったらエラー
		if content is None or target_model is None or target_id is None:
			message = "parameter missing"
			logging.error( message )
			out = {
				"meta": functions.createMetaData( status="fail", code=400, method_name="createComment", message=message ),
			};
			self.response.out.write( json.encode(out) )
			return

		# 文字列からモデルクラス取得
		classPath_str = "models."+ target_model.capitalize()
		klass = webapp2.import_string( classPath_str )
		target_obj = klass.get_by_id( int(target_id) );


		# ターゲットオブジェクトがなければエラー	
		if target_obj is None:
			message = target_model +"#"+ target_id +" is not found"
			logging.error( message )
			out = {
				"meta": functions.createMetaData( status="fail", code=400, method_name="createComment", message=message ),
			};
			self.response.out.write( json.encode(out) )
			return

		# 保存
		comment = models.Comment()
		comment.content = content
		comment.rating = rating
		comment.target_key = target_obj.key
		if self.user:
			comment.user_key = self.user.key
		comment.put();

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="createComment" ),
			"response": {
				"comments":[
					comment.toDict(),
				],
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 8
0
	def subscribe( self ):
		device_token = self.request.get( 'device_token', None );
		type = self.request.get( 'type', None ); # ios or android

		# パラメータが足りなかったらエラー
		if device_token is None or type is None:
			functions.printError( "parameter missing" )
			return

		# ios の場合は urbanairship に登録する。
		# android の場合はクライアント側のライブラリが
		# urbanairship への登録までやってくれているので何もしない。
		if type == "ios":
			from openfish.libs import urbanairship
			import config
			airship = urbanairship.Airship( config.URBANAIRSHIP_APP_KEY, config.URBANAIRSHIP_MASTER_SECRET )# 2つ目は master secret
			airship.register( device_token, alias=self.user.ua_alias )

		# user のプロパティとして保存
		self.user.device_token = device_token
		self.user.put()

		logging.info( "%s の device_token を %s として登録しました" % ( str(self.user.key), str(device_token) ) )

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="subscribePushNotification" ),
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 9
0
	def train( self ):
		content = self.request.get( "content", None )
		categories = json.decode( self.request.get( "categories", "[]" ) )
		if content is None or len(categories)==0:
			message = "parameter is missing"
			logging.error( message )
			out = {"meta": functions.createMetaData( status="fail", code=200, method_name="bayesTrain", message=message )};
			self.response.out.write( json.encode(out) )
			return

		nb = openfish.libs.naivebayes.naivebayes.NaiveBayes()
		for categoryName in categories:
			nb.train( content, str(categoryName) )

		out = {"meta": functions.createMetaData( status="ok", code=200, method_name="bayesTrain" )};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 10
0
	def search( self ):
		page = self.request.get( "page", 1 );
		per_page = self.request.get( "per_page", 10 );
		latitude = self.request.get( "latitude" );
		longitude = self.request.get( "longitude" );
		distance = self.request.get( "distance" );

		# 出力ひな形作成
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="searchPlaces" ),
			"response": {
				"places":[],
			},
		};

		
		if latitude and longitude and distance:
			entities = models.Place.searchByLocation( latitude, longitude, distance, per_page );
			# 出力データに追加
			for entity in entities:
				out["response"]["places"].append( entity.toDict() )
		else:
			# 普通にクエリ
			query = models.Place.query();
			for result in query.iter():
				out["response"]["places"].append( result.toDict() )


		self.response.out.write( json.encode(out) )
Ejemplo n.º 11
0
    def create(self, class_name):
        logging.info(self.request.arguments())
        if self.checkModel(class_name) == False:
            return

        if models.BlackList.checkBanned():
            return

            # 文字列からモデルクラス、エンティティ取得
        classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name)
        klass = webapp2.import_string(classPath_str)

        # マスタデータかどうかチェック & マスターデータだったら管理者以外は作成できないように。
        if klass.isMasterData == True and users.is_current_user_admin() == False:
            logging.warn("管理者以外がマスタデータを作成しようとしました")
            return False

            # 保存開始
        entity = klass()
        self.setPropertyFromRequestData(entity, self.request)
        entity.put()

        # 出力
        out = {
            "meta": functions.createMetaData(status="ok", code=200, method_name="createCustomObject"),
            "response": {"objects": [entity.toDict()]},
        }
        self.response.out.write(json.encode(out))
Ejemplo n.º 12
0
	def confirm_user( self ):
		user = None
 
		user_id = self.request.get( 'user_id', None );
		signup_token = self.request.get( 'signup_token', None );
		verification_type = self.request.get( 'type', None );

		# it should be something more concise like
		# self.auth.get_user_by_token(user_id, signup_token
		# unfortunately the auth interface does not (yet) allow to manipulate
		# signup tokens concisely
		user, ts = self.user_model.get_by_auth_token( int(user_id), signup_token, 'signup' )
 
		# store user data in the session
		self.auth.set_session( self.auth.store.user_to_dict(user), remember=True )
 
		if not user:
			out = {
				"meta":{
					"status":"fail",
					"message": 'Could not find any user with id "%s" signup token "%s"' % ( user_id, signup_token ),
				},
			};
			self.response.out.write( json.encode(out) )
			return
 
		if verification_type == 'v':
			# remove signup token, we don't want users to come back with an old link
			self.user_model.delete_signup_token( user.get_id(), signup_token )
 
			if not user.verified:
				user.verified = True
				user.put()

			out = { "meta": functions.createMetaData( status="ok", message="User email address has been verified." ) };
			self.response.out.write( json.encode(out) )
			return
		elif verification_type == 'p':
			out = { "meta": functions.createMetaData( status="fail", message="パスワードリセットはまだ実装されていません" ) };
			self.response.out.write( json.encode(out) )
			return
		else:
			out = { "meta": functions.createMetaData( status="fail", message="verification type not supported" ) };
			self.response.out.write( json.encode(out) )
			return
Ejemplo n.º 13
0
	def show( self ):
		post_id = self.request.get( 'post_id' );
		post = models.Post.get_by_id( int(post_id) );

		if post:
			out = {
				"meta": functions.createMetaData( status="ok", code=200, method_name="showPosts" ),
				"response": {
					"posts": [
						post.toDict(),
					],
				},
			};
		else:
			out = {
				"meta": functions.createMetaData( status="fail", code=400, message="hoge", method_name="showPosts" ),
			};
		
		self.response.out.write( json.encode(out) )
Ejemplo n.º 14
0
 def checkModel(self, class_name):
     standardModelNames_array = ["user", "post", "place", "blacklist", "report", "like", "comment"]
     if class_name.lower() in standardModelNames_array:
         message = class_name + " はこのAPIを通して操作できません"
         logging.warn(message)
         out = {"meta": functions.createMetaData(status="fail", code=401, message=message)}
         self.response.out.write(json.encode(out))
         return False
     else:
         return True
Ejemplo n.º 15
0
	def show( self ):
		user_id = self.request.get( 'user_id' );
		user = models.User.get_by_id( int(user_id) )

		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="showUser" ),
			"response":{
				"users": [
					user.toDict(),
				],
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 16
0
	def create( self ):
		file = self.request.get( 'file', None );
		name = self.request.get( 'name', "untitled" );

		# パラメータが足りなかったらエラー
		if file is None or name is None:
			message = "parameter missing"
			logging.warn( message );
			out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createFile", message=message )};
			self.response.out.write( json.encode(out) )
			return


		# ファイルを BlobStore に保存
		file_name = files.blobstore.create( mime_type='application/octet-stream' )# Create the file
		# Open the file and write to it
		with files.open( file_name, 'a' ) as f:
			f.write( file )
		files.finalize( file_name ) # Finalize the file. Do this before attempting to read it.
		blob_key = files.blobstore.get_blob_key( file_name ) # Get the file's blob key


		# 保存
		entity = models.File()
		entity.blob_key = blob_key
		entity.name = name
		entity.put();

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="createFile" ),
			"response": {
				"files":[
					entity.toDict(),
				],
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 17
0
	def email( self ):
		recipients = self.request.get( 'recipients', None );
		body = self.request.get( 'body', None );

		# パラメータが足りなかったらエラー
		if recipients is None or body is None:
			message = "parameter missing"
			logging.warn( message );
			out = {"meta": functions.createMetaData( status="fail", code=400, method_name="email", message=message )};
			self.response.out.write( json.encode(out) )
			return

		sender_address = "dd RemoteDraw Support <*****@*****.**>"
		subject = "Confirm your registration"
		body = "hgoehgoehog"
		# mail.send_mail( sender_address, "*****@*****.**", subject, body )


		# 出力
		out = {
			"meta": functions.createMetaData( status="email function is not implemented", code=200, method_name="email" ),
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 18
0
    def query(self, class_name):
        if self.checkModel(class_name) == False:
            return

        page = self.request.get("page", 1)
        per_page = self.request.get("per_page", 10)
        limit = self.request.get("limit", 100)
        skip = self.request.get("skip", 0)
        where = self.request.get("where")
        order = self.request.get("order")
        mine = self.request.get("mine", None)
        response_json_depth = self.request.get("response_json_depth", 3)

        # 出力ひな形作成
        out = {
            "meta": functions.createMetaData(status="ok", code=200, method_name="queryCustomObjects"),
            "response": {"objects": []},
        }

        # 文字列からモデルクラス取得
        classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name)
        klass = webapp2.import_string(classPath_str)

        gql_str = ""
        if where:
            gql_str = "WHERE " + where + " AND"
        else:
            gql_str = "WHERE"
        gql_str += " is_deleted=False"

        # モデルに is_public プロパティがあれば、それを暗黙で考慮する
        if hasattr(klass, "is_public") == True:
            gql_str += " AND is_public=True"

            # mine フラグがあったら自分の投稿したエントリーをフィルタ
        if (mine == "true") and (self.user is not None):
            gql_str += " AND user_key=" + self.user.key.id()

        if order:
            gql_str = gql_str + " ORDER BY " + order

        q = klass.gql(gql_str)
        results = q.fetch(int(limit))
        klass.prefetchReferences(results)

        for result in results:
            out["response"]["objects"].append(result.toDict(full=False))

        self.response.out.write(json.encode(out))
Ejemplo n.º 19
0
	def get_phone_number( self ):
		spot_id = self.request.get( 'spot_id', None )
		if spot_id is None:
			message = "パラメータが足りません"
			logging.info( message )
			out = {"meta": functions.createMetaData( status="fail", code=400, message=message, method_name="getPhoneNumber" )};
			self.response.out.write( json.encode(out) )
			return

		import urllib2
		import lxml
		from lxml import html
		# htmlでーた取得
		html = urllib2.urlopen("http://tou.ch/spot/"+ spot_id +"/").read()
		root = lxml.html.fromstring(html)
		
		# xpathでアクセス
		tel_node = root.xpath('//*[@id="spot-data"]/p[2]')
		if len(tel_node) == 0:
			logging.info( "電話番号の登録がありません" )
			out = {
				"meta": functions.createMetaData( status="fail", code=200, method_name="getPhoneNumber" ),
				"response": "",
			};
			self.response.out.write( json.encode(out) )
			return


		tel_str = tel_node[0].text
			
		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="getPhoneNumber" ),
			"response": tel_str,
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 20
0
    def addTag(self, class_name):
        if self.checkModel(class_name) == False:
            return

        id = self.request.get("id", None)
        tag = self.request.get("tag", None)

        # パラメータチェック
        if id is None or tag is None:
            message = "パラメータが不正です"
            logging.warn(message)
            out = {"meta": functions.createMetaData(status="fail", code=401, method_name="addTag", message=message)}
            self.response.out.write(json.encode(out))
            return

            # 文字列からモデルクラス、エンティティ取得
        classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name)
        klass = webapp2.import_string(classPath_str)
        entity = klass.get_by_id(int(id))
        if entity is None:
            message = "エンティティが見つかりません"
            logging.warn(message)
            out = {"meta": functions.createMetaData(status="fail", code=401, method_name="addTag", message=message)}
            self.response.out.write(json.encode(out))
            return

        currentTag = entity.tags
        currentTag.append(tag)
        entity.put()

        # 出力
        out = {
            "meta": functions.createMetaData(status="ok", code=200, method_name="addTag"),
            "response": {"objects": [entity.toDict()]},
        }
        self.response.out.write(json.encode(out))
Ejemplo n.º 21
0
	def showme( self ):
		if self.user:
			# ログイン済みの時
			out = {
				"meta": functions.createMetaData( status="ok", code=200, method_name="showUser" ),
				"response":{
					"temp_uid": self.session.get("temp_uid"),
					"users": [
						self.user.toDict( True ),
					],
				},
			};
		else:
			# 未ログイン
			out = {
				"meta": functions.createMetaData(
					status="fail", code=401, cc_code=1000, message="You need to sign in or sign up before continuing." , method_name="showUser"
				),
				"response":{
					"temp_uid": self.session.get("temp_uid"),
				}
			};

		self.response.out.write( json.encode(out) )
Ejemplo n.º 22
0
	def extendSSOAccessToken( self ):
		if self.user is None:
			functions.printError( "ログインが必要です" )
			return;

		if self.user.external_accounts is None:
			functions.printError( "facebook認証が必要です" )
			return;

		url = "https://api.facebook.com/method/auth.extendSSOAccessToken?format=json&access_token="+ self.user.external_accounts.token
		result = urlfetch.fetch(url)
		if result.status_code != 200:
			functions.printError( "facebook extendSSOAccessToken tokenが不正です。"+ result.content )
			return
		result_obj = json.decode( result.content )
		
		if "access_token" in result_obj == False:
			logging.error( "facebook extendSSOAccessToken facebook の accessToken を延長できませんでした。"+ result.content )
			out = {
				"meta": functions.createMetaData( status="fail", code=200, method_name="extendSSOAccessToken" ),
			};
			self.response.out.write( json.encode(out) )
			return


		self.user.external_accounts.token = result_obj["access_token"]
		self.user.put()
		logging.debug( "facebook extendSSOAccessToken accessToken を正常に延長できました。" )

		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="extendSSOAccessToken" ),
			"response":{
				"accessToken": self.user.external_accounts.token,
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 23
0
	def query( self ):
		target_model = self.request.get( 'target_model', None );
		target_id = self.request.get( 'target_id', None );

		page = self.request.get( "page", 1 );
		per_page = self.request.get( "per_page", 10 );
		limit = self.request.get( "limit", 100 );
		skip = self.request.get( "skip", 0 );
		where = self.request.get( "where" );
		order = self.request.get( "order" );
		response_json_depth = self.request.get( "response_json_depth", 3 );


		# 文字列からモデルクラス取得
		classPath_str = "models."+ target_model.capitalize()
		klass = webapp2.import_string( classPath_str )


		gql_str = ""
		if where:
			gql_str = "WHERE "+ where +" AND is_deleted=False"
		else:
			gql_str = "WHERE is_deleted=False"
		gql_str = gql_str +" AND target_key = key('%s',%d)" % ( target_model.capitalize(), int(target_id) )


		if order:
			gql_str = gql_str +" ORDER BY "+ order


		q = models.Comment.gql( gql_str )
		results = q.fetch( int(limit) )
		klass.prefetchReferences( results )

		# 出力ひな形作成
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="queryComments" ),
			"response": {
				"comments":[],
			},
		};

		for result in results:
			out["response"]["comments"].append( result.toDict( full=False ) )

		self.response.out.write( json.encode(out) )
Ejemplo n.º 24
0
	def searchFacebookFriends( self ):
		if self.user is None:
			return;

		users = self.user.getInAppFacebookFriends()

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="searchFacebookFriends" ),
			"response": {
				"users": [],
			},
		}
		for user in users:
			out["response"]["users"].append( user.toDict() )

		self.response.out.write( json.encode(out) )
Ejemplo n.º 25
0
	def ranking( self ):
		content = self.request.get( "content", None )
		limit = int( self.request.get( "limit", 3 ) )
		if content is None:
			self.response.out.write( "parameter missing" )
			return

		nb = openfish.libs.naivebayes.naivebayes.NaiveBayes()
		result = nb.getRanking( content )
		result = result[:limit] # limit まで切り詰める

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="bayesRanking" ),
			"response": {
				"categories": result,
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 26
0
	def upload( self ):
		file = self.request.body;
		mimetype = self.request.get( "mimetype", 'application/octet-stream' )

		# 保存
		entity = models.File()
		entity.user_key = self.user.key if self.user else None
		entity.setBlob( file, mimetype )
		entity.put();

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="createFile" ),
			"response": {
				"files":[
					entity.toDict(),
				],
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 27
0
	def upload( self ):
		# openfish.functions.logAccessUser( self.user );

		photo = self.request.body;

		# 保存
		entity = models.Photo()
		entity.user_key = self.user.key if self.user else None
		entity.setBlob( photo, "image/jpeg" )
		entity.put()

		# 出力
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="uploadPhoto" ),
			"response": {
				"photos":[
					entity.toDict(),
				],
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 28
0
	def query( self ):
		page = self.request.get( "page", 1 );
		per_page = self.request.get( "per_page", 10 );
		limit = self.request.get( "limit", 100 );
		skip = self.request.get( "skip", 0 );
		where = self.request.get( "where" );
		order = self.request.get( "order" );
		response_json_depth = self.request.get( "response_json_depth", 3 );

		# 出力ひな形作成
		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="queryPosts" ),
			"response": {
				"posts":[],
			},
		};

		# 取得して出力データに追加
		q = models.Post.query();
		for result in q.iter():
			out["response"]["posts"].append( result.toDict() )

		self.response.out.write( json.encode(out) )
Ejemplo n.º 29
0
	def externalAccountLink( self ):
		if self.user is None:
			functions.printError( "users externalAccountLink ログインが必要です" )
			return;

		type = self.request.get( "type" )
		token = self.request.get( "token", None )

		ea = models.ExternalAccount()
		ea.token = token
		ea.external_type = type

		# facebook情報を取得
		url = 'https://graph.facebook.com/me?access_token='+ token +'&fields=name,picture,email&locale=ja_JP'
		result = urlfetch.fetch(url)
		if result.status_code != 200:
			functions.printError( "tokenが不正です。"+ result.content )
			return
		result_obj = json.decode( result.content )
		facebook_id = str( result_obj["id"] )
		auth_id = "facebook:"+ facebook_id
		ea.external_id = facebook_id

		self.user.external_accounts = ea;
		if "email" in result_obj:
			self.user.email = result_obj["email"]
		self.user.add_auth_id( auth_id )

		out = {
			"meta": functions.createMetaData( status="ok", code=200, method_name="externalAccountLink" ),
			"response":{
				"users": [
					self.user.toDict( full=True ),
				],
			},
		};
		self.response.out.write( json.encode(out) )
Ejemplo n.º 30
0
    def update(self, class_name):
        if self.checkModel(class_name) == False:
            return

            # logging.info( self.request.arguments() )
        id = self.request.get("id", None)

        # パラメータチェック
        if id is None:
            message = "パラメータが不正です"
            logging.warn(message)
            out = {
                "meta": functions.createMetaData(status="fail", code=401, method_name="updateObject", message=message)
            }
            self.response.out.write(json.encode(out))
            return

            # 文字列からモデルクラス、エンティティ取得
        classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name)
        klass = webapp2.import_string(classPath_str)
        entity = klass.get_by_id(int(id))
        if entity is None:
            message = u"エンティティが見つかりません id=" + id
            logging.warn(message)
            out = {
                "meta": functions.createMetaData(status="fail", code=401, method_name="updateObject", message=message)
            }
            self.response.out.write(json.encode(out))
            return

            # マスタデータかどうかチェック & マスターデータだったら管理者以外は更新できないように。
        if hasattr(klass, "isMasterData") and klass.isMasterData and users.is_current_user_admin() == False:
            logging.warn("管理者以外がマスタデータを更新しようとしました")
            return False

            # ログインチェック
        if hasattr(entity, "user_key") == True and entity.user_key and users.is_current_user_admin() == False:
            if self.user is None:
                message = "ログインが必要です。"
                logging.warn(message)
                out = {
                    "meta": functions.createMetaData(
                        status="fail", code=401, method_name="updateObject", message=message
                    )
                }
                self.response.out.write(json.encode(out))
                return

                # 投稿ユーザーチェック
            if entity.user_key != self.user.key:
                message = "あなたの投稿したエンティティではありません"
                logging.warn(message)
                out = {
                    "meta": functions.createMetaData(
                        status="fail", code=401, method_name="updateObject", message=message
                    )
                }
                self.response.out.write(json.encode(out))
                return

                # --- 各種チェック終了 ---

                # 更新して保存
        self.setPropertyFromRequestData(entity, self.request)
        entity.put()

        # 出力
        out = {
            "meta": functions.createMetaData(status="ok", code=200, method_name="updateObject"),
            "response": {"objects": [entity.toDict()]},
        }
        self.response.out.write(json.encode(out))