Example #1
0
def invite_list(data):
    userId = UserService.user_id(data['UserKey'])
    db = MySQL()

    inviteListInstance = db.list(
        'SELECT * FROM `invite` WHERE `invite_date` >= NOW() - INTERVAL 60 DAY AND `is_pocket` = 0 AND `user_id` = %s AND `type` = %s',
        (userId, data.get('Type', None)),
        sort='invite_date',
        order='DESC')

    results = []
    for invite in inviteListInstance:
        dealUser = UserService.user_get(
            invite['deal_user_id'],
            notRaise=True) if invite['deal_user_id'] else None
        results.append({
            'Code': invite['id'],
            'InviteDate': invite['invite_date'],
            'ReferId': invite['refer_id'],
            'IsDeal': invite['is_deal'],
            'DealUserId': invite['deal_user_id'] if dealUser else None,
            'DealUser': dealUser['name'] if dealUser else None,
            'DealDate': invite['deal_date'] if dealUser else None,
            'IsPocket': invite['is_pocket'],
            'PocketDate': invite['pocket_date'],
        })

    return {
        'Type': data.get('Type', None),
        'Count': len(results),
        'Results': results,
    }
Example #2
0
def invite_list(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()

	inviteListInstance = db.list('SELECT * FROM `invite` WHERE `invite_date` >= NOW() - INTERVAL 60 DAY AND `is_pocket` = 0 AND `user_id` = %s AND `type` = %s', (userId, data.get('Type', None)), sort='invite_date', order='DESC')
	
	results = []
	for invite in inviteListInstance:
		dealUser = UserService.user_get(invite['deal_user_id'], notRaise = True) if invite['deal_user_id'] else None
		results.append({
				'Code': invite['id'],
				'InviteDate': invite['invite_date'],
				'ReferId': invite['refer_id'],
				'IsDeal': invite['is_deal'],
				'DealUserId': invite['deal_user_id'] if dealUser else None,
				'DealUser': dealUser['name'] if dealUser else None,
				'DealDate': invite['deal_date'] if dealUser else None,
				'IsPocket': invite['is_pocket'],
				'PocketDate': invite['pocket_date'],
			})

	return {
		'Type': data.get('Type', None),
		'Count': len(results),
		'Results': results,
	}
Example #3
0
    def notify_send(self, data):
        """
		发送通知
		参数:
			UserKey[string] – 用户会话ID
			NotifyUserId[string] - 通知用户ID
			Content[string] - 通知内容
			ReferId[string] - 相关对象ID[可选]
		返回值:
			NotifyId[string] – 通知ID
		"""
        if not self.__has_params(data, ('UserKey', 'NotifyUserId', 'Content')):
            raise tornado.web.HTTPError(400, '参数 Error')

        userId = UserService.user_id(data['UserKey'])
        toUser = UserService.user_get(data['NotifyUserId'])

        if not toUser:
            raise tornado.web.HTTPError(404, '通知用户不存在')

        self.__reponseJSON({
            'NotifyId':
            NotifyService.create(data['NotifyUserId'],
                                 data['Content'],
                                 sender=userId,
                                 refId=data.get('ReferId', None))
        })
Example #4
0
    def user_id(self, data):
        """
		获取用户信息
		参数:
			UserKey[string] – 用户登录后的会话ID
		返回值:
			UserId[String] – 用户ID
			Name[String] – 用户姓名
			Login[String] – 用户绑定的登录账户
			Mobile[String] – 用户绑定的手机号
			Email[String] – 用户绑定的邮箱
		"""
        if not self.__has_params(data, ('UserKey')):
            raise tornado.web.HTTPError(400, '参数Error')

        userId = UserService.user_id(data['UserKey'])
        user = UserService.user_get(userId)

        self.__reponseJSON({
            'UserId': userId,
            'Name': user['name'],
            'Mobile': user['mobile'],
            'Login': user['login'],
            'Email': user['email'],
        })
Example #5
0
	def user_id(self, data):
		"""
		获取用户信息
		参数:
			UserKey[string] – 用户登录后的会话ID
		返回值:
			UserId[String] – 用户ID
			Name[String] – 用户姓名
			Login[String] – 用户绑定的登录账户
			Mobile[String] – 用户绑定的手机号
			Email[String] – 用户绑定的邮箱
		"""
		if not self.__has_params(data, ('UserKey')):
			raise tornado.web.HTTPError(400, '参数Error')

		userId = UserService.user_id(data['UserKey'])
		user = UserService.user_get(userId)

		self.__reponseJSON({
			'UserId'    : userId,
			'Name'      : user['name'],
			'Mobile'    : user['mobile'],
			'Login'     : user['login'],
			'Email'     : user['email'],
		})
Example #6
0
def share_video(data):
	"""
	分享视频
	方法:
		share_video
	参数:
		UserKey[string] –用户登录后的会话ID。
		VID[string] – 分配的视频ID
		To[Array] – 分享对象列表,分享对象如下定义:
			Mobile[string] – 分享手机号,必填
			Name[string] – 分享姓名,可选
	返回值:
		sessionId[string] – 分配的分享会话ID
		Results[Array] – 分享结果对象列表,分享结果对象如下定义:
			Mobile[string] – 分享手机号
			Signup[boolean] – 是否注册用户
	"""
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()

	videoInstance = db.get('SELECT * FROM `video` WHERE `id` = %s', (data['VID']))
	if not videoInstance:
		raise Exception("视频不存在.")

	sessionId = Utils.UUID()
	results = []
	for to in data.get('To', ()):
		toUserId = UserService.getUserIdByMobile(to.get('Mobile'))
		result = db.save("""INSERT INTO `share` (`session_id`,`owner_id`,`video_id`,`to_user_id`,`to_mobile`,`to_name`) VALUES (%s,%s,%s,%s,%s,%s)"""
					, (sessionId, userId, data['VID'], toUserId, to.get('Mobile'), to.get('Name')))
		db.end()

		if toUserId:
			# create app notify
			NotifyService.create(toUserId, Utils.json_dumps({
				'Type'	: 'share_video',
				'From'	: UserService.user_mobile(userId),
				'To'	: to.get('Mobile'),
				'Date'	: datetime.now(),
				'VID'	: data['VID'],
			}), sender = 'share_video', refId = sessionId)

		if result:
			results.append({
				'Mobile': to.get('Mobile'),
				'Signup': toUserId != None
				})

	return {'SessionId': sessionId, 'Results': results}
Example #7
0
	def notify_list(self, data):
		"""
		通知列表
		参数:
			UserKey[string] – 用户会话ID
		返回值:
			Count[int] - 未读通知数量
			Results[Array] – 授权对象列表:
				NotifyId[string] – 通知ID
				Content[string] - 通知内容
				ReferId[string] - 相关对象ID[可选]
				Sender[string] - 通知发送者[可选]
				CreateTime[date] - 通知创建时间
				ArrivedTime[date] - 通知到达时间
				VisitedTime[date] - 通知查看时间
		"""
		if not self.__has_params(data, ('UserKey')):
			raise tornado.web.HTTPError(400, '参数 Error')

		userId = UserService.user_id(data['UserKey'])
		notifyList = NotifyService.list(userId)

		self.__reponseJSON({
			'Now': datetime.now(),
			'Results': notifyList,
			})
Example #8
0
	def user_auth(self, data):
		"""
		验证用户身份
		参数:
			Id[string] – 用户手机号码/用户名/绑定邮箱等相关支持方式的Id
			Device[string] – 登录设备名称
			Validate[string] – 验证码(通过调用vaildate接口下发的验证码,由用户输入)或 密码
		返回值:
			UserKey[string] – 用户登录后的会话ID。(用于后续功能调用)
			NewUser[boolean] – 是否新注册用户
			ValidityDate[date] – 登录会话有效日期。
		"""
		if not self.__has_params(data, ('Id', 'Device', 'Validate')):
			raise tornado.web.HTTPError(400, '参数Error')

		result = UserService.user_auth(data)
		if not result or not result['UserKey']:
			raise tornado.web.HTTPError(500, '验证码或用户名、密码错误!') 

		self.__reponseJSON({
			'Now'     : datetime.now(),
			'UserKey' : result['UserKey'],
			'NewUser' : result['NewUser'],
			'ValidityDate' : result['ValidityDate']
			})
		pass
Example #9
0
	def parseBody(self, data):
		try:
			if self._command == NOTIFY_COMMAND_REGISTER:
				# data == userKey
				self._userId = UserService.getUserId(str(data))

				send_notify(self._userId)
				print "[%s] Client Register UserId: %s" % ( datetime.now().strftime('%Y-%m-%d %H:%M:%S'), self._userId )

			elif self._command == NOTIFY_COMMAND_PING:
				self.postMessage(NOTIFY_COMMAND_PING, data)

			elif self._command == NOTIFY_COMMAND_NEWNOTIFY:
				# data == userId
				print "[%s] Has Notify UserId: %s " % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), data)
				send_notify(str(data))

			else:
				print "[%s] Unknown command: %s %s" % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), str(self._command), self._address)

		except Exception as e:
			print 'has error, to close connection! (%s)' % e
			self.close()

		self.postReadHeader() # read new packet
Example #10
0
    def user_auth(self, data):
        """
		验证用户身份
		参数:
			Id[string] – 用户手机号码/用户名/绑定邮箱等相关支持方式的Id
			Device[string] – 登录设备名称
			Validate[string] – 验证码(通过调用vaildate接口下发的验证码,由用户输入)或 密码
		返回值:
			UserKey[string] – 用户登录后的会话ID。(用于后续功能调用)
			NewUser[boolean] – 是否新注册用户
			ValidityDate[date] – 登录会话有效日期。
		"""
        if not self.__has_params(data, ('Id', 'Device', 'Validate')):
            raise tornado.web.HTTPError(400, '参数Error')

        result = UserService.user_auth(data)
        if not result or not result['UserKey']:
            raise tornado.web.HTTPError(500, '验证码或用户名、密码错误!')

        self.__reponseJSON({
            'Now': datetime.now(),
            'UserKey': result['UserKey'],
            'NewUser': result['NewUser'],
            'ValidityDate': result['ValidityDate']
        })
        pass
Example #11
0
def video_ready(data):
	"""
	视频处理状态
	方法:
		video_ready
	参数:
		UserKey[string] –用户登录后的会话ID。
		VID[string] – 视频ID
	返回值:
		VID[string] – 视频ID
		Results[Array] – 视频对象列表,视频对象定义如下:
			Definition[string] - 清晰度
			Ready[boolean] - 是否准备就绪
			URL[string] – 视频所有者,默认为视频上传/分享者的手机号
			Progress[float] – 处理进度
	"""
	result = []
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()
	videoInstance = db.get('SELECT * FROM `video` WHERE `id` = %s', (data['VID']))
	if videoInstance:

		VideoBaseURL = Config.get('Video','VideoBaseURL')
		videoTranscodeListInstance = db.list('SELECT * FROM `video_transcode` WHERE `video_id` = %s ORDER BY `video_width` DESC', (data['VID']))

		for videoTranscodeInstance in videoTranscodeListInstance:
			result.append({
				'Definition': MediaProbe.definitionName(videoTranscodeInstance['video_height'], videoTranscodeInstance['video_width']),
				'Ready'     : videoTranscodeInstance['is_ready'] == 1,
				'URL'       : "%s/%s" % (VideoBaseURL, videoTranscodeInstance['file_name']),
				'Progress'  : float(videoTranscodeInstance['progress']),
			})

	return result
Example #12
0
def upload_progress(data):
    """
	获取视频上传进度
	方法:
		upload_progress
	参数:
		UserKey[string] –用户登录后的会话ID。
		UploadId[string] – 分配的视频ID
	返回值:
		Length[long] – 视频字节数,单位BYTES。
		Saved[long] – 上传字节数,单位BYTES。
	"""
    userId = UserService.user_id(data['UserKey'])
    db = MySQL()

    uploadSession = db.get(
        "SELECT * FROM `upload` WHERE `id`=%s and `owner_id` = %s",
        (data['UploadId'], userId))
    if uploadSession == False:
        raise Exception("上传任务不存在或已过期!")

    return ({
        'length': long(uploadSession['length']),
        'saved': long(uploadSession['saved'])
    })
Example #13
0
def video_poster(data):
	"""
	视频截图更新
	方法:
		video_poster
	参数:
		UserKey[string] –用户登录后的会话ID。
		VID[string] – 分配的视频ID
		Time[float] – 截图播放时间点
	返回值:
		VID[string] – 视频ID
		Poster[string] – 视频截图地址
	"""
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()
	videoInstance = db.get('SELECT * FROM `video` WHERE `id` = %s', (data['VID']))

	if videoInstance:
		fileName = "%s/%s.mp4" % (videoDirectory, videoInstance['id'])

		PosterBaseURL = Config.get('Video','PosterBaseURL')
		PosterURL = "%s/%s.jpg" % (PosterBaseURL, videoInstance['id'])

		Transcoder.VideoPoster(fileName, ("%s/%s.jpg" % (videoDirectory, videoInstance['id'])), ss=float(data['Time']))
		return {
			'VID'       : videoInstance['id'],
			'Poster'    : PosterURL
		}

	return None
Example #14
0
def video_remove(data):
    """
	删除视频
	方法:
		video_remove
	参数:
		UserKey[string] –用户登录后的会话ID。
		VID[string] – 分配的视频ID
	返回值:
		VID[string] – 删除的视频ID
	"""
    userId = UserService.user_id(data['UserKey'])
    db = MySQL()

    videoInstance = db.get(
        'SELECT * FROM `video` WHERE `owner_id`=%s and `id` = %s',
        (userId, data['VID']))
    if not videoInstance:
        raise Exception("视频不存在.")

    db.delete("DELETE FROM `video` WHERE `owner_id`=%s and `id` = %s",
              (userId, data['VID']))
    db.end()

    return {'VID': data['VID']}
Example #15
0
def space_res_list(data):
	userId = UserService.user_id(data['UserKey'])
	if __test_auth_view(userId, data.get('Id', '')) > 0:
		db = MySQL()

		offset = long(data.get('Offset', 0))
		sort = max(1, min(3, int(data.get('Sort', 1))))
		order = int(data.get('Order', 0))
		listMax = min(100, data.get('Max', 10))

		resCount = db.get("SELECT COUNT(*) AS c FROM `space_resource` WHERE `space_id` = %s AND `res_type`=%s", (data.get('Id', ''), data.get('ResType', '')))['c']
		resList = db.list("SELECT * FROM `space_resource` WHERE `space_id` = %s AND `res_type`=%s", 
							(data.get('Id', ''), data.get('ResType', '')), sort='order_field%s'%sort, order='DESC' if order == 0 else 'ASC', offset=offset, pagesize=listMax )
		results = []
		for res in resList:
			results.append({
					'ResId': res['res_id'],
					'OrderField1': res['order_field1'],
					'OrderField2': res['order_field2'],
					'OrderField3': res['order_field3'],
				})

		return {
			'Id': data.get('Id', ''),
			'ResType': data.get('ResType', ''),
			'Count': resCount,
			'Offset': offset,
			'Max': listMax,
			'Sort': sort,
			'Order': order,
			'Results': results
		}
	else:
		raise Exception('没有权限或空间不存在')
Example #16
0
def video_update(data):
    """
	更新视频信息
	参数:
		UserKey[string] –用户登录后的会话ID。
		VID[string] – 视频ID
		Title[string] – 视频标题
		Author[string] – 分享者/创作者名称
		CreateTime[date] – 创作日期
		Category[string] – 视频分类
		Describe[string] – 视频描述
		Tag[string] – 视频标签,标签内容有半角“,”(逗号)分割
		AddrStr[string] - 视频位置信息
		Longitude[float] - 视频位置 - 经度
		Latitude[float] - 视频位置 - 纬度
	返回值:
		VID[string] – 视频ID
	"""

    userId = UserService.user_id(data['UserKey'])
    videoId = data.get('VID', '')

    db = MySQL()
    db.update(
        "UPDATE `video` set `title` = %s, `author` = %s, `create_date` = %s, `category` = %s, `describe` = %s, `tag` = %s  WHERE `id` = %s AND `owner_id` = %s ",
        (data.get('Title', ''), data.get('Author', ''),
         data.get('CreateTime', ''), data.get('Category', ''),
         data.get('Describe', ''), data.get('Tag', ''), videoId, userId))

    db.end()

    return data.get('VID', '')
Example #17
0
def video_poster(data):
    """
	视频截图更新
	方法:
		video_poster
	参数:
		UserKey[string] –用户登录后的会话ID。
		VID[string] – 分配的视频ID
		Time[float] – 截图播放时间点
	返回值:
		VID[string] – 视频ID
		Poster[string] – 视频截图地址
	"""
    userId = UserService.user_id(data['UserKey'])
    db = MySQL()
    videoInstance = db.get('SELECT * FROM `video` WHERE `id` = %s',
                           (data['VID']))

    if videoInstance:
        fileName = "%s/%s.mp4" % (videoDirectory, videoInstance['id'])

        PosterBaseURL = Config.get('Video', 'PosterBaseURL')
        PosterURL = "%s/%s.jpg" % (PosterBaseURL, videoInstance['id'])

        Transcoder.VideoPoster(
            fileName, ("%s/%s.jpg" % (videoDirectory, videoInstance['id'])),
            ss=float(data['Time']))
        return {'VID': videoInstance['id'], 'Poster': PosterURL}

    return None
Example #18
0
def space_reindex(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()

	spaceId = data.get('Id', '')
	afterId = data.get('After', '')

	index = []
	spaceListInstance = db.list('SELECT * FROM `space` WHERE `user_id` = %s ORDER BY `index` ASC', (userId))
	for space in spaceListInstance:
		index.append(space['id'])

	if not spaceId in index:
		raise Exception('空间不存在')

	index.remove(spaceId)
	if afterId == 'HEAD':
		index.insert(0, spaceId)
	elif afterId in index:
		index.insert(index.index(afterId) + 1, spaceId)
	else:
		index.append(spaceId)

	for i,value in enumerate(index):
		db.update("UPDATE `space` SET `index` = %s WHERE `id` = %s", (i, value))
	db.end()

	return {
		'Id': spaceId,
	}
Example #19
0
    def notify_list(self, data):
        """
		通知列表
		参数:
			UserKey[string] – 用户会话ID
		返回值:
			Count[int] - 未读通知数量
			Results[Array] – 授权对象列表:
				NotifyId[string] – 通知ID
				Content[string] - 通知内容
				ReferId[string] - 相关对象ID[可选]
				Sender[string] - 通知发送者[可选]
				CreateTime[date] - 通知创建时间
				ArrivedTime[date] - 通知到达时间
				VisitedTime[date] - 通知查看时间
		"""
        if not self.__has_params(data, ('UserKey')):
            raise tornado.web.HTTPError(400, '参数 Error')

        userId = UserService.user_id(data['UserKey'])
        notifyList = NotifyService.list(userId)

        self.__reponseJSON({
            'Now': datetime.now(),
            'Results': notifyList,
        })
Example #20
0
    def parseBody(self, data):
        try:
            if self._command == NOTIFY_COMMAND_REGISTER:
                # data == userKey
                self._userId = UserService.getUserId(str(data))

                send_notify(self._userId)
                print "[%s] Client Register UserId: %s" % (
                    datetime.now().strftime('%Y-%m-%d %H:%M:%S'), self._userId)

            elif self._command == NOTIFY_COMMAND_PING:
                self.postMessage(NOTIFY_COMMAND_PING, data)

            elif self._command == NOTIFY_COMMAND_NEWNOTIFY:
                # data == userId
                print "[%s] Has Notify UserId: %s " % (
                    datetime.now().strftime('%Y-%m-%d %H:%M:%S'), data)
                send_notify(str(data))

            else:
                print "[%s] Unknown command: %s %s" % (datetime.now().strftime(
                    '%Y-%m-%d %H:%M:%S'), str(self._command), self._address)

        except Exception as e:
            print 'has error, to close connection! (%s)' % e
            self.close()

        self.postReadHeader()  # read new packet
def signup():
    request_json = request.get_json()
    email = request_json['email']
    password = request_json['password']
    family_members = request_json['family_members']

    return jsonify(
        userService.addUser(UserPojo(email, password, family_members)))
Example #22
0
def register():
    request_data = request.get_json()
    username = request_data['username']
    password = request_data['password']
    email = request_data['email']
    user = UserService.create(username=username, password=password, email=email)
    if user:
        return jsonify(wrap_json_response(1, {}))
    else:
        return jsonify(wrap_json_response(0, {}))
Example #23
0
def login():
    request_data = request.get_json(force=True)
    username = request_data['username']
    password = request_data['password']
    user = UserService.auth(username, password)
    if user:
        login_user(user)
        return jsonify(wrap_json_response(1, {}))
    else:
        return jsonify(wrap_json_response(0, {}))
Example #24
0
def space_authorize(data):
	userId = UserService.user_id(data['UserKey'])
	spaceInstance = space_get(data.get('Id', ''))
	if userId == spaceInstance['user_id']:
		allowEdit = min(1, max(0, int(data.get('AllowEdit', 0))))
		db = MySQL()
		authorizeUser = UserService.user_get(data.get('UserId', ''))
		result = db.update("REPLACE INTO `space_authorize` (`space_id`, `user_id`, `allow_edit`) VALUES (%s,%s,%s)", 
						(data.get('Id', ''), data.get('UserId', ''), allowEdit))
		db.end()
		return {
			'Id': spaceInstance['id'],
			'Name': spaceInstance['name'],
			'UserId': authorizeUser['id'],
			'UserName': authorizeUser['name'],
			'AllowEdit': allowEdit,
		}
	else:
		raise Exception('没有权限或空间不存在')
Example #25
0
def invite_info(data):
    """
	邀请信息
	参数:
		Code[string] – 邀请码
	返回值:
		Code[string] – 邀请码
		Type[string] - 邀请类型
		ReferId[string] - 引用对象ID
		InviterId[string] – 邀请者UserId
		Inviter[string] – 邀请者姓名
		InviteDate[date] – 邀请日期
		Info[string] – 邀请信息
	"""
    db = MySQL()

    invite = db.get('SELECT * FROM `invite` WHERE `id` = %s',
                    (data.get('Code', None)))

    if not invite:
        raise Exception('邀请码不存在')

    inviter = UserService.user_get(invite['user_id'], notRaise=True)
    dealUser = UserService.user_get(
        invite['deal_user_id'],
        notRaise=True) if invite['deal_user_id'] else None

    return {
        'Code': invite['id'],
        'Type': invite['type'],
        'Inviter': inviter['name'],
        'InviterId': invite['user_id'],
        'InviteDate': invite['invite_date'],
        'ReferId': invite['refer_id'],
        'IsDeal': invite['is_deal'],
        'DealUser': dealUser['name'] if dealUser else None,
        'DealUserId': invite['deal_user_id'] if dealUser else None,
        'DealDate': invite['deal_date'] if dealUser else None,
        'IsPocket': invite['is_pocket'],
        'PocketDate': invite['pocket_date'] if invite['is_pocket'] else None,
        'Info': invite['info'],
    }
Example #26
0
def invite_pocket(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()
	result = db.update("UPDATE `invite` SET `is_pocket` = 1, `pocket_date` = now() WHERE `user_id` = %s AND `id` = %s AND `is_pocket` = 0", (userId, data.get('Code', None)))
	db.end()
	if result > 0:
		return {
			'Code': data.get('Code', None)
		}
	else:
		raise Exception('邀请码不存在或已处理')
Example #27
0
def invite_pocket(data):
    userId = UserService.user_id(data['UserKey'])
    db = MySQL()
    result = db.update(
        "UPDATE `invite` SET `is_pocket` = 1, `pocket_date` = now() WHERE `user_id` = %s AND `id` = %s AND `is_pocket` = 0",
        (userId, data.get('Code', None)))
    db.end()
    if result > 0:
        return {'Code': data.get('Code', None)}
    else:
        raise Exception('邀请码不存在或已处理')
Example #28
0
def space_authorize_list(data):
	userId = UserService.user_id(data['UserKey'])
	spaceInstance = space_get(data.get('Id', ''))

	if userId == spaceInstance['user_id']:
		db = MySQL()
		results=[]
		for item in db.list("SELECT DISTINCT * FROM `space_authorize` WHERE `space_id`=%s", data.get('Id', '')):
			authorizeUser = UserService.user_get(item['user_id'])
			results.append({
					'UserId': item['user_id'],
					'UserName': authorizeUser['name'],
					'AllowEdit': item['allow_edit']
				})
		return {
			'Id': data.get('Id', ''),
			'Name': spaceInstance['name'], 
			'Results': results
		}
	else:
		raise Exception('没有权限或空间不存在')
Example #29
0
def upload_data(data):
    """
	上传内容
	方法:
		upload_data
	参数:
		UserKey[string] –用户登录后的会话ID。
		UploadId[string] – 分配的视频ID
		Offset[long] – 视频文件偏移,单位BYTES。
		Data[string] – 数据包,经Base64编码后的数据包。
		Size[long] – 数据包包含数据大小(Base64编码前)。
	返回值:
		Length[long] – 视频字节数,单位BYTES。
		Saved[long] – 上传字节数,单位BYTES。
	"""
    userId = UserService.user_id(data['UserKey'])
    db = MySQL()

    uploadSession = db.get(
        "SELECT * FROM `upload` WHERE `id` = %s and `owner_id` = %s",
        (data['UploadId'], userId))

    if uploadSession == False:
        raise Exception("上传任务不存在或已过期!")

    bindata = base64.b64decode(data['Data'])
    offset = data['Offset']
    length = uploadSession['length']
    saved = uploadSession['saved'] + len(bindata)

    if len(bindata) != data['Size']:
        raise Exception("上传数据大小与提供的'Size'不匹配!")

    if length > 0 and saved > length:
        raise Exception("上传数据溢出!")

    if length > 0 and offset != uploadSession['saved']:
        raise Exception("上传数据不同步!")

    if db.update(
            "UPDATE `upload` SET `saved` = %s, `update_time` = now() WHERE `id` = %s and `owner_id` = %s",
        (saved, data['UploadId'], userId)) != 1:
        raise Exception("同步数据库失败!")
    db.end()

    fileName = "%s/%s" % (__uploadDirectory, data['UploadId'])

    f = open(fileName, 'ab')
    f.write(bindata)
    f.flush()
    f.close()

    return ({'length': long(length), 'saved': long(saved)})
Example #30
0
def invite_code(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()

	code = Utils.UUID()
	result = db.save("INSERT INTO `invite` (`id`, `user_id`, `type`, `refer_id`, `info`) VALUES (%s,%s,%s,%s,%s)", 
					(code, userId, data.get('Type', None), data.get('ReferId', None), data.get('Info', None)))
	db.end()

	return {
		'Code': code,
	}
Example #31
0
def space_authorized_spaces(data):
	userId = UserService.user_id(data['UserKey'])
	userInstance = UserService.user_get(userId)

	db = MySQL()
	results=[]
	for item in db.list("SELECT DISTINCT * FROM `space_authorize` WHERE `user_id`=%s", userId):
		spaceInstance = space_get(item['space_id'])
		if spaceInstance:
			spaceOwner = UserService.user_get(spaceInstance['user_id'], notRaise=True)
			results.append({
					'Id': spaceInstance['id'],
					'Name': spaceInstance['name'],
					'Owner': spaceOwner['name'] if spaceOwner else None,
					'OwnerId': spaceInstance['user_id'],
					'AllowEdit': item['allow_edit']
				})

	return {
		'Count': len(results),
		'Results': results
	}
Example #32
0
def space_rename(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()
	result = db.update("UPDATE `space` SET `name` = %s WHERE `id` = %s AND `user_id` = %s", (data.get('Name', ''), data.get('Id', ''), userId))
	db.end()

	if result > 0:
		return {
			'Id': data.get('Id', ''),
			'Name': data.get('Name', ''),
		}
	else:
		raise Exception('更新失败或空间不存在')
Example #33
0
def invite_info(data):
	"""
	邀请信息
	参数:
		Code[string] – 邀请码
	返回值:
		Code[string] – 邀请码
		Type[string] - 邀请类型
		ReferId[string] - 引用对象ID
		InviterId[string] – 邀请者UserId
		Inviter[string] – 邀请者姓名
		InviteDate[date] – 邀请日期
		Info[string] – 邀请信息
	"""
	db = MySQL()

	invite = db.get('SELECT * FROM `invite` WHERE `id` = %s', (data.get('Code', None)))

	if not invite:
		raise Exception('邀请码不存在')

	inviter = UserService.user_get(invite['user_id'], notRaise = True)
	dealUser = UserService.user_get(invite['deal_user_id'], notRaise = True) if invite['deal_user_id'] else None

	return {
			'Code': invite['id'],
			'Type': invite['type'],
			'Inviter': inviter['name'],
			'InviterId': invite['user_id'],
			'InviteDate': invite['invite_date'],
			'ReferId': invite['refer_id'],
			'IsDeal': invite['is_deal'],
			'DealUser': dealUser['name'] if dealUser else None,
			'DealUserId': invite['deal_user_id'] if dealUser else None,
			'DealDate': invite['deal_date'] if dealUser else None,
			'IsPocket': invite['is_pocket'],
			'PocketDate': invite['pocket_date'] if invite['is_pocket'] else None,
			'Info': invite['info'],
		}
Example #34
0
	def notify_send(self, data):
		"""
		发送通知
		参数:
			UserKey[string] – 用户会话ID
			NotifyUserId[string] - 通知用户ID
			Content[string] - 通知内容
			ReferId[string] - 相关对象ID[可选]
		返回值:
			NotifyId[string] – 通知ID
		"""
		if not self.__has_params(data, ('UserKey', 'NotifyUserId', 'Content')):
			raise tornado.web.HTTPError(400, '参数 Error')

		userId = UserService.user_id(data['UserKey'])
		toUser = UserService.user_get(data['NotifyUserId'])

		if not toUser:
			raise tornado.web.HTTPError(404, '通知用户不存在')

		self.__reponseJSON({
			'NotifyId': NotifyService.create(data['NotifyUserId'], data['Content'], sender=userId, refId=data.get('ReferId', None))
			})
Example #35
0
def invite_code(data):
    userId = UserService.user_id(data['UserKey'])
    db = MySQL()

    code = Utils.UUID()
    result = db.save(
        "INSERT INTO `invite` (`id`, `user_id`, `type`, `refer_id`, `info`) VALUES (%s,%s,%s,%s,%s)",
        (code, userId, data.get('Type', None), data.get(
            'ReferId', None), data.get('Info', None)))
    db.end()

    return {
        'Code': code,
    }
Example #36
0
    def __init__(self):

        #接口地址配置
        ipaddr = '10.32.173.200'
        #服务器地址
        port = 8085
        #端口号
        projectname = '/XK_Phr_Proxy/UserServlet'

        transport = THttpClient.THttpClient(
            ipaddr, port, projectname)  # ip  port projectname
        self.transport = TTransport.TBufferedTransport(transport)
        protocol = TBinaryProtocol.TBinaryProtocol(transport)
        self.client = UserService.Client(protocol)
Example #37
0
    def configure(
        self, num_of_movie_need_rating=60,
        knn_sim_metric="correlation", knn_n_neighbor=10,
        df_user=None, df_app_user=None,
        df_data=None, df_ratmat=None, df_app_data=None,
        df_movie=None,df_movie_genre=None):
        """Instantiates, wire and configure all the object comprising of the system.

        Args:
            num_of_movie_need_rating: minimum amount of rating required for a user
            knn_sim_metric: KNN metric option, default: "correlation"
            knn_n_neighbor: number of K nearest users for KNN
            df_user: optional custom data set for base user
            df_app_user: optional custom data set for app user
            df_data: optional custom data set for base user rating data
            df_ratmat: optional custom data set for userxrating matrix
            df_app_data: optional custom data set for app user rating data
            df_movie: optional custom data set for movie information
            df_movie_genre: optional custom data set for movie by genre information
        """
        self.num_of_movie_need_rating = num_of_movie_need_rating

        # configure model objects
        self.knn_n_neighbor = knn_n_neighbor
        knn = Knn.Knn(knn_sim_metric)
        genre = Genre.Genre()

        # configure backend data objects
        movie_data = md.MovieData(df_movie=df_movie, df_movie_genre=df_movie_genre)
        user_data = ud.UserData(df_user=df_user)
        app_user_data = ud.AppUserData(user_data, df_app_user=df_app_user)
        rating_data = rd.RatingData(df_data=df_data, df_ratmat=df_ratmat, df_app_data=df_app_data)

        # configure backend service objects
        user_service = us.UserService(user_data, app_user_data)
        movie_service = ms.MovieService(movie_data, rating_data)
        recommend_service = cs.RecommendService(rating_data, movie_data, user_data, app_user_data, knn, genre)
        rating_service = rs.RatingService(rating_data, movie_data, user_data, app_user_data)

        # app reference to backend service end points
        self.bs_movie = bs.MovieService(movie_service)
        self.bs_user = bs.UserService(user_service)
        self.bs_recommend = bs.RecommendService(recommend_service)
        self.bs_rating = bs.RatingService(rating_service)

        # configure frontend UI object and passes over backend end points
        self.fe = UI.UI(self, num_of_movie_need_rating)
        self.fe.configure(self.bs_movie, self.bs_user, self.bs_recommend, self.bs_rating)
Example #38
0
	def user_password(self, data):
		"""
		更改用户登录密码
		参数:
			UserKey[string] – 用户登录后的会话ID
			Password[string] – 用户设置的密码,建议在客户端通过MD5加密传输
		返回值:
			UserId[String] – 用户ID
		"""
		if not self.__has_params(data, ('UserKey', 'Password')):
			raise tornado.web.HTTPError(400, '参数Error')

		userId = UserService.user_password(data)
		self.__reponseJSON({
			'UserId' : userId,
		})
Example #39
0
    def user_password(self, data):
        """
		更改用户登录密码
		参数:
			UserKey[string] – 用户登录后的会话ID
			Password[string] – 用户设置的密码,建议在客户端通过MD5加密传输
		返回值:
			UserId[String] – 用户ID
		"""
        if not self.__has_params(data, ('UserKey', 'Password')):
            raise tornado.web.HTTPError(400, '参数Error')

        userId = UserService.user_password(data)
        self.__reponseJSON({
            'UserId': userId,
        })
Example #40
0
    def user_validate(self, data):
        """
		发送短信验证码
		参数:
			Mobile[string] – 用户手机号码
			Device[string] – 设备名称
		返回值:
			ValidityDate[date] – 验证码有效日期。
		"""
        if not self.__has_params(data, ('Mobile', 'Device')):
            raise tornado.web.HTTPError(400, '参数Error')

        validityDate = UserService.user_validate(data)

        self.__reponseJSON({
            'ValidityDate': validityDate,
        })
Example #41
0
	def user_validate(self, data):
		"""
		发送短信验证码
		参数:
			Mobile[string] – 用户手机号码
			Device[string] – 设备名称
		返回值:
			ValidityDate[date] – 验证码有效日期。
		"""
		if not self.__has_params(data, ('Mobile', 'Device')):
			raise tornado.web.HTTPError(400, '参数Error')

		validityDate = UserService.user_validate(data)

		self.__reponseJSON({ 
			'ValidityDate'  : validityDate,
		})
Example #42
0
def space_list(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()

	spaceListInstance = db.list('SELECT * FROM `space` WHERE `user_id` = %s ORDER BY `index` ASC', (userId))
	
	results = []
	for space in spaceListInstance:
		results.append({
				'Id': space['id'],
				'Name': space['name'],
			})

	return {
		'Count': len(results),
		'Spaces': results,
	}
Example #43
0
def space_unauthorize(data):
	userId = UserService.user_id(data['UserKey'])
	spaceInstance = space_get(data.get('Id', ''))
	if userId == spaceInstance['user_id']:
		db = MySQL()
		result = db.delete("DELETE FROM `space_authorize` WHERE `space_id`=%s AND `user_id`=%s", 
						(data.get('Id', ''), data.get('UserId', '')))
		db.end()
		if result > 0:
			return {
				'Id': data.get('Id', ''),
				'UserId': data.get('UserId', ''),
			}
		else:
			raise Exception('删除失败或授权不存在')
	else:
		raise Exception('没有权限或空间不存在')
Example #44
0
def invite_deal(data):
	"""
	接受邀请
	参数:
		UserKey[string] – 用户会话ID
		Code[string] – 邀请码
	返回值:
		Code[string] – 邀请码
	"""
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()
	result = db.update("UPDATE `invite` SET `is_deal` = 1, `deal_date` = now(), `deal_user_id` = %s WHERE `id` = %s AND `is_deal` = 0", (userId, data.get('Code', None)))
	db.end()
	if result > 0:
		return {
			'Code': data.get('Code', None)
		}
	else:
		raise Exception('邀请码不存在或已处理')
Example #45
0
def space_create(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()

	spaceId = Utils.UUID()
	result = db.save("INSERT INTO `space` (`id`, `user_id`, `name`) VALUES (%s,%s,%s)", 
					(spaceId, userId, data.get('Name', '')))
	db.end()

	space_reindex({
			'UserKey': data['UserKey'],
			'Id': spaceId,
			'After': data.get('After', ''),
		})

	return {
		'Id': spaceId,
		'Name': data.get('Name', '')
	}
Example #46
0
def share_list(data):
	"""
	获取分享列表
	方法:
		share_list
	参数:
		UserKey[string] –用户登录后的会话ID。
		Offset[long] – 列表起始位置。
		Max[long] – 列表最大条数
	返回值:
		Count[long] – 列表数量(全部)
		Offset[long] – 列表起始位置。
		Max[long] – 列表最大条数
		Results[Array] – 视频对象列表,视频对象定义如下:
			to_time[date] – 创作日期
			to_name[date] – 分享日期
			VID[string] – 视频ID
	"""
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()

	offset = data.get('Offset', 0)
	listMax = min(100, data.get('Max', 10))
	count = long(db.get('SELECT COUNT(*) as c FROM `share_list` WHERE (`owner_id` = %s and flag=0) or (`to_user_id` = %s and flag = 1)', (userId,userId)).get('c'))

	results = []

	shareListInstance = db.list('SELECT * FROM `share_list` WHERE (`owner_id` = %s and flag=0) or (`to_user_id` = %s and flag = 1) ORDER BY `to_time` DESC LIMIT %s,%s', (userId, userId, offset, listMax))

	for shareInstance in shareListInstance:
		results.append({
			'ToTime'    : shareInstance['to_time'],
			'ToName'    : shareInstance['to_name'],
			'VID'       : shareInstance['video_id'],
			'Flag'      : shareInstance['flag'],
		})

	return {
		'Count'     : count,
		'Offset'    : offset,
		'Max'       : listMax,
		'Results'   : results,
	}
Example #47
0
def space_res_unrelation(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()
	
	# TEST AUTHORIZE
	if __test_auth_edit(userId, data.get('Id', '')) > 0:
		result = db.delete("DELETE FROM `space_resource`  WHERE `space_id`=%s AND `res_type`=%s AND `res_id`=%s", 
						(data.get('Id', ''), data.get('ResType', ''), data.get('ResId', '')))
		db.end()
		if result > 0:
			return {
				'Id': data.get('Id', ''),
				'ResType': data.get('ResType', ''),
				'ResId': data.get('ResId', ''),
			}
		else:
			raise Exception('删除失败或资源不存在')
	else:
		raise Exception('没有权限或空间不存在')
Example #48
0
def space_res_relation(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()
	
	# TEST AUTHORIZE
	if __test_auth_edit(userId, data.get('Id', '')) > 0:
		newId = Utils.UUID()
		result = db.update("INSERT INTO `space_resource` (`id`, `space_id`, `owner_id`, `res_type`, `res_id`, `order_field1`, `order_field2`, `order_field3`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)", 
						(newId, data.get('Id', ''), userId, data.get('ResType', ''), data.get('ResId', ''), data.get('OrderField1', None), data.get('OrderField2', None), data.get('OrderField3', None)))
		db.end()

		if result > 0:
			return {
				'Id': data.get('Id', ''),
				'ResType': data.get('ResType', ''),
				'ResId': data.get('ResId', ''),
			}
		else:
			raise Exception('更新失败或空间不存在')
	else:
		raise Exception('没有权限或空间不存在')
Example #49
0
def space_res_order(data):
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()
	
	# TEST AUTHORIZE
	if __test_auth_edit(userId, data.get('Id', '')) > 0:
		newId = Utils.UUID()
		result = db.update("UPDATE `space_resource` SET `order_field1`=%s, `order_field2`=%s, `order_field3`=%s WHERE `space_id`=%s AND `res_type`=%s AND `res_id`=%s", 
						(data.get('OrderField1', None), data.get('OrderField2', None), data.get('OrderField3', None), data.get('Id', ''), userId, data.get('ResType', ''), data.get('ResId', '')))
		db.end()

		if result > 0:
			return {
				'Id': data.get('Id', ''),
				'ResType': data.get('ResType', ''),
				'ResId': data.get('ResId', ''),
			}
		else:
			raise Exception('更新失败或空间不存在')
	else:
		raise Exception('没有权限或空间不存在')
Example #50
0
def video_remove(data):
	"""
	删除视频
	方法:
		video_remove
	参数:
		UserKey[string] –用户登录后的会话ID。
		VID[string] – 分配的视频ID
	返回值:
		VID[string] – 删除的视频ID
	"""
	userId = UserService.user_id(data['UserKey'])
	db = MySQL()

	videoInstance = db.get('SELECT * FROM `video` WHERE `owner_id`=%s and `id` = %s', (userId, data['VID']))
	if not videoInstance:
		raise Exception("视频不存在.")

	db.delete("DELETE FROM `video` WHERE `owner_id`=%s and `id` = %s", (userId, data['VID']))
	db.end()

	return {'VID': data['VID']}
Example #51
0
def video_update(data):
	"""
	更新视频信息
	参数:
		UserKey[string] –用户登录后的会话ID。
		VID[string] – 视频ID
		Title[string] – 视频标题
		Author[string] – 分享者/创作者名称
		CreateTime[date] – 创作日期
		Category[string] – 视频分类
		Describe[string] – 视频描述
		Tag[string] – 视频标签,标签内容有半角“,”(逗号)分割
		AddrStr[string] - 视频位置信息
		Longitude[float] - 视频位置 - 经度
		Latitude[float] - 视频位置 - 纬度
	返回值:
		VID[string] – 视频ID
	"""

	userId = UserService.user_id(data['UserKey'])
	videoId = data.get('VID', '')

	db = MySQL()
	db.update("UPDATE `video` set `title` = %s, `author` = %s, `create_date` = %s, `category` = %s, `describe` = %s, `tag` = %s  WHERE `id` = %s AND `owner_id` = %s ", (
		data.get('Title', ''),
		data.get('Author', ''),
		data.get('CreateTime', ''),
		data.get('Category', ''),
		data.get('Describe', ''),
		data.get('Tag', ''),
		videoId,
		userId))

	db.end()
		
	return data.get('VID', '')