Ejemplo n.º 1
0
	def json(self, argv):
		self.manager 	= MovieManager(self.site, self.module)
		action 			= self.site.get_argument('action', None)
		if action == 'setting':
			post_id 	= self.site.get_argument('post', None)
			if post_id:
				if type(post_id) == str and re.match(r'[a-z0-9]{24}', post_id):
					post_id 		= ObjectId(post_id)

				mv_setting = self.site.get_argument('setting', None)

				if mv_setting == "complete":
					mv_setting = "mvc"
				elif mv_setting == "remove":
					mv_setting = "mvd"
				result = yield self.manager.set_user_view_post(post_id, mv_setting)
				if result:
					return '{"error":0,"success":1}'
		else:
			post_id 	= self.site.get_argument('post', None)
			if not post_id:
				posts_view 	= yield self.manager.get_user_view_post()
				if posts_view:
					post_id = []
					for p in posts_view:
						if 'post_id' in p:
							post_id.append(p['post_id'])
			###
			posts = yield self.post_json(post_id)
			posts_argv 	= []
			for post in posts:
				posts_argv.append(self.post_argv(post))
					
			return {"post": posts_argv}
		return '{"error":1,"success":0}'
Ejemplo n.º 2
0
    def json(self, argv):
        self.manager = MovieManager(self.site, self.module)
        # action 			= self.site.get_argument('action', None)
        # get cache store
        cache_string = "%s" % str(self.module['_id'])
        result = yield self.site.cache.get(cache_string)
        if result and 'data' in result:
            return result['data']
        else:
            posts = yield self.post_json()
            result = {"post": posts}

            # set cache store
            self.site.cache.set(cache_string, result, self.cache_time)
            return result
Ejemplo n.º 3
0
class Module(ModuleBase):
	"""docstring for Module"""
	def __init__(self):
		super(Module, self).__init__()
		self.script.extend([
			"/static/js/jquery.lazyload.min.js",
		])

	@gen.coroutine
	def form(self, argv):
		# generic template for json data
		argv 			= self.post_argv()
		template 		= {
			"post": self.site.render_string(self.module['path'] + "post.html", argv=[argv]).decode("utf-8"),
		}
		return self.site.render_string(
			self.module['path'] + "form.html",
			module 	= self.module,
			argv 	= {
				"template": b64encode(escape.json_encode(template).encode("utf-8")),
				"post": '{%% raw module["%s"]["post"] %%}' % self.module['_id']
			}
		), True
	@gen.coroutine
	def form_post(self, argv):
		json_argv 		= yield self.json(argv)
		post_form 		= self.site.render_string(self.module['path'] + "post.html", argv=json_argv['post'])
		return {"post": post_form}

	@gen.coroutine
	def json(self, argv):
		self.manager 	= MovieManager(self.site, self.module)
		action 			= self.site.get_argument('action', None)
		if action == 'setting':
			post_id 	= self.site.get_argument('post', None)
			if post_id:
				if type(post_id) == str and re.match(r'[a-z0-9]{24}', post_id):
					post_id 		= ObjectId(post_id)

				mv_setting = self.site.get_argument('setting', None)

				if mv_setting == "complete":
					mv_setting = "mvc"
				elif mv_setting == "remove":
					mv_setting = "mvd"
				result = yield self.manager.set_user_view_post(post_id, mv_setting)
				if result:
					return '{"error":0,"success":1}'
		else:
			post_id 	= self.site.get_argument('post', None)
			if not post_id:
				posts_view 	= yield self.manager.get_user_view_post()
				if posts_view:
					post_id = []
					for p in posts_view:
						if 'post_id' in p:
							post_id.append(p['post_id'])
			###
			posts = yield self.post_json(post_id)
			posts_argv 	= []
			for post in posts:
				posts_argv.append(self.post_argv(post))
					
			return {"post": posts_argv}
		return '{"error":1,"success":0}'

	def post_argv(self, post= None):
		if post:			# title
			if 'title_seo' in post['post']:
				title_seo 		= escape.xhtml_escape(post['post']['title_seo'])
			else:
				title_seo 	= ''

			if 'title' in post['post']:
				title 		= escape.xhtml_escape("%s (%s)" % (post['post']['title'], post['post']['year']))
			else:
				title 		= ""

			# poster
			if 'poster' in post['post']:
				poster 		= escape.xhtml_escape(post['post']['poster'])
			else:
				poster 		= ""

			###
			argv 	= {
				"id" 				: str(post['_id']),
				"title"				: title,
				"subtitle"			: escape.xhtml_escape(post['post']['subtitle']),
				"poster" 			: poster,
				"link" 				: "%s/%s/%s/%s.html" % (self.site.domain_root, self.module['setting']['server']['page_view'], post['_id'], title_seo),
			}
		else:
			argv 	= {
				"id" 				: '{{ id }}',
				"title"				: '{{ title }}',
				"subtitle"			: '{{ subtitle }}',
				"poster" 			: '{{ poster }}',
				"link"				: '{{ link }}'
			}
		return argv

	@gen.coroutine
	def post_json(self, post_id, sort=[('access.time', 1)], count=10):
		### post id
		if type(post_id) == str:
			post_id =[ObjectId(p) for p in post_id.split(',') if re.match(r'[a-z0-9]{24}', p)]

		if type(post_id) == list:
			post_id = {'$in': post_id}
		###
		cursor 	= self.site.db.post.find({
			'_id': post_id,
			'site_id': self.module['site_id'],
			'format': 'mv',
			'access.type': 'public'
		}, {'post': 1}).sort(sort)
		posts 	= yield cursor.to_list(length=count)
		if type(post_id) == dict and '$in' in post_id:
			result = []
			for p in post_id['$in']:
				for rp in posts:
					if p == rp['_id']:
						result.append(rp)
						break
			return result
		return posts
Ejemplo n.º 4
0
class Module(ModuleBase):
    """docstring for Module"""
    def __init__(self):
        super(Module, self).__init__()
        self.script.extend([
            "/static/jwplayer/jwplayer.js",
            # "/static/jwplayer/jwpsrv.js"
        ])

    @gen.coroutine
    def form(self, argv):
        post_argv = self.post_argv()
        template = {
            "post":
            self.site.render_string(self.module['path'] + "post.html",
                                    argv=post_argv,
                                    module=self.module).decode("utf-8")
        }
        return self.site.render_string(
            self.module['path'] + "form.html",
            module=self.module,
            form={
                "template":
                b64encode(escape.json_encode(template).encode("utf-8")),
                "post": '{%% raw module["%s"]["post"] %%}' % self.module['_id']
            }), True

    @gen.coroutine
    def form_post(self, argv):
        json_argv = yield self.json(argv)
        if 'post' in json_argv and json_argv['post']:
            post_form = self.site.render_string(self.module['path'] +
                                                "post.html",
                                                argv=json_argv['post'],
                                                module=self.module)
        else:
            post_form = "Nội dung đang chờ kiểm duyệt hoặc không tồn tại!"
        return {"post": post_form}

    @gen.coroutine
    def json(self, argv):
        self.manager = MovieManager(self.site, self.module)

        action = self.site.get_argument('action', None)
        post_id = self.site.get_argument('post', None)

        if post_id == None:
            try:
                post_id = argv[0]
            except:
                pass

        if type(post_id) == str and re.match(r'[a-z0-9]{24}', post_id):
            post_id = ObjectId(post_id)

        if post_id:
            # update movie track
            post_track = self.site.get_argument('track', None)
            if post_track:
                if len(post_track) == 24:
                    track_id = ObjectId(post_track)
                self.manager.set_user_view_post(track_id)

                # set movie view count
                self.manager.set_post_view(post_id)

            # part view
            if action == "part":
                # lock some request failure
                if self.site.request.headers.get(
                        'X-Requested-With'
                ) == 'XMLHttpRequest' and self.site.site_db['domain'][
                        0] in self.site.request.headers.get('Referer')[:50]:
                    mv_chap_index = self.site.get_argument('c-i', 0)
                    mv_server_index = self.site.get_argument('s-i', 0)
                    result = yield self.manager.get_movie_part(
                        post_id, mv_chap_index, mv_server_index)
                    if result:
                        return {"post": result}

            # save last viewing movie chap/server/part
            elif action == "viewing":
                mv_chap = self.site.get_argument('mv-chap', -1)
                mv_server = self.site.get_argument('mv-server', -1)
                mv_part = self.site.get_argument('mv-part', -1)
                mv_seek = self.site.get_argument('mv-seek', 0)
                ###
                try:
                    mv_chap = int(mv_chap)
                except:
                    mv_chap = -1
                ###
                try:
                    mv_server = int(mv_server)
                except:
                    mv_server = -1
                ###
                try:
                    mv_part = int(mv_part)
                except:
                    mv_part = -1
                ###
                try:
                    mv_seek = float(mv_seek)
                except:
                    mv_seek = -1
                ###
                # print(post_id, mv_chap, mv_server, mv_part, mv_seek)
                self.manager.get_user_view_post_lasted(post_id, mv_chap,
                                                       mv_server, mv_part,
                                                       mv_seek)
                return '{"error":0,"success":1}'
            elif action == "rating":
                mv_rate = self.site.get_argument('rate', None)
                if mv_rate:
                    # print('rate', mv_rate)
                    mv_rate = int(mv_rate)
                    self.manager.set_post_rating(post_id, mv_rate)
                    return '{"error":0,"success":1}'
            elif action == "report":
                mv_report = self.site.get_argument('report', None)
                mv_content = self.site.get_argument('content', None)
                obj = report.SiteReport(self.site)
                # fork
                obj.set(mv_report, mv_content)
                return '{"error":0,"success":1}'
            else:
                post = yield self.post_json(argv[0])
                if post:
                    argv = self.post_argv(post)

                    # facebook graph
                    self.site.graph['og:url'] = argv['link']
                    self.site.graph['og:title'] = "%s - %s - %s" % (
                        argv['title'], self.site.site_db['setting']['title'],
                        self.site.site_db['domain'])
                    if len(argv['description']) > 10:
                        self.site.graph[
                            'og:description'] = escape.xhtml_escape(
                                "Xem Phim %s, %s" %
                                (argv['title'], argv['description'][:300]))

                    if 'poster' in argv:
                        image = argv['poster']
                    # elif 'trailer' in post['post']['trailer']:
                    # 	image 		= "http://i1.ytimg.com/vi/%s/hqdefault.jpg" % post['post']['content']['video'].split('youtube.com/watch?v=',2)[1].split(r'/[#|\?]/', 1)[0]
                    else:
                        image = None
                    if image:
                        self.site.graph['og:image'] = [
                            ["og:image", image], ["og:image:width", "1500"],
                            ["og:image:height", "1500"]
                        ]

                else:
                    argv = None
                return {"post": argv}
        return '{"error":1,"success":0}'

    def post_argv(self, post=None):
        if post:
            # search page
            searcher = "/%s/" % ("search")

            ###
            argv = {
                "id": str(post['_id']),
            }

            # title
            if 'title' in post['post']:
                argv['title'] = escape.xhtml_escape(
                    "%s - %s (%s)" %
                    (post['post']['title'], post['post']['subtitle'],
                     post['post']['year']))
            else:
                argv['title'] = ""

            # poster
            if 'poster' in post['post']:
                argv['poster'] = escape.xhtml_escape(post['post']['poster'])
            else:
                argv['poster'] = ""

            # director
            if 'director' in post['post']:
                director = []
                for dir in post['post']['director']:
                    director.append(
                        '<a href="%s?director=%s" site-goto="">%s</a>' %
                        (searcher, escape.url_escape(dir), dir))
                argv['director'] = ', '.join(director)
            else:
                argv['director'] = ""

            # stars
            if 'stars' in post['post']:
                stars = []
                for star in post['post']['stars']:
                    stars.append('<a href="%s?stars=%s" site-goto="">%s</a>' %
                                 (searcher, escape.url_escape(star), star))
                argv['stars'] = ', '.join(stars)
            else:
                argv['stars'] = ""

            # description
            if 'description' in post['post']:
                argv['description'] = post['post']['description']
            else:
                argv['description'] = ""

            # country
            if 'country' in post['post']:
                argv[
                    'country'] = '<a href="%s?country=%s" site-goto="">%s</a>' % (
                        searcher, escape.url_escape(
                            post['post']['country']), post['post']['country'])
            else:
                argv['country'] = ""

            # year
            if 'year' in post['post']:
                argv['year'] = '<a href="%s?year=%s" site-goto="">%s</a>' % (
                    searcher, escape.url_escape(
                        post['post']['year']), post['post']['year'])
            else:
                argv['year'] = ""

            # length
            if 'length' in post['post'] and type(
                    post['post']['length']) == dict:
                obj = post['post']['length']
                if obj['type'] == "long":
                    # length = "%s/%s tập" % (obj['current'], obj['count'])
                    argv['length'] = "%s tập" % obj['count']
                    if 'current' in obj:
                        argv['length'] = "%s/%s" % (obj['current'],
                                                    argv['length'])
                else:
                    argv['length'] = "%s phút" % obj['count']
            else:
                argv['length'] = ""

            # category
            if 'category' in post['post']:
                category = []
                for cate in post['post']['category']:
                    category.append(
                        '<a href="%s?category=%s" site-goto="">%s</a>' %
                        (searcher, escape.url_escape(cate), cate))
                argv['category'] = ', '.join(category)
            else:
                argv['category'] = ""

            # lastview
            if 'lastview' in post:
                argv['lastview'] = "%s|%s|%s|%s" % (
                    post['lastview']['chap'], post['lastview']['server'],
                    post['lastview']['part'], post['lastview']['seek'])
            else:
                argv['lastview'] = ""

            # seo title
            if 'title_seo' in post['post']:
                title_seo = escape.xhtml_escape(post['post']['title_seo'])
            else:
                title_seo = ''
            argv["link"] = "%s/%s/%s/%s.html" % (
                self.site.domain_root, self.site.site_db['page']['name'],
                post['_id'], title_seo)

            # image background
            if 'image' in post['post'] and post['post']['image']:
                argv['background'] = post['post']['image'][0]
            else:
                argv[
                    'background'] = 'https://lh6.googleusercontent.com/-UCQ1vCljDNk/VD5yhNY3cBI/AAAAAAAAAFM/ubsvrbtVq3Q/s1200/286652.jpg'

            # rating
            if 'rating' in post:
                # rating 	= post['rating']
                argv['rating_count'] = int(post['rating']['count'])
                argv['rating_average'] = int(post['rating']['average'])
            else:
                argv['rating_count'] = 0
                argv['rating_average'] = 0

            # movie chaps
            chaps = []
            if 'chap' in post['post']:
                for chap in post['post']['chap']:
                    o_chap = {"name": chap['name'], "server": []}
                    for server in chap['server']:
                        o_chap['server'].append({"name": server['name']})
                    chaps.append(o_chap)
            argv['chap'] = b64encode(
                escape.json_encode(chaps).encode("utf-8")).decode("utf-8")
        else:
            argv = {
                "id": '{{ id }}',
                "title": '{{ title }}',
                "poster": '{{ poster }}',
                "director": '{{ director }}',
                "stars": '{{ stars }}',
                "description": '{{ description }}',
                "country": '{{ country }}',
                "year": '{{ year }}',
                "length": '{{ length }}',
                "category": '{{ category }}',
                "background": '{{ background }}',
                "chap": '{{ chap }}',
                "lastview": '{{ lastview }}',
                "rating_count": '{{ rating_count }}',
                "rating_average": '{{ rating_average }}',
                "link": '{{ link }}',
            }
        return argv

    @gen.coroutine
    def post_json(self, post_id):
        if type(post_id) == str and re.match(r'[a-z0-9]{24}', post_id):
            post_id = ObjectId(post_id)

        if type(post_id) == ObjectId:
            query = {
                '_id': post_id,
                'site_id': self.module['site_id'],
                'format': 'mv'
            }

            if 'access' in self.module['setting']['server']:
                query['access.type'] = self.module['setting']['server'][
                    'access']
            # print(query)
            post = yield self.manager.db.find_one(
                query,
                {
                    'rating.count': 1,
                    'rating.average': 1,
                    'post.title': 1,
                    'post.subtitle': 1,
                    'post.title_seo': 1,
                    'post.poster': 1,
                    'post.director': 1,
                    'post.stars': 1,
                    'post.description': 1,
                    'post.country': 1,
                    'post.year': 1,
                    'post.length': 1,
                    'post.category': 1,
                    # 'post.image': {"$slice": [0,1]},
                    'post.image': 1,
                    'post.chap.name': 1,
                    'post.chap.server.name': 1,
                })
            # print(post)
            if post:
                lastview = yield self.manager.get_user_view_post_lasted(
                    post['_id'])
                if lastview and 'data' in lastview:
                    post['lastview'] = lastview['data']
            return post
Ejemplo n.º 5
0
    def json(self, argv):
        self.manager = MovieManager(self.site, self.module)

        action = self.site.get_argument('action', None)
        post_id = self.site.get_argument('post', None)

        if post_id == None:
            try:
                post_id = argv[0]
            except:
                pass

        if type(post_id) == str and re.match(r'[a-z0-9]{24}', post_id):
            post_id = ObjectId(post_id)

        if post_id:
            # update movie track
            post_track = self.site.get_argument('track', None)
            if post_track:
                if len(post_track) == 24:
                    track_id = ObjectId(post_track)
                self.manager.set_user_view_post(track_id)

                # set movie view count
                self.manager.set_post_view(post_id)

            # part view
            if action == "part":
                # lock some request failure
                if self.site.request.headers.get(
                        'X-Requested-With'
                ) == 'XMLHttpRequest' and self.site.site_db['domain'][
                        0] in self.site.request.headers.get('Referer')[:50]:
                    mv_chap_index = self.site.get_argument('c-i', 0)
                    mv_server_index = self.site.get_argument('s-i', 0)
                    result = yield self.manager.get_movie_part(
                        post_id, mv_chap_index, mv_server_index)
                    if result:
                        return {"post": result}

            # save last viewing movie chap/server/part
            elif action == "viewing":
                mv_chap = self.site.get_argument('mv-chap', -1)
                mv_server = self.site.get_argument('mv-server', -1)
                mv_part = self.site.get_argument('mv-part', -1)
                mv_seek = self.site.get_argument('mv-seek', 0)
                ###
                try:
                    mv_chap = int(mv_chap)
                except:
                    mv_chap = -1
                ###
                try:
                    mv_server = int(mv_server)
                except:
                    mv_server = -1
                ###
                try:
                    mv_part = int(mv_part)
                except:
                    mv_part = -1
                ###
                try:
                    mv_seek = float(mv_seek)
                except:
                    mv_seek = -1
                ###
                # print(post_id, mv_chap, mv_server, mv_part, mv_seek)
                self.manager.get_user_view_post_lasted(post_id, mv_chap,
                                                       mv_server, mv_part,
                                                       mv_seek)
                return '{"error":0,"success":1}'
            elif action == "rating":
                mv_rate = self.site.get_argument('rate', None)
                if mv_rate:
                    # print('rate', mv_rate)
                    mv_rate = int(mv_rate)
                    self.manager.set_post_rating(post_id, mv_rate)
                    return '{"error":0,"success":1}'
            elif action == "report":
                mv_report = self.site.get_argument('report', None)
                mv_content = self.site.get_argument('content', None)
                obj = report.SiteReport(self.site)
                # fork
                obj.set(mv_report, mv_content)
                return '{"error":0,"success":1}'
            else:
                post = yield self.post_json(argv[0])
                if post:
                    argv = self.post_argv(post)

                    # facebook graph
                    self.site.graph['og:url'] = argv['link']
                    self.site.graph['og:title'] = "%s - %s - %s" % (
                        argv['title'], self.site.site_db['setting']['title'],
                        self.site.site_db['domain'])
                    if len(argv['description']) > 10:
                        self.site.graph[
                            'og:description'] = escape.xhtml_escape(
                                "Xem Phim %s, %s" %
                                (argv['title'], argv['description'][:300]))

                    if 'poster' in argv:
                        image = argv['poster']
                    # elif 'trailer' in post['post']['trailer']:
                    # 	image 		= "http://i1.ytimg.com/vi/%s/hqdefault.jpg" % post['post']['content']['video'].split('youtube.com/watch?v=',2)[1].split(r'/[#|\?]/', 1)[0]
                    else:
                        image = None
                    if image:
                        self.site.graph['og:image'] = [
                            ["og:image", image], ["og:image:width", "1500"],
                            ["og:image:height", "1500"]
                        ]

                else:
                    argv = None
                return {"post": argv}
        return '{"error":1,"success":0}'
Ejemplo n.º 6
0
class Module(ModuleBase):
	# """docstring for Module"""
	def __init__(self):
		super(Module, self).__init__()
		self.script.extend([
			"/static/js/jquery.lazyload.min.js",
		])

	@gen.coroutine
	def form(self, argv, default = None):
		# generic template for json data
		post_argv 		= self.post_argv()
		info_argv 		= self.info_argv()
		template 		= {
			"post": self.site.render_string(self.module['path'] + "post.html", argv=[post_argv]).decode("utf-8"),
			"info": self.site.render_string(self.module['path'] + "info.html", argv=info_argv).decode("utf-8")
		}
		form_argv = {
				"template": b64encode(escape.json_encode(template).encode("utf-8")),
				"post": '{%% raw module["%s"]["post"] %%}' % self.module['_id']
			}
		if default:
			form_argv.update(default)

		return self.site.render_string(
			self.module['path'] + "form.html",
			module 	= self.module,
			argv 	= form_argv
		), True

	@gen.coroutine
	def form_post(self, argv):
		if 'init_post' in self.module['setting']['server'] and not self.module['setting']['server']['init_post']:
			post_form 		= ''
		else:
			json_argv 		= yield self.json(argv)
			post_form 		= self.site.render_string(self.module['path'] + "post.html", argv=json_argv['post'])
		return {"post": post_form}

	@gen.coroutine
	def json(self, argv):
		self.manager 	= MovieManager(self.site, self.module)
		
		action 		= self.site.get_argument('action', None)
		search 		= self.site.get_argument('search', None)
		post_skip 	= self.site.get_argument('skip', None)
		post_tab 	= self.site.get_argument('tab', None)
		post_count 	= int(self.site.get_argument('count', 0))
		post_sort 	= False
		
		if search:
			post_id 	= yield self.manager.search_title_seo(search, post_count)
			post_sort 	= True
		else:
			post_id 	= self.site.get_argument('post', None)
			if post_id == None:
				try:
					post_id = argv[0]
				except:
					pass
			if type(post_id) == str and len(post_id) == 24:
				post_id 	= ObjectId(post_id)

		if action == "info":
			output = {
				'post.title':1,
				'post.subtitle':1,
				'post.poster':1,
				'post.director':1,
				'post.stars':1,
				'post.description':1,
				'post.country':1,
				'post.year':1,
				'post.length':1,
				'post.category':1,
				'post.title_seo':1,
				'post.trailer':1,
				'post.imdb':1,
				# 'view.count':1,
			}
		else:
			output = {
				'post.title':1,
				'post.subtitle':1,
				'post.title_seo':1,
				'post.poster':1,
				'post.year':1,
				'post.imdb':1,
				'post.length':1,
				# 'rating.count': 1,
				# 'rating.average': 1,
				'view.count':1,
			}

		posts 	= yield self.post_json(
			post_id		= post_id,
			post_skip	= post_skip,
			post_tab 	= post_tab,
			post_count 	= post_count,
			post_sort 	= post_sort,
			output 		= output,
		)
		posts_argv 	= []
		if action == "info":
			for post in posts:
				posts_argv.append(self.info_argv(post))
		else:
			for post in posts:
				posts_argv.append(self.post_argv(post))
		return {"post": posts_argv, "form": {'search': search}}

	def post_argv(self, post= None):
		if post and 'post' in post:
			argv 	= {
				"id" 			: str(post['_id']),
				"title"			: escape.xhtml_escape("%s (%s)" % (post['post']['title'], post['post']['year'])),
				"subtitle" 		: escape.xhtml_escape(post['post']['subtitle']),
			}

			if 'poster' in post['post']:
				argv['poster'] 	= post['post']['poster']
			else:
				argv['poster'] 	= ''

			# seo title generic
			if 'title_seo' in post['post']:
				title_seo 	= post['post']['title_seo']
			else:
				title_seo 	= function.seo_encode('%s-%s-%s' % (post['post']['title'], post['post']['subtitle'], post['post']['year']))
			argv["link"] 	= "%s/%s/%s/%s.html" % (self.site.domain_root, self.module['setting']['server']['page_view'], post['_id'], escape.url_escape(title_seo))
			
			# imdb
			if 'imdb' in post['post']:
				argv['imdb'] 	= post['post']['imdb']
			else:
				argv['imdb'] 	= 0

			# # rating
			# if 'rating' in post:
			# 	# rating 	= post['rating']
			# 	argv['rating_count'] 	= int(post['rating']['count'])
			# 	argv['rating_average'] 	= int(post['rating']['average'])
			# else:
			# 	argv['rating_count'] 	= 0
			# 	argv['rating_average'] 	= 0

			# view count
			if 'view' in post and 'count' in post['view']:
				argv['view_count'] = post['view']['count']
			else:
				argv['view_count'] = 0

			# length
			try:
				argv['length'] 		= "%s/%s" % (post['post']['length']['current'], post['post']['length']['count'])
				argv['length_type'] = post['post']['length']['type']
			except:
				argv['length'] 		= ''
				argv['length_type'] = 'short'
		else:
			argv 	= {
				"id" 				: '{{ id }}',
				"title"				: '{{ title }}',
				"subtitle"			: '{{ subtitle }}',
				"poster" 			: '{{ poster }}',
				"link" 				: '{{ link }}',
				# "rating_count"		: '{{ rating_count }}',
				# "rating_average"	: '{{ rating_average }}',
				"view_count"		: '{{ view_count }}',
				"length"			: '{{ length }}',
				"length_type"		: '{{ length_type }}',
				"imdb"				: '{{ imdb }}'
			}
		return argv

	def info_argv(self, post= None):
		if post:
			# search page
			searcher 	= "/%s/" % ("search")
			
			# # title
			# if 'title' in post['post']:
			# 	title 		= escape.xhtml_escape("%s - %s (%s)" % (post['post']['title'], post['post']['subtitle'], post['post']['year']))
			# else:
			# 	title 		= ""

			# poster
			if 'poster' in post['post']:
				poster 		= escape.xhtml_escape(post['post']['poster'])
			else:
				poster 		= ""

			# director
			if 'director' in post['post']:
				director 	= []
				for dir in post['post']['director']:
					director.append('<a href="%s?director=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(dir), dir))
				director 	= ', '.join(director)
			else:
				director 	= ""

			# stars
			if 'stars' in post['post']:
				stars 	= []
				for star in post['post']['stars']:
					stars.append('<a href="%s?stars=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(star), star))
				stars 	= ', '.join(stars)
			else:
				stars 	= ""

			# description
			if 'description' in post['post']:
				description 	= post['post']['description']
			else:
				description 	= ""

			# country
			if 'country' in post['post']:
				country 	= '<a href="%s?country=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(post['post']['country']), post['post']['country'])
			else:
				country 	= ""

			# year
			if 'year' in post['post']:
				year 	= '<a href="%s?year=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(post['post']['year']), post['post']['year'])
			else:
				year 	= ""

			# length
			if 'length' in post['post']:
				length 	= post['post']['length']
				if type(length) == dict:
					length 	= "%s %s" % (length['count'], "tập" if length['type'] == "long" else "phút")
			else:
				length 	= ""

			# category
			if 'category' in post['post']:
				category 	= []
				for cate in post['post']['category']:
					category.append('<a href="%s?category=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(cate), cate))
				category 	= ', '.join(category)
			else:
				category 	= ""

			# seo title
			if 'title_seo' in post['post']:
				title_seo 		= escape.xhtml_escape(post['post']['title_seo'])
			else:
				title_seo 	= ''

			# trailer
			if 'trailer' in post['post']:
				trailer 	= []
				regex 		= re.compile("(\?v\=|\/v\/|\.be\/)(.*?)(\?|&|#|$)")
				for t in post['post']['trailer']:
					if not '/embed/' in t:
						r = regex.search(t)
						if r:
							t = 'https://www.youtube.com/embed/%s' % r.groups()[1]
					trailer.append('<div class="embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item" src="%s"></iframe></div>' % escape.xhtml_escape(t))
				trailer 	= ''.join(trailer)
			else:
				trailer 	= ''

			# imdb
			if 'imdb' in post['post']:
				imdb 	= post['post']['imdb']
			else:
				imdb 	= 0

			###
			argv 	= {
				"id" 				: str(post['_id']),
				"title"				: escape.xhtml_escape("%s (%s)" % (post['post']['title'], post['post']['year'])),
				"subtitle" 			: escape.xhtml_escape(post['post']['subtitle']),
				"poster" 			: poster,
				"director" 			: director,
				"stars" 			: stars,
				"description" 		: description,
				"country" 			: country,
				"year" 				: year,
				"length" 			: length,
				"category" 			: category,
				"trailer"			: trailer,
				"imdb"				: imdb,
				"link" 				: "%s/%s/%s/%s.html" % (self.site.domain_root, self.module['setting']['server']['page_view'], post['_id'], title_seo),
			}
		else:
			argv 	= {
				"id" 				: '{{ id }}',
				"title"				: '{{ title }}',
				"subtitle"			: '{{ subtitle }}',
				"poster" 			: '{{ poster }}',
				"director" 			: '{{ director }}',
				"stars" 			: '{{ stars }}',
				"description" 		: '{{ description }}',
				"country" 			: '{{ country }}',
				"year" 				: '{{ year }}',
				"length" 			: '{{ length }}',
				"category" 			: '{{ category }}',
				"trailer"			: '{{ trailer }}',
				"imdb"				: '{{ imdb }}',
				"link"				: '{{ link }}'
			}
		return argv

	@gen.coroutine
	def post_json(
		self,
		post_id 	= None,
		post_skip 	= None,
		post_tab 	= None,
		post_count 	= 0,
		post_sort 	= False,
		sort 		= [('access.time', -1)],
		output 		= None,
	):
		#  limit count of post
		if not post_count and 'count' in self.module['setting']['server']:
			post_count = self.module['setting']['server']['count']
		try:
			if post_count > self.module['setting']['server']['max_count']:
				post_count = self.module['setting']['server']['max_count']
		except:
			pass
		# set tab static
		if not post_tab and 'tab' in self.module['setting']['server']:
			post_tab = self.module['setting']['server']['tab']

		posts 		= []
		if post_count > 0:
			###
			query	= {
				'site_id'		: self.module['site_id'],
				'format'		: "mv",
				'access.type' 	: "public"
			}
			###
			if 'channel' in self.site.site_db['page']:
				query['channel'] = self.site.site_db['page']['channel']['_id']

			if 'post_length' in self.module['setting']['server'] and self.module['setting']['server']['post_length'] in ['short', 'long']:
				query['post.length.type'] = self.module['setting']['server']['post_length']
			###
			if post_tab == "recommend":
				result 	= yield self.manager.post_recommend(post_id, count=post_count)
				if result and post_id in result:
					result.remove(post_id)
				post_id = result
				# sort output = tab rate
				post_tab = "rate"

			if post_tab == "rate":
				sort = [('rating.average', -1), ('rating.count', -1)] + sort
			
			if post_id:
				if type(post_id) == str:
					post_id 	= [ObjectId(p) for p in post_id.split(',')]
				elif type(post_id) == ObjectId:
					post_id 	= [post_id]

				if type(post_id) == list:
					query['_id'] = {'$in': post_id}
			###
			if not output:
				output = {}
			cursor 		= self.site.db.post.find(query, output).sort(sort)
			if post_skip:
				try:
					cursor = cursor.skip(int(post_skip))
				except:
					pass
			posts	= yield cursor.to_list(length=post_count)

			# sort with post id
			if post_sort and len(post_id) > 1:
				result = query['_id']['$in']
				for i in range(0,len(result)):
					if type(result[i]) == ObjectId:
						for p in posts:
							if result[i] == p['_id']:
								result[i] = p
								break
					if type(result[i]) == ObjectId:
						result[i] = None

				posts = [x for x in result if x]
		return posts
Ejemplo n.º 7
0
	def json(self, argv):
		self.manager 	= MovieManager(self.site, self.module)
		
		action 		= self.site.get_argument('action', None)
		search 		= self.site.get_argument('search', None)
		post_skip 	= self.site.get_argument('skip', None)
		post_tab 	= self.site.get_argument('tab', None)
		post_count 	= int(self.site.get_argument('count', 0))
		post_sort 	= False
		
		if search:
			post_id 	= yield self.manager.search_title_seo(search, post_count)
			post_sort 	= True
		else:
			post_id 	= self.site.get_argument('post', None)
			if post_id == None:
				try:
					post_id = argv[0]
				except:
					pass
			if type(post_id) == str and len(post_id) == 24:
				post_id 	= ObjectId(post_id)

		if action == "info":
			output = {
				'post.title':1,
				'post.subtitle':1,
				'post.poster':1,
				'post.director':1,
				'post.stars':1,
				'post.description':1,
				'post.country':1,
				'post.year':1,
				'post.length':1,
				'post.category':1,
				'post.title_seo':1,
				'post.trailer':1,
				'post.imdb':1,
				# 'view.count':1,
			}
		else:
			output = {
				'post.title':1,
				'post.subtitle':1,
				'post.title_seo':1,
				'post.poster':1,
				'post.year':1,
				'post.imdb':1,
				'post.length':1,
				# 'rating.count': 1,
				# 'rating.average': 1,
				'view.count':1,
			}

		posts 	= yield self.post_json(
			post_id		= post_id,
			post_skip	= post_skip,
			post_tab 	= post_tab,
			post_count 	= post_count,
			post_sort 	= post_sort,
			output 		= output,
		)
		posts_argv 	= []
		if action == "info":
			for post in posts:
				posts_argv.append(self.info_argv(post))
		else:
			for post in posts:
				posts_argv.append(self.post_argv(post))
		return {"post": posts_argv, "form": {'search': search}}
Ejemplo n.º 8
0
class Module(ModuleBase):
	"""docstring for Module"""
	def __init__(self):
		super(Module, self).__init__()
		self.script.extend([
			"/static/jwplayer/jwplayer.js",
			# "/static/jwplayer/jwpsrv.js"
		])

	@gen.coroutine
	def form(self, argv):
		post_argv 		= self.post_argv()
		template 		= {
			"post": self.site.render_string(self.module['path'] + "post.html", argv=post_argv, module= self.module).decode("utf-8")
		}
		return self.site.render_string(
			self.module['path'] + "form.html",
			module 	= self.module,
			form 	= {
				"template": b64encode(escape.json_encode(template).encode("utf-8")),
				"post": '{%% raw module["%s"]["post"] %%}' % self.module['_id']
			}
		), True
	@gen.coroutine
	def form_post(self, argv):
		json_argv 		= yield self.json(argv)
		if 'post' in json_argv and json_argv['post']:
			post_form 	= self.site.render_string(self.module['path'] + "post.html", argv=json_argv['post'], module= self.module)
		else:
			post_form 	= "Nội dung đang chờ kiểm duyệt hoặc không tồn tại!"
		return {"post": post_form}

	@gen.coroutine
	def json(self, argv):
		self.manager 	= MovieManager(self.site, self.module)

		action 		= self.site.get_argument('action', None)
		post_id 	= self.site.get_argument('post', None)
		
		if post_id == None:
			try:
				post_id = argv[0]
			except:
				pass

		if type(post_id) == str and re.match(r'[a-z0-9]{24}', post_id):
			post_id 		= ObjectId(post_id)

		if post_id:
			# update movie track
			post_track 	= self.site.get_argument('track', None)
			if post_track:
				if len(post_track) == 24:
					track_id = ObjectId(post_track)
				self.manager.set_user_view_post(track_id)

				# set movie view count
				self.manager.set_post_view(post_id)
		
			# part view
			if action == "part":
				# lock some request failure
				if self.site.request.headers.get('X-Requested-With') == 'XMLHttpRequest' and self.site.site_db['domain'][0] in self.site.request.headers.get('Referer')[:50]:
					mv_chap_index 		= self.site.get_argument('c-i', 0)
					mv_server_index 	= self.site.get_argument('s-i', 0)
					result = yield self.manager.get_movie_part(post_id, mv_chap_index, mv_server_index)
					if result:
						return {"post": result}
			
			# save last viewing movie chap/server/part
			elif action == "viewing":
				mv_chap 	= self.site.get_argument('mv-chap', -1)
				mv_server 	= self.site.get_argument('mv-server', -1)
				mv_part 	= self.site.get_argument('mv-part', -1)
				mv_seek 	= self.site.get_argument('mv-seek', 0)
				###
				try:
					mv_chap = int(mv_chap)
				except:
					mv_chap = -1
				###
				try:
					mv_server = int(mv_server)
				except:
					mv_server = -1
				###
				try:
					mv_part = int(mv_part)
				except:
					mv_part = -1
				###
				try:
					mv_seek = float(mv_seek)
				except:
					mv_seek = -1
				###
				# print(post_id, mv_chap, mv_server, mv_part, mv_seek)
				self.manager.get_user_view_post_lasted(post_id, mv_chap, mv_server, mv_part, mv_seek)
				return '{"error":0,"success":1}'
			elif action == "rating":
				mv_rate 	= self.site.get_argument('rate', None)
				if mv_rate:
					# print('rate', mv_rate)
					mv_rate = int(mv_rate)
					self.manager.set_post_rating(post_id, mv_rate)
					return '{"error":0,"success":1}'
			elif action == "report":
				mv_report 	= self.site.get_argument('report', None)
				mv_content	= self.site.get_argument('content', None)
				obj 		= report.SiteReport(self.site)
				# fork
				obj.set(mv_report, mv_content)
				return '{"error":0,"success":1}'
			else:
				post 	= yield self.post_json(argv[0])
				if post:
					argv 	= self.post_argv(post)
					
					# facebook graph
					self.site.graph['og:url'] 		= argv['link']
					self.site.graph['og:title'] 	= "%s - %s - %s"% (argv['title'], self.site.site_db['setting']['title'], self.site.site_db['domain'])
					if len(argv['description']) > 10:
						self.site.graph['og:description'] 	= escape.xhtml_escape("Xem Phim %s, %s" % (argv['title'], argv['description'][:300]))

					if 'poster' in argv:
						image 		= argv['poster']
					# elif 'trailer' in post['post']['trailer']:
					# 	image 		= "http://i1.ytimg.com/vi/%s/hqdefault.jpg" % post['post']['content']['video'].split('youtube.com/watch?v=',2)[1].split(r'/[#|\?]/', 1)[0]
					else:
						image 		= None
					if image:
						self.site.graph['og:image'] 	= [
							["og:image", image],
							["og:image:width", "1500"],
							["og:image:height", "1500"]
						]

				else:
					argv 	= None				
				return {"post": argv}
		return '{"error":1,"success":0}'

	def post_argv(self, post=None):
		if post:
			# search page
			searcher 	= "/%s/" % ("search")
			
			###
			argv 	= {
				"id" 				: str(post['_id']),
			}

			# title
			if 'title' in post['post']:
				argv['title'] 		= escape.xhtml_escape("%s - %s (%s)" % (post['post']['title'], post['post']['subtitle'], post['post']['year']))
			else:
				argv['title'] 		= ""

			# poster
			if 'poster' in post['post']:
				argv['poster'] 		= escape.xhtml_escape(post['post']['poster'])
			else:
				argv['poster'] 		= ""

			# director
			if 'director' in post['post']:
				director 	= []
				for dir in post['post']['director']:
					director.append('<a href="%s?director=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(dir), dir))
				argv['director'] 	= ', '.join(director)
			else:
				argv['director'] 	= ""

			# stars
			if 'stars' in post['post']:
				stars 	= []
				for star in post['post']['stars']:
					stars.append('<a href="%s?stars=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(star), star))
				argv['stars'] 	= ', '.join(stars)
			else:
				argv['stars'] 	= ""

			# description
			if 'description' in post['post']:
				argv['description'] 	= post['post']['description']
			else:
				argv['description'] 	= ""

			# country
			if 'country' in post['post']:
				argv['country'] 	= '<a href="%s?country=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(post['post']['country']), post['post']['country'])
			else:
				argv['country'] 	= ""

			# year
			if 'year' in post['post']:
				argv['year'] 	= '<a href="%s?year=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(post['post']['year']), post['post']['year'])
			else:
				argv['year'] 	= ""

			# length
			if 'length' in post['post'] and type(post['post']['length']) == dict:
				obj 	= post['post']['length']
				if obj['type'] == "long":
					# length = "%s/%s tập" % (obj['current'], obj['count'])
					argv['length'] = "%s tập" % obj['count']
					if 'current' in obj:
						argv['length'] = "%s/%s" % (obj['current'], argv['length'])
				else:
					argv['length'] 	= "%s phút" % obj['count']
			else:
				argv['length'] 	= ""

			# category
			if 'category' in post['post']:
				category 	= []
				for cate in post['post']['category']:
					category.append('<a href="%s?category=%s" site-goto="">%s</a>' % (searcher, escape.url_escape(cate), cate))
				argv['category'] 	= ', '.join(category)
			else:
				argv['category'] 	= ""

			# lastview
			if 'lastview' in post:
				argv['lastview'] = "%s|%s|%s|%s" % (post['lastview']['chap'], post['lastview']['server'], post['lastview']['part'], post['lastview']['seek'])
			else:
				argv['lastview'] = ""

			# seo title
			if 'title_seo' in post['post']:
				title_seo 		= escape.xhtml_escape(post['post']['title_seo'])
			else:
				title_seo 	= ''
			argv["link"] 	= "%s/%s/%s/%s.html" % (self.site.domain_root, self.site.site_db['page']['name'], post['_id'], title_seo)

			# image background
			if 'image' in post['post'] and post['post']['image']:
				argv['background'] = post['post']['image'][0]
			else:
				argv['background'] = 'https://lh6.googleusercontent.com/-UCQ1vCljDNk/VD5yhNY3cBI/AAAAAAAAAFM/ubsvrbtVq3Q/s1200/286652.jpg'

			# rating
			if 'rating' in post:
				# rating 	= post['rating']
				argv['rating_count'] 	= int(post['rating']['count'])
				argv['rating_average'] 	= int(post['rating']['average'])
			else:
				argv['rating_count'] 	= 0
				argv['rating_average'] 	= 0

			# movie chaps
			chaps 	= []
			if 'chap' in post['post']:
				for chap in post['post']['chap']:
					o_chap = {"name": chap['name'], "server": []}
					for server in chap['server']:
						o_chap['server'].append({"name": server['name']})
					chaps.append(o_chap)
			argv['chap'] 	= b64encode(escape.json_encode(chaps).encode("utf-8")).decode("utf-8")			
		else:
			argv 	= {
				"id" 				: '{{ id }}',
				"title"				: '{{ title }}',
				"poster" 			: '{{ poster }}',
				"director" 			: '{{ director }}',
				"stars" 			: '{{ stars }}',
				"description" 		: '{{ description }}',
				"country" 			: '{{ country }}',
				"year" 				: '{{ year }}',
				"length" 			: '{{ length }}',
				"category" 			: '{{ category }}',
				"background"		: '{{ background }}',
				"chap" 				: '{{ chap }}',
				"lastview"			: '{{ lastview }}',
				"rating_count"		: '{{ rating_count }}',
				"rating_average"	: '{{ rating_average }}',
				"link"				: '{{ link }}',
			}
		return argv

	@gen.coroutine
	def post_json(self, post_id):
		if type(post_id) == str and re.match(r'[a-z0-9]{24}', post_id):
			post_id 		= ObjectId(post_id)
		
		if type(post_id) == ObjectId:
			query = {
				'_id' 		: post_id,
				'site_id' 	: self.module['site_id'],
				'format' 	: 'mv'
			}

			if 'access' in self.module['setting']['server']:
				query['access.type'] = self.module['setting']['server']['access']
			# print(query)
			post 	= yield self.manager.db.find_one( query, {
				'rating.count': 1,
				'rating.average': 1,
				'post.title': 1,
				'post.subtitle': 1,
				'post.title_seo': 1,
				'post.poster': 1,
				'post.director': 1,
				'post.stars': 1,
				'post.description': 1,
				'post.country': 1,
				'post.year': 1,
				'post.length': 1,
				'post.category': 1,
				# 'post.image': {"$slice": [0,1]}, 
				'post.image': 1,
				'post.chap.name': 1,
				'post.chap.server.name': 1,
			})
			# print(post)
			if post:
				lastview 	= yield self.manager.get_user_view_post_lasted(post['_id'])
				if lastview and 'data' in lastview:
					post['lastview'] = lastview['data']
			return post
Ejemplo n.º 9
0
	def json(self, argv):
		self.manager 	= MovieManager(self.site, self.module)

		action 		= self.site.get_argument('action', None)
		post_id 	= self.site.get_argument('post', None)
		
		if post_id == None:
			try:
				post_id = argv[0]
			except:
				pass

		if type(post_id) == str and re.match(r'[a-z0-9]{24}', post_id):
			post_id 		= ObjectId(post_id)

		if post_id:
			# update movie track
			post_track 	= self.site.get_argument('track', None)
			if post_track:
				if len(post_track) == 24:
					track_id = ObjectId(post_track)
				self.manager.set_user_view_post(track_id)

				# set movie view count
				self.manager.set_post_view(post_id)
		
			# part view
			if action == "part":
				# lock some request failure
				if self.site.request.headers.get('X-Requested-With') == 'XMLHttpRequest' and self.site.site_db['domain'][0] in self.site.request.headers.get('Referer')[:50]:
					mv_chap_index 		= self.site.get_argument('c-i', 0)
					mv_server_index 	= self.site.get_argument('s-i', 0)
					result = yield self.manager.get_movie_part(post_id, mv_chap_index, mv_server_index)
					if result:
						return {"post": result}
			
			# save last viewing movie chap/server/part
			elif action == "viewing":
				mv_chap 	= self.site.get_argument('mv-chap', -1)
				mv_server 	= self.site.get_argument('mv-server', -1)
				mv_part 	= self.site.get_argument('mv-part', -1)
				mv_seek 	= self.site.get_argument('mv-seek', 0)
				###
				try:
					mv_chap = int(mv_chap)
				except:
					mv_chap = -1
				###
				try:
					mv_server = int(mv_server)
				except:
					mv_server = -1
				###
				try:
					mv_part = int(mv_part)
				except:
					mv_part = -1
				###
				try:
					mv_seek = float(mv_seek)
				except:
					mv_seek = -1
				###
				# print(post_id, mv_chap, mv_server, mv_part, mv_seek)
				self.manager.get_user_view_post_lasted(post_id, mv_chap, mv_server, mv_part, mv_seek)
				return '{"error":0,"success":1}'
			elif action == "rating":
				mv_rate 	= self.site.get_argument('rate', None)
				if mv_rate:
					# print('rate', mv_rate)
					mv_rate = int(mv_rate)
					self.manager.set_post_rating(post_id, mv_rate)
					return '{"error":0,"success":1}'
			elif action == "report":
				mv_report 	= self.site.get_argument('report', None)
				mv_content	= self.site.get_argument('content', None)
				obj 		= report.SiteReport(self.site)
				# fork
				obj.set(mv_report, mv_content)
				return '{"error":0,"success":1}'
			else:
				post 	= yield self.post_json(argv[0])
				if post:
					argv 	= self.post_argv(post)
					
					# facebook graph
					self.site.graph['og:url'] 		= argv['link']
					self.site.graph['og:title'] 	= "%s - %s - %s"% (argv['title'], self.site.site_db['setting']['title'], self.site.site_db['domain'])
					if len(argv['description']) > 10:
						self.site.graph['og:description'] 	= escape.xhtml_escape("Xem Phim %s, %s" % (argv['title'], argv['description'][:300]))

					if 'poster' in argv:
						image 		= argv['poster']
					# elif 'trailer' in post['post']['trailer']:
					# 	image 		= "http://i1.ytimg.com/vi/%s/hqdefault.jpg" % post['post']['content']['video'].split('youtube.com/watch?v=',2)[1].split(r'/[#|\?]/', 1)[0]
					else:
						image 		= None
					if image:
						self.site.graph['og:image'] 	= [
							["og:image", image],
							["og:image:width", "1500"],
							["og:image:height", "1500"]
						]

				else:
					argv 	= None				
				return {"post": argv}
		return '{"error":1,"success":0}'
Ejemplo n.º 10
0
    def json(self, argv):
        self.manager = MovieManager(self.site, self.module)
        post_id = self.site.get_argument('post', None)

        if not post_id and argv and len(argv) > 0:
            post_id = argv[0]

        if type(post_id) == str and len(post_id) == 24:
            post_id = ObjectId(post_id)

        action = self.site.get_argument('action', None)

        if action == "findgroup":
            g_name = self.site.get_argument('g_name', None)
            groups = yield self.manager.search_post_group(g_name)
            if groups:
                result = []
                for g in groups:
                    result.append({
                        "id": str(g['_id']),
                        "name": g['name'],
                        "post": [str(p) for p in g['post']]
                    })
                return {"post": result}
        elif action == "groupofpost":
            if post_id:
                groups = yield self.manager.get_post_group(post_id=post_id,
                                                           output={
                                                               "_id": 1,
                                                               "name": 1,
                                                               "post": 1
                                                           })
                # print(groups)
                result = []
                for g in groups:
                    result.append({
                        "id": str(g['_id']),
                        "name": g['name'],
                        "post": [str(p) for p in g['post']]
                    })
                return {"post": result}
        elif action == "postofgroup":
            g_id = self.site.get_argument('g_id', None)
            if g_id:
                groups = yield self.manager.get_post_group(group_id=g_id,
                                                           output={
                                                               "_id": 1,
                                                               "name": 1,
                                                               "post": 1
                                                           })
                if groups and 'post' in groups[0]:
                    posts = yield self.post_json(post_id=groups[0]['post'])
                    posts_argv = []
                    for post in posts:
                        posts_argv.append(self.post_argv(post))
                    return {"post": posts_argv}

        elif action == "channelofpost":
            if post_id:
                post = yield self.site.db.post.find_one({"_id": post_id},
                                                        {"channel": 1})
                result = []
                if post and 'channel' in post:
                    channel = yield self.site.db.channel.find(
                        {
                            '_id': {
                                "$in": post['channel']
                            }
                        }, {
                            "name": 1
                        }).to_list(length=30)
                    for c in channel:
                        result.append({
                            "id": str(c['_id']),
                            "name": c['name'],
                        })
                return {"post": result}
        elif action == "findchannel":
            c_name = self.site.get_argument('c_name', None)

            query = {'site_id': self.site.site_db['_id']}
            if c_name:
                query['name'] = c_name

            channel = yield self.site.db.channel.find(query, {
                "name": 1
            }).to_list(length=30)
            result = []
            for c in channel:
                result.append({
                    "id": str(c['_id']),
                    "name": c['name'],
                })
            return {"post": result}

        elif type(post_id) == ObjectId:
            ### public/private/trash/restore post
            if action == "manager":
                post_is = self.site.get_argument('is', 'private')
                # public post
                if post_is in ["public", "private", "trash", "restore"]:
                    timestep = int(self.site.get_argument('timestep', 0))
                    update = yield self.manager.set_post_access(
                        post_id, access=post_is, timestep=timestep)
                    if update:
                        return '{"error": 0, "success": "%s successful!"}' % post_is
                #  finished post
                elif post_is == "finished":
                    update = yield self.manager.set_movie_finished(post_id)
                    if update:
                        return '{"error": 0, "success": "%s successful!"}' % post_is
                # unfinished post
                elif post_is == "unfinished":
                    update = yield self.manager.set_movie_unfinished(post_id)
                    if update:
                        return '{"error": 0, "success": "%s successful!"}' % post_is
                # edit post
                elif post_is == "edit":
                    json = self.site.get_argument('movie', None)
                    if json:
                        json = escape.json_decode(json)
                        if 'chap' in json:
                            update = yield self.manager.set_movie_chaps(
                                json['chap'], post_id)
                        else:
                            update = yield self.manager.set_movie_info(
                                json, post_id)

                        if update:
                            return '{"error": 0, "success": "edit successful!"}'

                # delete post
                elif post_is == "delete":
                    post = yield self.manager.db.remove({
                        "_id":
                        post_id,
                        'site_id':
                        self.site.site_db['_id'],
                        'post.format':
                        "mv",
                        "type":
                        "trash"
                    })
                    if post:
                        post = yield self.manager.db.remove({
                            "parent_id":
                            post_id,
                            'site_id':
                            self.site.site_db['_id'],
                            'post.format':
                            "mvc"
                        })
                        if post:
                            return '{"error": 0, "success": "delete successful!"}'

                # join group
                elif post_is == "joingroup":
                    group_id = self.site.get_argument('g_id', None)
                    group_name = self.site.get_argument('g_name', None)
                    yield self.manager.set_post_group(post_id, group_id,
                                                      group_name)

                # join group
                elif post_is == "leavegroup":
                    group_id = self.site.get_argument('g_id', None)
                    yield self.manager.leave_post_group(post_id, group_id)

                elif post_is == "joinchannel":
                    channel_id = self.site.get_argument('c_id', None)
                    if type(channel_id) == str and len(channel_id) == 24:
                        channel_id = ObjectId(channel_id)

                    result = yield self.site.db.post.update(
                        {"_id": post_id}, {"$push": {
                            "channel": channel_id
                        }},
                        upsert=True)
                    if result and 'n' in result and result['n'] > 0:
                        return '{"error": 0, "success": "edit successful!"}'
                elif post_is == "removechannel":
                    channel_id = self.site.get_argument('c_id', None)
                    if type(channel_id) == str and len(channel_id) == 24:
                        channel_id = ObjectId(channel_id)

                    post = yield self.site.db.post.find_one({'_id': post_id},
                                                            {"channel": 1})
                    if post and 'channel' in post and channel_id in post[
                            'channel']:
                        channels = [
                            x for x in post['channel'] if x != channel_id
                        ]
                        result = yield self.site.db.post.update(
                            {"_id": post_id}, {"$set": {
                                "channel": channels
                            }},
                            upsert=True)
                        if result and 'n' in result and result['n'] > 0:
                            return '{"error": 0, "success": "edit successful!"}'
            # get post information for editor
            elif action == "edit":
                post = yield self.manager.db.find_one({'_id': post_id},
                                                      {'post': 1})
                if post:
                    return {"post": post['post']}
            # join search list post
            elif action == "search":
                search = self.site.get_argument('search', None)
                if search:
                    try:
                        post_count = int(self.site.get_argument('count', 10))
                    except Exception as e:
                        post_count = 10
                    # tim danh sach post
                    posts_id = yield self.manager.search_title_seo(search)
                    # ko trung voi post hien co
                    posts_id = [x for x in posts_id if x != post_id]
                    posts = yield self.post_json(post_id=posts_id,
                                                 post_tab="search",
                                                 post_count=post_count)
                    posts_argv = {p['_id']: self.post_argv(p) for p in posts}
                    post_result = [
                        posts_argv[p] for p in posts_id
                        if p in list(posts_argv.keys())
                    ]
                    return {"post": post_result}
        ### get post content
        if not action:
            post_skip = self.site.get_argument('skip', None)
            # post_view 	= self.site.get_argument('view', None)
            post_tab = self.site.get_argument('tab', "new")
            post_count = int(self.site.get_argument('count', 10))

            posts = yield self.post_json(post_id=post_id,
                                         post_skip=post_skip,
                                         post_tab=post_tab,
                                         post_count=post_count)
            # print(posts)
            posts_argv = []
            for post in posts:
                posts_argv.append(self.post_argv(post))
            # print(post_argv)
            return {"post": posts_argv, "tab": post_tab}

        return '{"error":1,"success":0}'
Ejemplo n.º 11
0
class Module(ModuleBase):
    """docstring for Module"""
    def __init__(self):
        super(Module, self).__init__()
        self.script.extend([
            "/static/js/beautify.js",
        ])

    @gen.coroutine
    def form(self, argv):
        json_argv = self.post_argv()
        template = {
            "post":
            self.site.render_string(self.module['path'] + "post.html",
                                    argv=[json_argv]).decode("utf-8"),
        }
        return self.site.render_string(
            self.module['path'] + "form.html",
            module=self.module,
            argv={
                "template":
                b64encode(escape.json_encode(template).encode("utf-8")),
                "post":
                '{%% raw module["%s"]["post"] %%}' % self.module['_id'],
                "tab": '{%% raw module["%s"]["tab"] %%}' % self.module['_id'],
            },
        ), True

    @gen.coroutine
    def form_post(self, argv):
        json_argv = yield self.json(argv)
        post_form = self.site.render_string(self.module['path'] + "post.html",
                                            argv=json_argv['post'])
        return {"post": post_form, "tab": json_argv['tab']}

    @gen.coroutine
    def json(self, argv):
        self.manager = MovieManager(self.site, self.module)
        post_id = self.site.get_argument('post', None)

        if not post_id and argv and len(argv) > 0:
            post_id = argv[0]

        if type(post_id) == str and len(post_id) == 24:
            post_id = ObjectId(post_id)

        action = self.site.get_argument('action', None)

        if action == "findgroup":
            g_name = self.site.get_argument('g_name', None)
            groups = yield self.manager.search_post_group(g_name)
            if groups:
                result = []
                for g in groups:
                    result.append({
                        "id": str(g['_id']),
                        "name": g['name'],
                        "post": [str(p) for p in g['post']]
                    })
                return {"post": result}
        elif action == "groupofpost":
            if post_id:
                groups = yield self.manager.get_post_group(post_id=post_id,
                                                           output={
                                                               "_id": 1,
                                                               "name": 1,
                                                               "post": 1
                                                           })
                # print(groups)
                result = []
                for g in groups:
                    result.append({
                        "id": str(g['_id']),
                        "name": g['name'],
                        "post": [str(p) for p in g['post']]
                    })
                return {"post": result}
        elif action == "postofgroup":
            g_id = self.site.get_argument('g_id', None)
            if g_id:
                groups = yield self.manager.get_post_group(group_id=g_id,
                                                           output={
                                                               "_id": 1,
                                                               "name": 1,
                                                               "post": 1
                                                           })
                if groups and 'post' in groups[0]:
                    posts = yield self.post_json(post_id=groups[0]['post'])
                    posts_argv = []
                    for post in posts:
                        posts_argv.append(self.post_argv(post))
                    return {"post": posts_argv}

        elif action == "channelofpost":
            if post_id:
                post = yield self.site.db.post.find_one({"_id": post_id},
                                                        {"channel": 1})
                result = []
                if post and 'channel' in post:
                    channel = yield self.site.db.channel.find(
                        {
                            '_id': {
                                "$in": post['channel']
                            }
                        }, {
                            "name": 1
                        }).to_list(length=30)
                    for c in channel:
                        result.append({
                            "id": str(c['_id']),
                            "name": c['name'],
                        })
                return {"post": result}
        elif action == "findchannel":
            c_name = self.site.get_argument('c_name', None)

            query = {'site_id': self.site.site_db['_id']}
            if c_name:
                query['name'] = c_name

            channel = yield self.site.db.channel.find(query, {
                "name": 1
            }).to_list(length=30)
            result = []
            for c in channel:
                result.append({
                    "id": str(c['_id']),
                    "name": c['name'],
                })
            return {"post": result}

        elif type(post_id) == ObjectId:
            ### public/private/trash/restore post
            if action == "manager":
                post_is = self.site.get_argument('is', 'private')
                # public post
                if post_is in ["public", "private", "trash", "restore"]:
                    timestep = int(self.site.get_argument('timestep', 0))
                    update = yield self.manager.set_post_access(
                        post_id, access=post_is, timestep=timestep)
                    if update:
                        return '{"error": 0, "success": "%s successful!"}' % post_is
                #  finished post
                elif post_is == "finished":
                    update = yield self.manager.set_movie_finished(post_id)
                    if update:
                        return '{"error": 0, "success": "%s successful!"}' % post_is
                # unfinished post
                elif post_is == "unfinished":
                    update = yield self.manager.set_movie_unfinished(post_id)
                    if update:
                        return '{"error": 0, "success": "%s successful!"}' % post_is
                # edit post
                elif post_is == "edit":
                    json = self.site.get_argument('movie', None)
                    if json:
                        json = escape.json_decode(json)
                        if 'chap' in json:
                            update = yield self.manager.set_movie_chaps(
                                json['chap'], post_id)
                        else:
                            update = yield self.manager.set_movie_info(
                                json, post_id)

                        if update:
                            return '{"error": 0, "success": "edit successful!"}'

                # delete post
                elif post_is == "delete":
                    post = yield self.manager.db.remove({
                        "_id":
                        post_id,
                        'site_id':
                        self.site.site_db['_id'],
                        'post.format':
                        "mv",
                        "type":
                        "trash"
                    })
                    if post:
                        post = yield self.manager.db.remove({
                            "parent_id":
                            post_id,
                            'site_id':
                            self.site.site_db['_id'],
                            'post.format':
                            "mvc"
                        })
                        if post:
                            return '{"error": 0, "success": "delete successful!"}'

                # join group
                elif post_is == "joingroup":
                    group_id = self.site.get_argument('g_id', None)
                    group_name = self.site.get_argument('g_name', None)
                    yield self.manager.set_post_group(post_id, group_id,
                                                      group_name)

                # join group
                elif post_is == "leavegroup":
                    group_id = self.site.get_argument('g_id', None)
                    yield self.manager.leave_post_group(post_id, group_id)

                elif post_is == "joinchannel":
                    channel_id = self.site.get_argument('c_id', None)
                    if type(channel_id) == str and len(channel_id) == 24:
                        channel_id = ObjectId(channel_id)

                    result = yield self.site.db.post.update(
                        {"_id": post_id}, {"$push": {
                            "channel": channel_id
                        }},
                        upsert=True)
                    if result and 'n' in result and result['n'] > 0:
                        return '{"error": 0, "success": "edit successful!"}'
                elif post_is == "removechannel":
                    channel_id = self.site.get_argument('c_id', None)
                    if type(channel_id) == str and len(channel_id) == 24:
                        channel_id = ObjectId(channel_id)

                    post = yield self.site.db.post.find_one({'_id': post_id},
                                                            {"channel": 1})
                    if post and 'channel' in post and channel_id in post[
                            'channel']:
                        channels = [
                            x for x in post['channel'] if x != channel_id
                        ]
                        result = yield self.site.db.post.update(
                            {"_id": post_id}, {"$set": {
                                "channel": channels
                            }},
                            upsert=True)
                        if result and 'n' in result and result['n'] > 0:
                            return '{"error": 0, "success": "edit successful!"}'
            # get post information for editor
            elif action == "edit":
                post = yield self.manager.db.find_one({'_id': post_id},
                                                      {'post': 1})
                if post:
                    return {"post": post['post']}
            # join search list post
            elif action == "search":
                search = self.site.get_argument('search', None)
                if search:
                    try:
                        post_count = int(self.site.get_argument('count', 10))
                    except Exception as e:
                        post_count = 10
                    # tim danh sach post
                    posts_id = yield self.manager.search_title_seo(search)
                    # ko trung voi post hien co
                    posts_id = [x for x in posts_id if x != post_id]
                    posts = yield self.post_json(post_id=posts_id,
                                                 post_tab="search",
                                                 post_count=post_count)
                    posts_argv = {p['_id']: self.post_argv(p) for p in posts}
                    post_result = [
                        posts_argv[p] for p in posts_id
                        if p in list(posts_argv.keys())
                    ]
                    return {"post": post_result}
        ### get post content
        if not action:
            post_skip = self.site.get_argument('skip', None)
            # post_view 	= self.site.get_argument('view', None)
            post_tab = self.site.get_argument('tab', "new")
            post_count = int(self.site.get_argument('count', 10))

            posts = yield self.post_json(post_id=post_id,
                                         post_skip=post_skip,
                                         post_tab=post_tab,
                                         post_count=post_count)
            # print(posts)
            posts_argv = []
            for post in posts:
                posts_argv.append(self.post_argv(post))
            # print(post_argv)
            return {"post": posts_argv, "tab": post_tab}

        return '{"error":1,"success":0}'

    def post_argv(self, post=None):
        if post:
            if 'poster' in post['post']:
                poster = post['post']['poster']
            else:
                poster = ''
            ### seo title generic ###
            if 'title_seo' in post['post']:
                title_seo = post['post']['title_seo']
            else:
                title_seo = ''
            ### link generic ###
            if 'link' in post['post']:
                link = post['post']['link']
            else:
                link = "%s/%s/%s/%s.html" % (self.site.domain_root,
                                             self.site.site_db['page']['name'],
                                             post['_id'], title_seo)
            ### is public post ###
            if 'access' in post:
                action = post['access']['type']
            else:
                action = 'private'
            #####
            argv = {
                "id":
                str(post['_id']),
                "poster":
                poster,
                "link":
                link,
                "title":
                escape.xhtml_escape(
                    "%s - %s (%s)" %
                    (post['post']['title'], post['post']['subtitle'],
                     post['post']['year'])),
                "by":
                post['user']['first_name'] + ' ' + post['user']['last_name'],
                "view":
                post['view']['count'] if 'view' in post else 0,
                "time":
                post['owner']['time'],
                "action":
                action,
                "finished":
                'finished' if 'finished' in post['post']
                and post['post']['finished'] == True else 'unfinished'
            }
        else:
            argv = {
                "id": '{{ id }}',
                "poster": '{{ poster }}',
                "link": '{{ link }}',
                "title": '{{ title }}',
                "by": '{{ by }}',
                "view": '{{ view }}',
                "time": '{{ time }}',
                "action": '{{ action }}',
                "finished": '{{ finished }}',
            }
        return argv

    @gen.coroutine
    def post_json(self,
                  post_id=None,
                  post_skip=None,
                  post_tab=None,
                  post_count=25):
        if post_count > self.module['setting']['server']['max_count']:
            post_count = self.module['setting']['server']['max_count']
        ###
        if type(post_id) == str:
            post_id = [ObjectId(p) for p in post_id.split(',')]
        elif type(post_id) == ObjectId:
            post_id = [post_id]

        ###
        posts = []
        if post_count > 0:
            ### sap xem theo thoi gian moi nhat
            sort = [('access.time', -1)]

            # find query
            query = {'site_id': self.module['site_id'], "format": "mv"}

            if type(post_id) == list:
                query['_id'] = {'$in': post_id}

            # search movie
            if post_tab != "search":
                # finished post
                if post_tab == "finished":
                    query['post.finished'] = True

                elif post_tab == "unfinished":
                    query['$or'] = [{
                        'post.finished': False
                    }, {
                        'post.finished': {
                            "$exists": False
                        }
                    }]

                # public post
                if post_tab == "public":
                    query['access.type'] = "public"
                # private post
                elif post_tab == "private":
                    query['$or'] = [{
                        "access.type": "private"
                    }, {
                        "access.type": {
                            "$exists": False
                        }
                    }]
                # trash post
                elif post_tab == "trash":
                    query['access.type'] = "trash"
                # new post : mac dinh ko co trong trash
                else:
                    query['access.type'] = {"$nin": ["trash"]}

            # run search
            cursor = self.manager.db.find(query, {
                'owner': 1,
                'post': 1,
                'view.count': 1,
                'access.type': 1
            }).sort(sort)
            if post_skip:
                try:
                    cursor = cursor.skip(int(post_skip))
                except:
                    pass
            cursor = cursor.limit(post_count)

            # insert user info
            users_id = {}
            while (yield cursor.fetch_next):
                post = cursor.next_object()
                posts.append(post)
                # id cua user post
                users_id[post['owner']['id']] = 1
            ###
            # lay info cua user comment trong list
            query = {"_id": {"$in": list(users_id.keys())}}
            users = {}
            cursor = self.site.db.user.find(query, {
                'first_name': 1,
                'last_name': 1,
                'email': 1,
                'picture': 1
            })
            while (yield cursor.fetch_next):
                user = cursor.next_object()
                users[user['_id']] = user
            ###
            for post in posts:
                if post['owner']['id'] in users:
                    post['user'] = users[post['owner']['id']]
        return posts