Beispiel #1
0
def admin():
    if request.method == "GET":
        if "logged_in" in session:
            videos = Video.objects()
            return render_template("admin.html", videos=videos)
        else:
            return render_template("error.html")
    else:
        form = request.form
        link = form["link"]

        ydl = YoutubeDL()
        data = ydl.extract_info(link, download=False)

        title = data["title"]
        thumbnail = data["thumbnail"]
        views = data["view_count"]
        link = data["webpage_url"]
        youtubeid = data["id"]

        new_video = Video(title=title,
                          thumbnail=thumbnail,
                          views=views,
                          link=link,
                          youtubeid=youtubeid)
        new_video.save()

        return render_template("admin.html")
Beispiel #2
0
    def post(self):
        print 'Content-Type: text/plain'
        print ''

        video = Video.get_by_key_name('vid' + self.request.get('playerID'))
        if not video:
            video = Video.get_by_key_name(self.request.get('playerID'))
        author = users.get_current_user()
        if video:
            text = unicode(self.request.get('message')).strip()
            stime = float(self.request.get('playTime'))
            mode = int(self.request.get('mode'))
            fontsize = int(self.request.get('fontsize'))
            color = int(self.request.get('color'))

            cmt = Comment(author=author,
                          text=text,
                          stime=stime,
                          mode=mode,
                          fontsize=fontsize,
                          color=color,
                          cid=video)
            if cmt:
                cmt.put()
                print 'OK'
            else:
                print 'Failed'
        else:
            print 'Failed'
Beispiel #3
0
def admin():
    if "loggedin" in session:

        if request.method == "GET":
            videos = Video.objects()
            return render_template('admin.html', videos=videos)
        elif request.method == "POST":
            form = request.form
            link = form['link']
            ydl = YoutubeDL()
            data = ydl.extract_info(link, download=False)
            title = data["title"]
            thumbnail = data["thumbnail"]
            views = data["view_count"]
            youtube_id = data["id"]
            new_video = Video(title=title,
                              thumbnail=thumbnail,
                              views=views,
                              link=link,
                              youtube_id=youtube_id)
            new_video.save()

            return redirect(url_for("admin"))
    else:
        return redirect(url_for("login"))
Beispiel #4
0
def admin():
    if "loggedin" in session:
        if session['loggedin'] == True:
            if request.method == 'GET':
                videos = Video.objects()
                return render_template('admin.html', videos=videos)
            elif request.method == 'POST':
                form = request.form
                link = form['link']
                ydl = YoutubeDL()

                data = ydl.extract_info(link, download=False)

                title = data['title']
                views = data['view_count']
                thumbnail = data['thumbnail']
                youtube_id = data['id']

                video = Video(title=title,
                              views=views,
                              thumbnail=thumbnail,
                              youtube_id=youtube_id,
                              link=link)

                video.save()

                return redirect(url_for('admin'))
        else:
            return "Đăng nhập chưa mà đòi"
    else:
        return "Đăng nhập chưa mà đòi"
Beispiel #5
0
  def post(self):
    print 'Content-Type: text/plain'
    print ''

    video = Video.get_by_key_name('vid' + self.request.get('playerID'))
    if not video:
      video = Video.get_by_key_name(self.request.get('playerID'))
    author = users.get_current_user()
    if video:
      text = unicode(self.request.get('message')).strip()
      stime = float(self.request.get('playTime'))
      mode = int(self.request.get('mode'))
      fontsize = int(self.request.get('fontsize'))
      color = int(self.request.get('color'))

      cmt = Comment(author=author,
                    text=text,
                    stime=stime,
                    mode=mode,
                    fontsize=fontsize,
                    color=color,
                    cid=video)
      if cmt:
        cmt.put()
        print 'OK'
      else:
        print 'Failed'
    else:
      print 'Failed'
def admin():
    if "loggedin" in session:
        if request.method == "GET":
            videos = Video.objects()
            return render_template('admin.html', videos=videos)
        elif request.method == "POST":
            form = request.form
            link = form['link']

            ydl = YoutubeDL()
            data = ydl.extract_info(link, download=False)
            title = data['title']
            thumbnail = data['thumbnail']
            views = data['view_count']
            youtubeid = data['id']

            new_video = Video(title=title,
                              thumbnail=thumbnail,
                              views=views,
                              youtubeid=youtubeid,
                              link=link)
            new_video.save()

            return redirect(url_for('admin'))
    else:
        return "Yêu cầu đăng nhập !!!"
Beispiel #7
0
def admin():
    if "loggedin" in session:
        if request.method =="GET":
            videos = Video.objects()
            print(videos)
            return render_template('admin.html', videos = videos)
        elif request.method =="POST":
            form = request.form
            link = form['link']
            ydl_opts = {
                'nocheckcertificate' : True,
            }
            ydl = YoutubeDL()
            data = ydl.extract_info(link, download = False)
            print(data)
            title = data['title']
            thumbnail = data['thumbnail']
            views = data['view_count']
            youtube_id = data['id']
            uploader = data['uploader']
            new_video = Video(  title = title, 
                                thumbnail = thumbnail, 
                                views = views, 
                                link = link, 
                                youtube_id = youtube_id, 
                                uploader = uploader)
            new_video.save()
            return redirect(url_for('admin'))
    else:
        return "Yêu cầu đăng nhập"
Beispiel #8
0
def admin():
    if request.method == 'GET':
        if 'logged_in' in session:
            videos = Video.objects()
            return render_template('admin.html', videos=videos)
        else:
            return render_template('error.html')

    elif request.method == 'POST':
        form = request.form
        link = form['link']
        ydl = YoutubeDL()
        data = ydl.extract_info(link, download=False)
        title = data['title']
        thumbnail = data['thumbnail']
        views = data['view_count']
        link = data['webpage_url']
        youtubeid = data['id']

        new_video = Video(title=title,
                          thumbnail=thumbnail,
                          views=views,
                          link=link,
                          youtubeid=youtubeid)
        new_video.save()
        return redirect(url_for('admin'))
    def add_video_by_id(self, youtube_id):
        html = self.downloader.get_html(youtube_id)
        if not self.parser._check_video_availability(html):
            return

        video_item = Video(youtube_id)
        video_item.update(title=self.parser.get_video_title(html))
        self.db_handler.add_entry(video_item)
Beispiel #10
0
    def __init__(self, movie_title, movie_duration, movie_trailer_youtube_url, movie_story_line, movie_post_image_url, movie_director, movie_release_date, movie_iMDB_rate):

        Video.__init__(self, movie_title, movie_duration, movie_trailer_youtube_url)
        self.movie_story_line     = movie_story_line;
        self.movie_post_image_url = movie_post_image_url;
        self.movie_director         = movie_director;
        self.movie_release_date   = movie_release_date;
        self.movie_iMDB_rate      = movie_iMDB_rate;
Beispiel #11
0
    def post(self):
        user = users.get_current_user()
        vkeystr = unicode(self.request.get('videoId')).strip()
        vkey = db.Key(vkeystr)
        if not vkey:
            self.error(404)
        else:
            video = Video.get(vkey)
            path = unicode(self.request.get('path')).strip()
            if path == '' and self.request.POST.get('localfile') == '':
                self.redirect('/addvideo/' + video.art.key().name() + '/')
            else:
                if video.cblock_set.count():
                    MukioTools.delete(video.cblock_set)  #删除已经存在的外部XML
                if user != video.art.author:
                    self.error(404)  #只有本人才能进行该操作

                data = self.getfile()

                if data:
                    cbk = CBlock(link=path,
                                 data=unicode(data, 'utf-8'),
                                 cid=video)
                    if cbk:
                        cbk.put()
                        self.redirect('/addvideo/' + video.art.key().name() +
                                      '/')
                else:
                    self.error(404)
Beispiel #12
0
 def get(self):
     args = self.reqparse.parse_args()
     token = args.get('auth-token')
     profesor = Profesor.load_from_token(token)
     if profesor == None:
         return {'response': 'user_invalid'}, 401
     return Video.get_all_by_asignatura(profesor.asignatura.id)
Beispiel #13
0
  def post(self):
    user = users.get_current_user()
    vkeystr = unicode(self.request.get('videoId')).strip()
    vkey = db.Key(vkeystr)
    if not vkey:
      self.error(404)
    else:
      video = Video.get(vkey)
      path = unicode(self.request.get('path')).strip()
      if path == '' and self.request.POST.get('localfile') == '':
        self.redirect('/addvideo/' + video.art.key().name() + '/')
      else:
        if video.cblock_set.count():
          MukioTools.delete(video.cblock_set)#删除已经存在的外部XML
        if user != video.art.author:
          self.error(404)#只有本人才能进行该操作

        data = self.getfile()
        
        if data:
          cbk = CBlock(link=path,
                       data=unicode(data,'utf-8'),
                       cid=video)
          if cbk:
            cbk.put()
            self.redirect('/addvideo/' + video.art.key().name() + '/')
        else:
          self.error(404)
Beispiel #14
0
def video():
    if request.method == 'GET':
        videos = Video.objects()
        cardios = Cardio.objects()
        # overweights = Overweight.objects()
        underweights = Underweight.objects()
        yogas= Yoga.objects()
        exercises = Exercise.objects()
        return render_template('admin.html', videos=videos, cardios=cardios, underweights=underweights, yogas=yogas, exercises=exercises )
    elif request.method == 'POST':
        form = request.form
        link = form['link']
        ydl = YoutubeDL()
        data = ydl.extract_info(link, download=False)

        title = data['title']
        thumbnail = data['thumbnail']
        youtube_id = data['id']
        # duration = data['duration']


        new_ex = Exercise(
                title= title,
                link= link,
                thumbnail= thumbnail,
                youtube_id= youtube_id
                # duration= duration
            )

        new_ex.save()
    
        return redirect(url_for('video'))
Beispiel #15
0
def getlean(bmi_id):
    if "logged_in" in session:
        # bmi = session['user_bmi']
        body = Body.objects.with_id(bmi_id)
        
        user = User.objects.with_id(session['user_id'])
        # user_id = session['user_id']
        # print(user_id)
        # get_body = Body.objects(user_id = user_id)
        # print(get_body)
        # bmi = Body.objects.order_by('-user_id').first()
        videos = Video.objects()
        cardios = Cardio.objects()
        yogas = Yoga.objects()
        exercises = Exercise.objects()
        underweights = Underweight.objects()
        if body.bmi < 18.5:
            return render_template('underweight.html', full_name = user.fname, user_id = user.id, bmi = body.bmi, videos=videos, cardios=cardios, yogas=yogas, underweights=underweights) 
        elif 18.5 <= body.bmi < 25:
            return render_template('normal.html', full_name = user.fname, user_id = user.id, bmi = body.bmi, videos=videos, cardios=cardios, yogas=yogas, underweights=underweights)
        elif 25 <= body.bmi < 30: 
            return render_template('overweight.html', full_name = user.fname, user_id = user.id, bmi = body.bmi, videos=videos, cardios=cardios, exercises=exercises)
        else:
            return render_template('obese.html', full_name = user.fname, user_id = user.id, bmi = body.bmi, videos=videos, cardios=cardios, exercises=exercises)
    else:
        return render_template(url_for('login'))
Beispiel #16
0
def favorite_method():
    if session['Account']:
        if request.method == 'POST':
            url = request.form['url']
            title = request.form['title']
            link = request.form['link']
            img = request.form['img']
            account = session['Account']
            Video(account, title, link, img).save_to_db()
            return redirect(url)
        else:
            account = session['Account']
            user_video = Video.find_video(account)
            return render_template("favorite.html", user_video=user_video)
    else:
        return redirect("/login")
Beispiel #17
0
	def add_video(self, service, url, title, duration, start_time):
		c = database.cursor()
		c.execute('''
			SELECT rank
			FROM room_queue
			WHERE room_id = ?
			ORDER BY rank DESC
			LIMIT 1'''
			, (self.room_id,))
		result_next_rank = c.fetchone()

		if result_next_rank:
			next_rank = result_next_rank[0] + 1.0
		else:
			next_rank = 0.0

		video_id = Video.create(
			self.room_id
			, next_rank
			, service
			, url
			, title
			, duration
			, start_time)

		return Video(video_id)
Beispiel #18
0
def remove_method():
    if session['account']:
        link = request.form['link']
        account = session['account']
        print("the link is {0}".format(link))
        Video(account).delete_video(account,link)
        return redirect("/favorite")
Beispiel #19
0
def result_page():
    url = request.url
    favorite_video = []
    user_favorite = Video(session['account']).fine_video(session['account'])
    for video in user_favorite:
        favorite_video.append(video['link'])

    if request.args.get("q") is None:
        search = request.args.get("search")
        soup = item.find_search_content(search)
        all_item = item.every_video(soup)
        all_page = item.page_bar(soup)
        return render_template("result.html",search=search,all_item=all_item,all_page=all_page,url=url,favorite_video=favorite_video)

    elif request.args.get("q") is not None:
        search = request.args.get("q")
        page = request.args.get("sp")
        current_page = request.args.get("current_page")
        link = "q={}".format(search)+"&sp={}".format(page)
        soup = item.find_page_content(link)
        all_item = item.every_video(soup)
        all_page = item.page_bar(soup)
        return render_template("result_page.html", search=search, all_item=all_item, all_page=all_page,current_page=current_page,int=int,url=url,favorite_video=favorite_video)
    else:
        return redirect('/')
Beispiel #20
0
def bmi():
    if request.method == "GET":
        if 'user_name' not in session:
            return redirect(url_for('login'))
        else:
            return render_template('check.html', full_name = session['user_name'])
    elif request.method == "POST":
        form = request.form
        weight = form['weight']
        height = form['height']
        time = datetime.datetime.now
        bmi = int(weight) / (int(height) ** 2) *10000
        if bmi < 18.5:
            bmi_type = "underweight"
        elif 18.5 <= bmi < 25:
            bmi_type = "normal"
        elif 25 <= bmi < 30:
            bmi_type = "overweight"
        else:
            bmi_type = "obese"

        if "logged_in" in session:
            # session['user_bmi'] = bmi
            user_id = session['user_id']
            new_body = Body(
                time = time,
                weight = weight,
                height = height,
                bmi = bmi,
                bmi_type = bmi_type
            )
            new_body.save()
            new_body.reload()
            # videos = Video.objects()
            # cardios = Cardio.objects()

            current_user = User.objects.with_id(user_id)
            # current_user.update(add_to_set__bmi_id = str(new_body.id))
            # print(new_body)
            # print(current_user)
            current_user.update(push__bmi_id = new_body)
            # return render_template ('individual.html', all_body = current_user.bmi_id, full_name = session['user_name'], user_id = session['user_id'])
            # return "sadasd"
            return redirect(url_for('individual'))
        else:
            videos = Video.objects()
            cardios = Cardio.objects()
            underweights = Underweight.objects()
            yogas = Yoga.objects()
            exercises = Exercise.objects()
            # overweights = Overweight.objects()
            if bmi < 18.5:
                return render_template('underweight.html', bmi = bmi, yogas=yogas, underweights=underweights, full_name = session['user_name']) 
            elif 18.5 <= bmi < 25:
                return render_template('normal.html', bmi = bmi, videos=videos, yogas=yogas, underweights=underweights, full_name = session['user_name'])
            elif 25 <= bmi < 30:
                return render_template('overweight.html', bmi = bmi, videos=videos, cardios=cardios, exercises=exercises,full_name = session['user_name'])
            elif bmi > 30:
                return render_template('obese.html', bmi = bmi, videos=videos, cardios=cardios, exercises=exercises)
Beispiel #21
0
 def __convert_item_to_video(item):
     return Video(
         title=item['snippet']['title'],
         thumbnail=item['snippet']['thumbnails']['default']['url'],
         channel_name=item['snippet']['channelTitle'],
         url=f"https://youtube.com/watch?v={item['snippet']['resourceId']['videoId']}",
         date=item['snippet']['publishedAt']
     )
def admin():
    user = session.get('username')
    if user is None:
        return redirect(url_for('login'))
    else:
        total_vegetablesAndFruits = Vegetablesfruits.objects()
        total_animals = Animals.objects()
        total_food = Food.objects()
        total_actions = Actions.objects()
        x = len(total_vegetablesAndFruits)
        y = len(total_animals)
        z = len(total_food)
        if request.method == 'GET':
            videos = Video.objects()
            return render_template(
                "admin.html",
                total_vegetablesAndFruits=total_vegetablesAndFruits,
                total_animals=total_animals,
                total_food=total_food,
                total_actions=total_actions,
                x=x,
                y=y,
                z=z,
                videos=videos)
        elif request.method == 'POST':
            form = request.form
            link = form['link']

            ydl = YoutubeDL()

            data = ydl.extract_info(link, download=False)

            title = data['title']
            thumbnail = data['thumbnail']
            views = data['view_count']
            youtube_id = data['id']
            link = link
            video = Video(
                title=title,
                thumbnail=thumbnail,
                views=views,
                youtube_id=youtube_id,
                link=link,
            )
            video.save()
            return redirect(url_for('admin'))
Beispiel #23
0
 def delete_comment_by_video_key_name_without_author(keyname):
   v = Video.get_by_key_name(keyname)
   user = users.get_current_user()
   if v and user:
     comments = v.comment_set
     for c in comments:
       if c.author != user:
         c.delete()
Beispiel #24
0
def main():
    # Initialize FPS Monitor
    fps = FPS().start()

    # Initalize Video Capture
    video = Video()

    # Object Recognition
    # objectRecognition = Mobilenet()
    objectRecognition = Haarcascade()

    # Initialize Object Tracker
    objectTracker = Tracker()

    # Frame Counter
    frameCount = 1
    frameMod = 1

    # Process Frames
    while True:
        frame = video.fetchFrame()
        if frame is None: continue

        # Only read x amount of frames (performance boost)
        # Detect objects in frame
        if frameCount % frameMod == 0:
            # Detect objects in frame
            recognisedObjects = objectRecognition.detect(video.fetchRoiFrame())
            # cv2.imshow("ROI", video.fetchRoiFrame())

            # Track objects detected
            objectTracker.track(recognisedObjects)

            # Debug Object Tracker Data
            objectTracker.debug()

        # Update Frame Counter
        frameCount += 1
        fps.update()
        fps.stop()

        # Draw Frame
        video.drawFrame(objectTracker, fps, frameCount)
        cv2.imshow("Traffic Flow", frame)

        # input("")

        # Quit (q) shortcut
        c = cv2.waitKey(1)
        if c == ord("q"):
            break

    # Release Capture Device
    video.releaseCapture()
    cv2.destroyAllWindows()
Beispiel #25
0
  def delete_video_by_key_name(keyname):
    v = Video.get_by_key_name(keyname)
    if v:
      comments = v.comment_set
      MukioTools.delete(comments)
      cblocks = v.cblock_set
      MukioTools.delete(cblocks)# 新,删永久xml

      v.delete()
Beispiel #26
0
 def get(self):
     args = self.reqparse.parse_args()
     token = args.get('auth-token')
     alumno = Alumno.load_from_token(token)
     if alumno == None:
         return {'response': 'user_invalid'}, 401
     asignatura_id = request.args.get('asignatura_id')
     return Video.get_all_by_asignatura_and_curso(asignatura_id,
                                                  alumno.curso.id)
Beispiel #27
0
def history():
    if "loggedin" in session:
        if session['loggedin'] == True:
            all_video = Video.objects()
            return render_template('history.html', all_video=all_video)
        else:
            return redirect(url_for('login'))
    else:
        return redirect(url_for('login'))
Beispiel #28
0
  def get(self,cid,block=''):
    video = Video.get_by_key_name('vid' + cid)
    if not video:
      video = Video.get_by_key_name(cid)

    if block == 'permanent':#新,双重字幕中的永久字幕,可以通过导入空的xml来覆盖
      block = video.cblock_set.get()
      self.render('pcmt.xml',{'cblock':block})
    else:
      comments = []
      if video:
        cmts = video.comment_set
        #cmts.order('parttitle')
        for c in cmts:
          c.keyid = c.key().id()
          c.postdate += timedelta(hours=+8)
          comments.append(c)

      tmpvars = {'comments':comments}
      self.render('comment.xml',tmpvars)
Beispiel #29
0
def sort_videos(videos):
    dict_videos = list()
    for v in videos:
        dict_videos.append(v.to_dict())
    dict_videos.sort(key=operator.itemgetter('date'))

    _videos = list()
    for v in dict_videos:
        _videos.append(Video.from_dict(v))
    _videos.reverse()
    return _videos
Beispiel #30
0
    def get(self, cid, block=''):
        video = Video.get_by_key_name('vid' + cid)
        if not video:
            video = Video.get_by_key_name(cid)

        if block == 'permanent':  #新,双重字幕中的永久字幕,可以通过导入空的xml来覆盖
            block = video.cblock_set.get()
            self.render('pcmt.xml', {'cblock': block})
        else:
            comments = []
            if video:
                cmts = video.comment_set
                #cmts.order('parttitle')
                for c in cmts:
                    c.keyid = c.key().id()
                    c.postdate += timedelta(hours=+8)
                    comments.append(c)

            tmpvars = {'comments': comments}
            self.render('comment.xml', tmpvars)
Beispiel #31
0
def result_page():
    favorite_video = []
    user_favorite = Video.find_video(session['Account'])
    for video in user_favorite:
        favorite_video.append(video['link'])

    url = request.url
    search = request.args.get('search')
    soup = item.find_search_content(search)
    all_item = item.every_video(soup)
    return render_template("result.html", search=search, all_item=all_item, url=url, favorite_video=favorite_video)
Beispiel #32
0
 def get(self, cid):
     video = Video.get_by_key_name(cid)
     if not video:
         self.error(404)
     else:
         self.render(
             'addblock.html', {
                 'video': video,
                 'title':
                 'Add/Update XML File for Video: ' + video.key().name()
             })
Beispiel #33
0
def favorite_method():
    if session['account']:
        if request.method == "POST":
            url = request.form['url']
            title = request.form['title']
            link = request.form['link']
            img = request.form['img']
            time = request.form['time']
            account = session['account']
            print("the url is {0},the title is {1},the link is {2},the img is {3},the account is {4}".format(url,title,link,img,account))
            Video(account,title,link,img,time).save_to_db()
            return redirect(url)
        else:
            account = session['account']
            user_video = Video(account).fine_video(account)
            print(user_video)
            return render_template("favorite.html", user_video=user_video)

    else:
        return redirect("/login")
def video():
    user = session.get('username')
    allWordSave = Reviews.objects()
    numberOfWords = 0
    for i in allWordSave:
        if i.username == user:
            numberOfWords += 1
    videos = Video.objects()
    return render_template("videos.html",
                           videos=videos,
                           user=user,
                           numberOfWords=numberOfWords)
Beispiel #35
0
def index():
    if request.method == 'GET':  #Get de lay du lieu
        return render_template('index.html')
    elif request.method == 'POST': #Post de tao tai nguyen
        isRight = False
        form = request.form
        link = form['link_yt']
        dl = youtube_dl.YoutubeDL()

        # Check link
        ies = youtube_dl.extractor.gen_extractors()
        for ie in ies:
            if ie.suitable(link) and ie.IE_NAME != 'generic':
                isRight = True
        
        if isRight == True:
            try:
                data = dl.extract_info(link, download=False)
                title = data['title']
                views = data['view_count']
                likes = data['like_count']
                dislikes = data['dislike_count']
                youtube_id = data['id']

                video = Video(
                    title=title,
                    views=views,
                    likes=likes,
                    dislikes=dislikes,
                    youtube_id=youtube_id,
                    link=link,
                    time=datetime.now()
                )

                video.save()
                return render_template('index.html', video=video, template=1)
            except Exception as e:
                return render_template('link-fail.html')
        elif isRight == False:
            return render_template('link-fail.html')
Beispiel #36
0
def download_audio(youtube_id):
    # Count
    all_video=[]
    now = datetime.now()
    count_video = Video.objects()
    for video in count_video:
        if video['time'].day == now.day:
            all_video.append(video)
    
    found_count = Count.objects()
    if (len(found_count) > 0) and (found_count[len(found_count)-1]['time'].day == now.day) and (found_count[len(found_count)-1]['time'].month == now.month) and (found_count[len(found_count)-1]['time'].year == now.year):
        number = len(all_video)
        found_count[len(found_count)-1].update(set__amount=number)
    else:
        new_count = Count(
            amount = 1,
            time = now
        )
        new_count.save()
    
    # Download
    found_video = Video.objects.with_id(youtube_id)
    if found_video is not None:
        # Download
        options = {
        'format': 'bestaudio/audio',
        'outtmpl': '%(id)s'
        }

        dl = youtube_dl.YoutubeDL(options)
        result = dl.extract_info(
        found_video.link,
        download = True
        )

        # Send File
        save_file = found_video.title.replace(" ", "")
        save_file = re.sub('[^A-Za-z0-9]+', '', save_file)
        os.rename(result['id'], save_file + '.mp3')
        try:
            # Set Download Type
            found_video.update(set__download_type="Audio")
            found_video.update(set__time=datetime.now())

            return send_file(save_file + '.mp3', save_file + '.mp3', as_attachment=True)
        except Exception as e:
            return str(e)

        # Delete Video from Database
        # found_video.delete()
    else:
        return 'Video is not found'
Beispiel #37
0
	def create_internal(self, room_id, rank, service, url, title, duration, start_time):
		video_id = Video.create(room_id, rank, service, url, title, duration, start_time)

		recreated_video = Video(video_id)
		assert_equals(room_id, recreated_video.room_id)
		assert_equals(rank, recreated_video.rank)
		assert_equals(service, recreated_video.service)
		assert_equals(url, recreated_video.url)
		assert_equals(title, recreated_video.title)
		assert_equals(duration, recreated_video.duration)
		assert_equals(start_time, recreated_video.start_time)

		return recreated_video
Beispiel #38
0
  def get(self,typ,vid):
    video = Video.all().filter('typ =',typ).filter('vid =',vid).get()
    if not video:
      video = Video(typ = typ,
                    vid = vid)
      if video:
        video.put()
      else:
        self.error(404)

    cmts = memcache.get(str(video.key().id_or_name()))
    if not cmts:
      cmts = video.comment_set
      memcache.set(str(video.key().id_or_name()),cmts)

    tmpvars = {'comments':cmts}
    self.render('comment.xml',tmpvars)
Beispiel #39
0
  def post(self):
    parttitle = unicode(self.request.get('parttitle')).strip()
    #vid = unicode(self.request.get('vid')).strip()
    fileurl = unicode(self.request.get('fileurl')).strip()
    typ = unicode(self.request.get('typ')).strip()
    artkeystr = unicode(self.request.get('articleId')).strip()
    artkey = db.Key(artkeystr)
    if not artkey:
      self.redirect('/')

    art = Article.get(artkey)
    usr = users.get_current_user()
    if art.author == usr:
      self.redirect('/')

    if typ == 'bokecc':

      reg = re.compile(r'http://.*vid=([^&]+)',re.I)
      res = reg.findall(fileurl)

      if len(res) == 1:
        vid = res[0]
      else:
        vid = fileurl

      fileurl = ''
      keyname = 'vid' + vid

    elif typ == 'sina' or typ == 'youku' or typ == '6room' or typ == 'qq':
      vid = fileurl
      fileurl = ''
      keyname = 'vid' + vid

    elif typ == 'video':
      vid = ''
      keyname = MukioTools.rndvid(4)

    else:
      self.error(404)
      
    '''typ = 'sina'
    if not vid:
      typ = 'video'
      if not fileurl:
        typ = 'none'

    if typ == 'none':
      self.redirect('/')
    else:
      if typ == 'sina':
        keyname = 'vid' + vid
      else:
        reg = re.compile(r'vid=([^&]+)',re.I)
        res = reg.findall(fileurl)
        if len(res) == 1:
          typ = 'bokecc'
          vid = res[0]
          keyname = 'vid' + res[0]
        else:
          keyname = MukioTools.rndvid(4)'''

    video = Video(key_name=keyname,
                  typ=typ,
                  vid=vid,
                  fileurl=fileurl,
                  parttitle=parttitle,
                  art=artkey
                  )
    if video:
      video.put()
      self.redirect('/addvideo/' + artkey.name() + '/')
    else:
      self.redirect('/')
Beispiel #40
0
 def delete_permanent_comment(self, key_name):
   video = Video.get_by_key_name(key_name)
   if video:
     if video.art.author == self.user:
       MukioTools.delete_permanent_comment_by_video_key_name(key_name)
Beispiel #41
0
 def delete_user_comment(self, key_name):
   video = Video.get_by_key_name(key_name)
   if video:
     if video.art.author == self.user:
       MukioTools.delete_comment_by_video_key_name_without_author(key_name)
Beispiel #42
0
 def delete_video(self, key_name):
   video = Video.get_by_key_name(key_name)
   if video:
     if video.art.author == self.user:
       MukioTools.delete_video_by_key_name(key_name)
Beispiel #43
0
 def compareAndUpdate(self,article,videos,oldvideos):
   def addkey(i):
     i.keyname = i.key().name()
     return i
   oldvideos = map(addkey,oldvideos)
   for video in videos:
     # logging.info('video:%r' % video)
     flag = 0
     if video[3] != '0':
       for v in oldvideos:
         if v.keyname == video[3]:
           if (v.typ !='video' and v.typ !='sound' and v.keyname != video[2] and v.keyname != 'vid'+video[2]) or v.typ != video[1]:
             MukioTools.delete_video_by_key_name(v.keyname)
             try:
               newvideo = Video(key_name = 'vid'+video[2],
                                parttitle = video[0],
                                fileurl = '',
                                vid = video[2],
                                typ = video[1],
                                art = article.key())
               newvideo.put()
             except:
               logging.info('插入视频失败 %r' % (video))
           else:
             v.parttitle = video[0]
             v.typ = video[1]
             if v.typ == 'video' or v.typ == 'sound':
               v.fileurl = video[2]
               v.vid = ''
             else:
               v.fileurl = ''
               v.vid = video[2]
             v.postdate = datetime.now()
             v.put()
           oldvideos.remove(v)
           flag = 1
           break
     if flag != 1:
       # logging.info('new video:%r' % video)
       if video[1] == 'video' or video[1] == 'sound':
         keyname = MukioTools.rndvid(4)
         fileurl = video[2]
         vid = ''
         # logging.info('new video type video or sound:%r' % video[1])
       else:
         keyname = 'vid'+video[2]
         fileurl = ''
         vid = video[2]
         # logging.info('new video type not video or sound:%r' % video[1])
       # logging.info('hello')
       # logging.info('%r %r %r %r %r' % (keyname,video[1],vid,fileurl,video[0]))
       try:
         newvideo = Video(key_name = keyname,
                          typ = video[1],
                          vid = vid,
                          fileurl = fileurl,
                          parttitle = video[0],
                          art = article.key())
         if not newvideo:
           logging.info('new video Objected failed:%r' % video[1])
         else:
           # logging.info('new video Objected success:%r' % video[1])
           newvideo.put()
       except:
         logging.info('插入视频失败 %r' % (video))
   for v in oldvideos:
     MukioTools.delete_video_by_key_name(v.keyname)
Beispiel #44
0
 def get(self,cid):
   video = Video.get_by_key_name(cid)
   if not video:
     self.error(404)
   else:
     self.render('addblock.html',{'video':video,'title':'Add/Update XML File for Video: ' + video.key().name()})
Beispiel #45
0
  def post(self,typ,vid):
    now = datetime.now() + timedelta(hours=+8)
    #date check
    date = self.request.get('date')
    try:
      date = datetime.strptime(date,'%Y-%m-%d %H:%M:%S')
      postdelta = abs(now - date)
    except:#拒绝不合法的时间格式
      self.response.out.write('busy,code:1')
      return

    #self.response.out.write(str(abs(postdelta.seconds))+'\r\n')#不能给用户看到

    if DELAYCHECK and (postdelta.days != 0 or postdelta.seconds > DELAYMAX):#时间有效性检验,如果与服务器间隔大于60s,就为非法
      self.response.out.write('busy,code:2')
      return


    #post interval limitation
    ipstr = self.request.remote_addr
    ip = Ip.all().filter('ip =',ipstr).get()
    if ip:
      delta = now - ip.lastpostdate
      if delta.days == 0 and abs(delta.seconds) < POSTINTERVAL:
        self.response.out.write('busy,code:3')
        return
      else:
        ip.lastpostdate = now
        ip.put()
    else:
      ip = Ip(ip=ipstr,lastpostdate = now)
      ip.put()
        


    video = Video.all().filter('typ =',typ).filter('vid =',vid).get()
    if not video:
      video = Video(typ = typ,
                    vid = vid)
      if video:
        video.put()
      else:
        self.error(404)

    text = unicode(self.request.get('message')).strip()
    stime = float(self.request.get('playTime'))
    mode = int(self.request.get('mode'))
    fontsize = int(self.request.get('fontsize'))
    color = int(self.request.get('color'))

    cmt = Comment(author_ip=ipstr,
                  text=text,
                  stime=stime,
                  mode=mode,
                  fontsize=fontsize,
                  color=color,
                  cid=video,
                  postdate=(datetime.now() + timedelta(hours=+8))
                  )

    if cmt:
      cmt.put()
      memcache.delete(str(video.key().id_or_name()))
      self.response.out.write('OK')
    else:
      self.response.out.write('Failed')
Beispiel #46
0
 def delete_comment_by_video_key_name(keyname):
   v = Video.get_by_key_name(keyname)
   if v:
     comments = v.comment_set
     MukioTools.delete(comments)
Beispiel #47
0
 def delete_permanent_comment_by_video_key_name(keyname):
   v = Video.get_by_key_name(keyname)
   if v:
     cblocks = v.cblock_set
     MukioTools.delete(cblocks)