def __init__(self, receiver):
     self.root = Tk()
     self.m = Media(self.root)
     self.m.receiver = receiver
     self.root.title("Receiver Controls")
     self.root.protocol("WM_DELETE_WINDOW", self.on_exit)
     self.root.mainloop()
示例#2
0
    def __run_playlist(self):
        import threading, time
        # Use a separate thread to reduce the noticeable lag when finding
        # episodes in a big directory.
        def generate_playlist(playlist_seed, lock):
            from aux import find_more_episodes
            time.sleep(1.5)
            with lock:
                self.playlist += find_more_episodes(playlist_seed)
        playlist_lock = threading.Lock()
        playlist_thread = threading.Thread(target=generate_playlist, args=(self.playlist[-1],playlist_lock))
        playlist_thread.daemon = True
        playlist_thread.start()

        # Watchdog thread
        def watch(m):
            # wait for media setting up
            time.sleep(3.0)
            m.fetch_if_no_local_subtitles()
        from media import Media
        while self.playlist:
            with playlist_lock:
                f = self.playlist.pop(0)
            m = Media(f)
            watch_thread = threading.Thread(target=watch, args=(m,))
            watch_thread.daemon = True
            watch_thread.start()

            m.play()
            
            if singleton.get_mplayer().last_exit_status == 'Quit':
                break

            playlist_thread.join()
示例#3
0
    def POST(self):
        try:
            webData = web.data()
            print "Handle Post webdata is ", webData  # 后台打印日志
            recMsg = receive.parse_xml(webData)  # 解析webData
            if isinstance(recMsg, receive.Msg):  # 若recMsg为消息类
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                print recMsg.MsgType
                if recMsg.MsgType == 'text':
                    content = recMsg.Content
                    picPath = "/home/pi/media/%s.jpg" % content
                    #print "content is %s"%content
                    #print "picPath is %s"%picPath
                    # 若名为content的图片存在,且大小小于2M,则上传到临时素材,获得mediaId
                    if os.path.exists(
                            picPath) and os.path.getsize(picPath) < 2097152:
                        print "Sending picture %s.jpg, size: %sB" % (
                            content, os.path.getsize(picPath))
                        myMedia = Media()
                        accessToken = Basic().get_access_token()
                        mediaType = "image"
                        mediaId = myMedia.upload(accessToken, picPath,
                                                 mediaType)
                        # 发送图片
                        replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
                        return replyMsg.send()
                    else:
                        print "%s not valid" % picPath
                        return "success"
                else:
                    return "success"

            elif isinstance(recMsg, receive.Evt):  # 若recMsg为事件类
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                print recMsg.Event
                # 若事件类型为订阅,发送使用提示
                if recMsg.Event == 'subscribe':
                    #print "Sending qrcode..."
                    # 获取accessToken,上传临时素材
                    #myMedia = Media()
                    #accessToken = Basic().get_access_token()
                    #filePath = "/home/pi/media/qrcode.png"
                    #mediaType = "image"
                    #mediaId = myMedia.upload(accessToken, filePath, mediaType)
                    # 发送二维码
                    # replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
                    # return replyMsg.send()
                    content = "共享拍立得:请发送图片码获取图片"
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()
                else:
                    return "success"
            else:
                print "No action"
                return "success"
        except Exception, Argument:
            return Argument
示例#4
0
	def stream(self):
		from random import random
		while(self.queue):
			if(random() > 0.8):
				self.broadcast(Media(Status('time').file))
				Status('time').delete()
			self.broadcast(Media(self.queue.pop()), title = (random() > 0.75))
		self.stop()
    def __init__(self, frequency, a, b=None, mode_type = 'te', m=1, \
            n=0, ep_r=1, mu_r=1, *args, **kwargs):
        '''
        RectangularWaveguide initializer

        Parameters
        ----------
        frequency : class:`~skrf.frequency.Frequency` object
                frequency band for this media
        a : number
                width of waveguide, in meters.
        b : number
                height of waveguide, in meters. If `None` defaults to a/2
        mode_type : ['te','tm']
                mode type, transverse electric (te) or transverse magnetic
                (tm) to-z. where z is direction of propagation
        m : int
                mode index in 'a'-direction
        n : int
                mode index in 'b'-direction
        ep_r : number, array-like,
                filling material's relative permativity
        mu_r : number, array-like
                filling material's relative permeability
        *args,**kwargs : arguments, keywrod arguments
                passed to :class:`~skrf.media.media.Media`'s constructor
                (:func:`~skrf.media.media.Media.__init__`


        Examples
        ------------
        Most common usage is standard aspect ratio (2:1) dominant
        mode, TE10 mode of wr10 waveguide can be constructed by

        >>> freq = rf.Frequency(75,110,101,'ghz')
        >>> rf.RectangularWaveguide(freq, 100*mil)
        '''
        if b is None:
            b = a / 2.
        if mode_type.lower() not in ['te', 'tm']:
            raise ValueError('mode_type must be either \'te\' or \'tm\'')

        self.frequency = frequency
        self.a = a
        self.b = b
        self.mode_type = mode_type
        self.m = m
        self.n = n
        self.ep_r = ep_r
        self.mu_r = mu_r


        Media.__init__(self,\
                frequency = frequency,\
                propagation_constant = self.kz, \
                characteristic_impedance = self.Z0,\
                *args, **kwargs)
示例#6
0
	def __init__(self, frequency, a, b=None, mode_type = 'te', m=1, \
		n=0, ep_r=1, mu_r=1, *args, **kwargs):
		'''
		RectangularWaveguide initializer
		
		Parameters
		----------
		frequency : class:`~mwavepy.frequency.Frequency` object
			frequency band for this media
		a : number
			width of waveguide, in meters.
		b : number 
			height of waveguide, in meters. If `None` defaults to a/2
		mode_type : ['te','tm']
			mode type, transverse electric (te) or transverse magnetic
			(tm) to-z. where z is direction of propagation
		m : int 
			mode index in 'a'-direction
		n : int
			mode index in 'b'-direction
		ep_r : number, array-like, 
			filling material's relative permativity
		mu_r : number, array-like 
			filling material's relative permeability
		*args,**kwargs : arguments, keywrod arguments
			passed to :class:`~mwavepy.media.media.Media`'s constructor
			(:func:`~mwavepy.media.media.Media.__init__`
		
			
		Examples
		------------
		Most common usage is standard aspect ratio (2:1) dominant 
		mode, TE10 mode of wr10 waveguide can be constructed by
		
		>>> freq = mv.Frequency(75,110,101,'ghz')
		>>> mv.RectangularWaveguide(freq, 100*mil)
		'''
		if b is None: 
			b = a/2.
		if mode_type.lower() not in ['te','tm']:
			raise ValueError('mode_type must be either \'te\' or \'tm\'')
			 
		self.frequency = frequency 
		self.a = a
		self.b = b
		self.mode_type = mode_type
		self.m = m
		self.n = n
		self.ep_r = ep_r
		self.mu_r = mu_r
		
		
		Media.__init__(self,\
			frequency = frequency,\
			propagation_constant = self.kz, \
			characteristic_impedance = self.Z0,\
			*args, **kwargs)
 def setUp(self):
     self.media_object = Media()
     ydl_opts = {
         'format': 'bestaudio/best',
         'postprocessors': [{
             'key': 'FFmpegExtractAudio',
             'preferredcodec': 'mp3',
             'preferredquality': '192',
         }],
     }
示例#8
0
	def broadcast(self, media, offset = 0, title = False, chunks = 128):
		try:
			media.exist()
		except IOError:
			error('cannot open file, skipping')
			return()

		if(title):
			from random import random
			placement = (random() > 0.5)

		if(title and placement):
			try:
				tmp = Status(media.tags['title'], 'the, next, song, is: %s; by %s.' % (media.tags['title'], media.tags['artist']))
				broadcast(Media(tmp.file))
				tmp.delete()
			except TypeError:
				pass

		# transcodes media
		from os import pipe
		(r, w) = pipe()
		try:
			call = media.play((r, w), offset = offset)
		except SeekError:
			error('illegal seek value, skipping')
			return()

		# reads output data to be streamed
		buffer = chunks * 1024
		from os import fdopen
		fp = fdopen(r, 'r')
		try:
			data = fp.read(buffer)
			while(data):
				print(data)
				data = fp.read(buffer)
			call.kill()
			if(title and not(placement)):
				try:
					tmp = Status(media.tags['title'], 'that was: %s; by %s.' % (media.tags['title'], media.tags['artist']))
					broadcast(Media(tmp.file))
					tmp.delete()
				except TypeError:
					pass
		except KeyboardInterrupt:
			call.kill()
			# shutdown
			exit(0)
		# IOError occurs when stream is interrupted (i.e. client disconnect)
		except IOError:
			call.kill()
			# shutdown
			exit(0)
示例#9
0
	def setUp(self):
		if db_url:
			engine = create_engine(db_url)
		else:
			engine = create_engine('sqlite:///:memory:')

		self.media = Media(
			engine,
			install=True,
			db_prefix=base64_url_encode(uuid.uuid4().bytes),
		)
示例#10
0
class mediaui():
    def __init__(self, receiver):
        self.root = Tk()
        self.m = Media(self.root)
        self.m.receiver = receiver
        self.root.title("Receiver Controls")
        self.root.protocol("WM_DELETE_WINDOW", self.on_exit)
        self.root.mainloop()

    def on_exit(self):
        self.m.on_closing()
        self.root.destroy()
示例#11
0
 def POST(self):
     try:
         webData = web.data()
         util.lstr("Handle Post webdata is: ")
         util.lstr(webData)
         # print(type(webData))  # str
         recMsg = receive.parse_xml(webData)
         if isinstance(recMsg, receive.Msg):
             toUser = recMsg.FromUserName
             fromUser = recMsg.ToUserName
             usr = user.UserProfile(recMsg.FromUserName)
             if recMsg.MsgType == 'text':
                 info = 'empty'
                 # 设置 cookie
                 # cookie = web.cookies(count='-1')
                 # info = 'cookie.count = {}'.format(cookie.count)
                 # int_count = int(cookie.count) + 1
                 # web.setcookie('count', str(int_count), 3600)
                 # end 设置 cookie
                 info = '之前的问题是: ' + ','.join(
                     usr.get_info(user.jkey_quetions))
                 usr.set_info(user.jkey_quetions, recMsg.Content)
                 content = '收到问题: ' + recMsg.Content + ' info: ' + info
                 replyMsg = reply.TextMsg(toUser, fromUser, content)
                 return replyMsg.send()
             if recMsg.MsgType == 'image':
                 # 保存图片
                 myMedia = Media()
                 imageUrl = recMsg.PicUrl
                 savedUrl = myMedia.get_saved_url(imageUrl)
                 myMedia.save_user_image(imageUrl)
                 # 发送信息
                 content = '用户: ' + recMsg.FromUserName + ' 发送图片,已保存在: ' + savedUrl
                 replyMsg = reply.TextMsg(toUser, fromUser, content)
                 return replyMsg.send()
                 # mediaId = recMsg.MediaId
                 # replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
                 # return replyMsg.send()
             if recMsg.MsgType == 'voice':
                 content = '用户: ' + recMsg.FromUserName + ' 发送了语音,转化为文字为: ' + recMsg.Recognition
                 replyMsg = reply.TextMsg(toUser, fromUser, content)
                 return replyMsg.send()
             else:
                 return reply.Msg().send()
         else:
             util.lstr("暂且不处理")
             return reply.Msg().send()
     except Exception, Argment:
         util.lstr('========Exception=======')
         util.lstr(traceback.format_exc())
         return Argment
示例#12
0
 def POST(self):
     try:
         webData = web.data()
         util.lstr("Handle Post webdata is: ")
         util.lstr(webData)
         # print(type(webData))  # str
         recMsg = receive.parse_xml(webData)
         if isinstance(recMsg, receive.Msg):
             toUser = recMsg.FromUserName
             fromUser = recMsg.ToUserName
             usr = user.UserProfile(recMsg.FromUserName)
             if recMsg.MsgType == 'text':
                 return self.HandleUserMsg(usr, recMsg, Handle.dialog,
                                           toUser, fromUser)
             elif recMsg.MsgType == 'image':
                 # 保存图片
                 myMedia = Media()
                 imageUrl = recMsg.PicUrl
                 savedUrl = myMedia.get_saved_url(imageUrl)
                 myMedia.save_user_image(imageUrl)
                 # 发送信息
                 content = '用户: ' + recMsg.FromUserName + ' 发送图片,已保存在: ' + savedUrl
                 replyMsg = reply.TextMsg(toUser, fromUser, content)
                 return replyMsg.send()
                 # mediaId = recMsg.MediaId
                 # replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
                 # return replyMsg.send()
             elif recMsg.MsgType == 'voice':
                 content = '用户: ' + recMsg.FromUserName + ' 发送了语音,转化为文字为: ' + recMsg.Recognition
                 replyMsg = reply.TextMsg(toUser, fromUser, content)
                 return replyMsg.send()
             elif recMsg.MsgType == 'event':
                 print(u'event received, recMsg.Content = ' +
                       recMsg.Content)
                 if recMsg.Content == u'unsubscribe':
                     usr.delete()
                     reply.Msg().send()
                 elif recMsg.Content == u'subscribe':
                     return self.HandleUserMsg(usr, recMsg, Handle.dialog,
                                               toUser, fromUser)
             else:
                 return reply.Msg().send()
         else:
             util.lstr("暂且不处理")
             return reply.Msg().send()
     except Exception, Argment:
         util.lstr('========Exception=======')
         util.lstr(traceback.format_exc())
         return Argment
示例#13
0
文件: util.py 项目: 7uice/OpenCast
def build_media_library():
    media = []
    t0 = time.time()
    for root, dir_names, file_names in os.walk(config.MEDIA_BASE_DIR):
        for f in file_names:
            if os.path.splitext(f)[1] in config.SUPPORTED_MEDIA_FORMATS:
                m = Media(os.path.join(root, f))
                media.append(m.json())
    if not media:
        return {"warning": "No media found in {}".format(config.MEDIA_BASE_DIR)}
    with open(config.MEDIA_JSON, "w") as f:
        f.write(json.dumps(media, indent=4))
    elapsed = round(time.time() - t0, 2)
    return {"success": "{} entries written to {} in {} seconds"
                       .format(len(media), config.MEDIA_JSON, elapsed)}
示例#14
0
 def add_feed_media(cls, collection_id, feed_category=None, approve_all=False):
   collection = Collection.get_by_id(int(collection_id))
   medias = []
   if feed_category:
     uri = Collection.YOUTUBE_CATEGORY_FEED % ((collection.region or 'US'), collection.feed_id,
                                               feed_category)
   else:
     uri = Collection.YOUTUBE_FEED % ((collection.region or 'US'), collection.feed_id)
   response = urlfetch.fetch(uri)
   if response.status_code == 200:
     data = simplejson.loads(response.content) or {}
     entries = data['feed']['entry'] if data.get('feed') else []
     ids = ''
     publisher_map = {}
     for entry in entries:
       id = re.search('video:(.*)', entry['id']['$t']).group(1)
       publisher = Publisher.add(host=MediaHost.YOUTUBE, host_id=entry['author'][0]['yt$userId']['$t'])
       deferred.defer(Publisher.fetch_details, publisher.id,
                      _name='publisher-' + publisher.id + '-' + str(uuid.uuid1()),
                      _queue='youtube')
       ids += id + ','
       publisher_map[id] = publisher
     if len(ids):
       youtube3 = get_youtube3_service()
       videos_response = youtube3.videos().list(
         id=ids,
         part='id,snippet,topicDetails,contentDetails,statistics'
       ).execute()
       logging.info('ADD FEED VIDEO: ' + id)
       medias = Media.add_from_snippet(videos_response.get('items', []), collection=collection,
                                       publisher=publisher, approve=approve_all)
   return medias
示例#15
0
 def get_media(self, media_id: Union[Media, int]) -> Media:
     """
     :param media_id: when you pass media_id as Media, we do query from the database again
     :return: Media
     """
     if isinstance(media_id, Media):
         media_id = media_id.id
     cur = self.db.cursor()
     cur.execute(
         """
         SELECT * FROM media WHERE id = ?;
         """,
         (media_id,)
     )
     media = cur.fetchall()[0]
     cur.close()
     return Media.from_dict(
         {
             "id": media_id,
             "hash": media[1],
             "filename": media[2],
             "filesize": media[3],
             "caption": media[4],
             "time_add": media[5],
             "type": MediaType(media[6]),
             "sub_type": media[7],
             "type_addition": media[8],
             "series_uuid": media[9],
             "series_no": media[10],
             "comment": media[11]
         },
         self
     )
示例#16
0
文件: client.py 项目: noonat/omplex
    def playMedia(self, path, arguments):
        address     = arguments.get("address",      None)
        protocol    = arguments.get("protocol",     "http")
        port        = arguments.get("port",         "32400")
        key         = arguments.get("key",          None)
        offset      = int(int(arguments.get("offset",   0))/1e3)
        url         = urlparse.urljoin("%s://%s:%s" % (protocol, address, port), key)
        media       = Media(url)

        log.debug("HttpHandler::playMedia %s" % media)

        # TODO: Select video, media and part here based off user settings
        video = media.get_video(0)
        if video:
            playerManager.play(video, offset)
            timelineManager.SendTimelineToSubscribers()
示例#17
0
def generate(sections, opts):
    scenes = []
    with Pool() as pool:
        scenes = pool.starmap(generate_video_scene,
                              [(s, opts) for s in sections])

    return Media.concat(scenes).mix_in_audio('music.ogg', 1.0, False).path
示例#18
0
 def __init__(self, callNumber, title, subject, author, notes, description,
              publisher, city, series, year):
     Media.__init__(self, callNumber, title, subject, notes)
     self.description = description
     self.year = year
     self.author = author
     self.publisher = publisher
     self.series = series
     self.city = city
     self.items.append('Description: ' + description)
     self.items.append('Year: ' + year)
     self.items.append('Author: ' + author)
     self.items.append('Publisher: ' + publisher)
     self.items.append('City: ' + city)
     self.items.append('Series: ' + series)
     self.items.insert(0, 'Book:')
示例#19
0
    def execute(self):
        # Pre launch set-up
        MyrmidonGame.current_fps = 60
        self.priority = PRIORITY_MAIN_GAME

        # Load all media
        self.media = Media()
        self.media.load_fonts()
        self.media.load_graphics()
        self.media.load_audio()

        # Debug display
        if DEBUG_SHOW_FPS:
            self.fps_text = MyrmidonGame.write_text(0.0, 0.0, font = self.media.fonts['basic'], text = 0)
            self.fps_text.colour = (1, 1, 1, 1)
            self.fps_text.z = -2000

        # Set up starting game objects
        self.galaxy = Galaxy(self)
        self.gui = GUI(self)
        self.switch_game_state_to(GAME_STATE_SOLAR_SYSTEM)

        self.media.audio['ambient'].play(loops = -1)
        
        while True:

            # update debug display
            if DEBUG_SHOW_FPS:
                self.fps_text.text = "fps: " + str(MyrmidonGame.fps)
                
            yield
    def new_media(self, request):
        """
        Generates a new media in the platform.
        """
        logging.debug("[FrontEnd] - Media - Name = {0}".format(request.name))
        logging.debug("[FrontEnd] - Media - Observacion = {0}".format(request.observacion))
        logging.debug("[FrontEnd] - Media - Type = {0}".format(request.m_type))

        resp = messages.CreateMediaResponse()
        try:
            Media.create(observacion=request.observacion, name=request.name, m_type=request.m_type)
        except MediaCreationError as e:
            resp.error = e.value
        else:
            resp.ok = True
        return resp
示例#21
0
def generate_thumbnail(sections):
    random_frame = Media(sections[0].media.src).frame(10).path

    return Image.composite(
        [random_frame, 'thumbnail_template.png']).mix_in_caption(
            sections[0].title,
            '/home/sam/projects/devlogr/work/nishuki_pixels.ttf').path
示例#22
0
 def render_path( self, path = None ):
   name, ext = os.path.splitext( path )
   try:  
     mime = EXTENSIONS[ ext ]
   except KeyError:
     mime = 'text/html'
   self.response.headers[ 'Content-Type' ] = mime
   self.response.write( Media.render( path = path ) )
示例#23
0
    def archive(self):
        # check and create directory
        if not path.exists(self.media_dir):
            mkdir(self.media_dir)

        if User(self.username, self.api).archive():
            Tweets(self.username, self.api).archive()
            Media(self.username, self.api).archive()
示例#24
0
 def POST(self):
     try:
         webData = web.data()
         print "Handle Post webdata is ", webData  #后台打日志
         recMsg = receive.parse_xml(webData)
         myMedia = Media()
         #print recMsg
         #print recMsg.MsgType
         if isinstance(recMsg, receive.Event):
             toUser = recMsg.FromUserName
             fromUser = recMsg.ToUserName
             if recMsg.MsgType == 'event':
                 event = recMsg.Event
                 if event == 'subscribe':
                     content = "Hi, thanks for attention Fancytech WeChat! /::D"
                     replyMsg = reply.TextMsg(toUser, fromUser, content)
                     return replyMsg.send()
         elif isinstance(recMsg, receive.Msg):
             toUser = recMsg.FromUserName
             fromUser = recMsg.ToUserName
             if recMsg.MsgType == 'text':
                 Content = recMsg.Content
                 print Content
                 if Content == '111':
                     content = "别浪费流量,乱发消息!/:wipe"
                 else:
                     content = "Hi, Can I help you ? /::,@"
                 replyMsg = reply.TextMsg(toUser, fromUser, content)
                 print "反馈文字信息成功!!!!!!!!!"
                 return replyMsg.send()
             if recMsg.MsgType == 'image':
                 content = "图片已经接收...Thanks♪(・ω・)ノ"
                 mediaId = recMsg.MediaId
                 accessToken = Basic().get_access_token()
                 myMedia.get(accessToken, mediaId, toUser)
                 replyMsg = reply.TextMsg(toUser, fromUser, content)
                 #replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
                 return replyMsg.send()
             else:
                 return reply.Msg().send()
         else:
             print "暂且不处理"
             return reply.Msg().send()
     except Exception, Argment:
         return Argment
示例#25
0
    def run_abstract_service(self, service_name, persist=False):
        #print "run run_abstract_service(Events, persist) from run_events_service(self, persist=False)"
        i = 1
        service_instance = None
        while True:
            try:
                if isinstance(self.__connection,
                              ONVIFCamera) and self.__connect_state:
                    #print 'Run ' + str(service_name) + ' service'
                    support = self.loop_check_status_abstract_service(
                        'support', service_name)
                    init = self.loop_check_status_abstract_service(
                        'init', service_name)
                    #run = self.loop_check_status_abstract_service('run', service_name)
                    if self.__loop_mode:
                        if support and init:
                            #print 'change state run True ' + str(service_name) + ' service'
                            #print "Call loop_edit_status_abstract_service(run, Events) from run_abstract_service(Events, persist)"
                            self.loop_edit_status_abstract_service(
                                'run', service_name)
                    else:
                        print 'Start ' + str(service_name) + ' service'
                        # self.__services['Event'] = EventService(self.__connection, persist)
                        self.loop_edit_status_abstract_service(
                            'run', service_name)
                        if service_name == 'Analytics':
                            service_instance = Analytics(self, persist)
                        if service_name == 'Device':
                            service_instance = Device(self, persist)
                        if service_name == 'Events':
                            service_instance = Events(self, persist)
                        if service_name == 'Imaging':
                            service_instance = Imaging(self, persist)
                        if service_name == 'Media':
                            service_instance = Media(self, persist)
                        if service_name == 'PTZ':
                            service_instance = PTZ(self, 0, 0, 0, 20, persist,
                                                   None)
                        if service_instance is not None:
                            self.loop_edit_status_abstract_service(
                                'instance', service_name, service_instance)
                            break
                        else:
                            print 'service_instance of ' + str(
                                service_name) + ' is None'

                else:
                    if not isinstance(self.__connection,
                                      ONVIFCamera) or not self.__connect_state:
                        # print 'The connection has not yet been established or connection has been lost'
                        self.try_connect(i)
            except ONVIFError as e:
                self.__connect_state = False
                print 'Exception inside get_support_device: ' + str(e.reason)
                self.try_connect(i)
                continue
            i += 1
def get_medias_by_yourself():
    """ 手动输入medias """
    name = input("请输入名称:")
    post_url = input("请输入海报url:")
    media_url = input("请输入视频链接地址:")
    stars = input("请输入你的评分:")

    return Media(name=name, post_url=post_url, media_url=media_url,
                 stars=stars)
示例#27
0
def generate_video_scene(section, opts):
    audio_path = os.path.splitext(section.media.src)[0] + '.m4a'
    video_path = section.media.src

    audio = Audio(audio_path).ogg().remove_low_freq().denoise().compress()
    video = Media(video_path).set_scale(opts.scale).mix_in_text(
        section.title).mix_in_audio(audio.path, 0.1)

    return video.path
示例#28
0
 def media(self):
     r = requests.get(self._media_url)
     expression = r'"(\w+.JPG)"'
     pattern = re.compile(expression)
     self._media = []
     for item in re.findall(pattern, r.content):
         item_url = self._media_url + item
         self._media.append(Media(item_url))
     return self._media
示例#29
0
    def new_media(self, request):
        """
        Generates a new media in the platform.
        """
        logging.debug("[FrontEnd] - Media - Name = {0}".format(request.name))
        logging.debug("[FrontEnd] - Media - Observacion = {0}".format(
            request.observacion))
        logging.debug("[FrontEnd] - Media - Type = {0}".format(request.m_type))

        resp = messages.CreateMediaResponse()
        try:
            Media.create(observacion=request.observacion,
                         name=request.name,
                         m_type=request.m_type)
        except MediaCreationError as e:
            resp.error = e.value
        else:
            resp.ok = True
        return resp
示例#30
0
    def retrieve(self, media_id):
        if not self.database.has_key(media_id):
            raise RuntimeError(
                "Failed to retrieve media with id %s, it was not found in the database."
                % media_id)

        marshalled_media = self.database.retrieve(media_id)
        return Media(id=marshalled_media["id"],
                     url=marshalled_media["url"],
                     status=marshalled_media["status"])
示例#31
0
 def _playlist_config_to_media_list(plist_config: config.PlaylistFile):
     media = []
     tmp = list(plist_config.media())
     tmp.sort()
     for m in tmp:
         try:
             media.append(Media(m, plist_config.options))
         except FileNotFoundError:
             # File removed between globbing and creation
             pass
     return media
示例#32
0
 def add_to_queue(self, new_transcode):
     video_file_ext = ['.mkv','.mp4','.avi', '.mpegts', '.flv']
     if os.path.exists(new_transcode):
         for path, dirs, files in os.walk(new_transcode):
             for file in files:
                 filename, fileext = os.path.splitext(file)
                 if fileext in video_file_ext:
                     full_video_path = os.path.join(path, file)
                     new_transcode = Media(full_video_path, args=self.args)
                     print(f'Found video file to add to queue {full_video_path}')
                     self.transcode_queue.put(new_transcode)
示例#33
0
def create_media(media: Media) -> Media:
    request = post(f'{API_URI}/medias', json=asdict(media))

    if request.status_code != 201:
        exit(
            f'Error HTTP {request.status_code} for {media.name} : {request.text}'
        )

    print(f'[INFO] {media.name} successfully created')

    media.id = int(request.json()['id'])
    return media
def get_medias_by_csv(filename):
    """ 从csv文件中获取medias """

    medias_list = []
    with open(filename, "r", encoding="utf-8") as f:
        f_csv = csv.reader(f)
        headers = next(f_csv)   # 第一行是标题,不读
        for row in f_csv:
            print(row)
            media = Media(row[0], row[1], row[2], row[3])
            medias_list.append(media)
    return medias_list
示例#35
0
 def list_media(self, available=True):
     """
     List all media objects
     """
     result = []
     for m in (yield self.query(type='media')):
         m = dict(m)
         media = self._db.medialist.get_by_beacon_id(('media', m['id']))
         if not available and media is None:
             media = Media(m['name'], self, m['id'])
         if media:
             result.append(media)
     yield result
示例#36
0
    def __run_playlist(self):
        import threading, time

        # Use a separate thread to reduce the noticeable lag when finding
        # episodes in a big directory.
        def generate_playlist(playlist_seed, lock):
            from aux import find_more_episodes
            time.sleep(1.5)
            with lock:
                self.playlist += find_more_episodes(playlist_seed)

        playlist_lock = threading.Lock()
        playlist_thread = threading.Thread(target=generate_playlist,
                                           args=(self.playlist[-1],
                                                 playlist_lock))
        playlist_thread.daemon = True
        playlist_thread.start()

        # Watchdog thread
        def watch(m):
            # wait for media setting up
            time.sleep(3.0)
            m.fetch_if_no_local_subtitles()

        from media import Media
        while self.playlist:
            with playlist_lock:
                f = self.playlist.pop(0)
            m = Media(f)
            watch_thread = threading.Thread(target=watch, args=(m, ))
            watch_thread.daemon = True
            watch_thread.start()

            m.play()

            if singleton.get_mplayer().last_exit_status == 'Quit':
                break

            playlist_thread.join()
示例#37
0
 def crawlMedia(self, link):
     """
     crawl all media
     """
     headers = {"User-Agent":"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11",
                "Referer":"http://hjbbs.com/index.asp",
                "Connection":"keep-alive",
                "Keep-Alive":115}
     try:
         req = urllib2.Request(
             url = link,
             headers = headers
             )
         res = urllib2.urlopen(req)
     except Exception:
         logger.error("crawlMedia failed: " + link)
     else:
         media  = res.read()
         fp = open(Media.dir(link), "wb")
         fp.write(media)
         fp.close()
         logger.info("crawlMedia OK: " + link)
示例#38
0
 def add_reddit_media(cls, collection_id, reddit_id, approve_all):
   collection = Collection.get_by_id(int(collection_id))
   response = urlfetch.fetch('http://www.reddit.com/r/%s.json?limit=50' % reddit_id)
   content = simplejson.loads(response.content) or {}
   if content.get('error'):
     logging.error('REDDIT ERROR: ' + str(content.get('error')))
   data = content.get('data')
   if data:
     links = data.get('children')
     ids = []
     reddit_ids = {}
     logging.info('FETCHING %s VIDEOS FROM REDDIT' % str(len(links)))
     for link in links:
       link_data = link.get('data') or {}
       if link_data.get('domain') == 'youtube.com' and not link_data.get('over_18') and link_data.get('score') > 100:
         url = link_data.get('url')
         parsed_url = urlparse.urlparse(url)
         host_id = urlparse.parse_qs(parsed_url.query)['v'][0]
         reddit_ids[host_id] = link.get('kind') + '_' + link_data.get('id')
         ids.append(host_id)
 
     youtube3 = get_youtube3_service()
     
     while len(ids) > 0:
       videos_response = youtube3.videos().list(
         id=','.join(ids[0:10]),
         part="id,snippet,topicDetails,contentDetails,statistics"
       ).execute()
       if videos_response.get('error'):
         logging.error(videos_response.get('error').get('error')[0]['reason'])
         return
       medias = Media.add_from_snippet(videos_response.get("items", []),
                                       collection=collection,
                                       approve=approve_all)
       for media in medias:
         if reddit_ids[media.host_id]:
           media.reddit_id = reddit_ids[media.host_id]
           media.put()
       ids = ids[10:]
示例#39
0
文件: playlist.py 项目: ebby/brokentv
 def fetch(self, approve_all=False, max=50, collection=None):
   medias = []
   logging.info('Fetching playlist')
   max = 200 if not self.last_fetch else max
   yt_service = get_youtube_service()
   offset = 1
   while offset <= max:
     feed = yt_service.GetYouTubePlaylistVideoFeed(
         uri=Playlist.YT_PLAYLIST % (self.host_id, offset))
     if not self.name:
       self.name = feed.title.text
       self.publisher = Publisher.add('youtube', feed.author[0].name.text)
       self.put()
     if len(feed.entry) == 0:
       break
     medias = Media.add_from_entry(feed.entry, collection=collection, approve=approve_all, fetch_publisher=True)
     for media in medias:
       PlaylistMedia.add(playlist=self, media=media,
                           approved=(True if approve_all else None))
     offset += len(medias)
   self.last_fetch = datetime.datetime.now()
   self.put()
   return medias
示例#40
0
 def post( self, media_type, id = 'new' ):
   """ Create or update a specific instance """
   self.response.write( Media.render( media_type = media_type, id = id, params = self.request.POST.mixed() ) )
示例#41
0
 def matchScript(self, obj):
     url = obj.group(1)
     mp3url = Media.path(url)
     return '<embed src="' + mp3url + '" loop=false autostart=false name="IMG_English" width="300" height="20"></embed>'
	def __init__(self, title, storyline, poster_image_url, trailer_youtube_url):
		"""Initializes the Movie class and its superclasses with the arguments 'title', 'poster_image_url', 'trailer_youtube_id' and 'storyline'."""
		Media.__init__(self, title, poster_image_url, trailer_youtube_url)
		self.storyline = storyline
示例#43
0
class Game(MyrmidonProcess):

    # Current state
    game_state = 0

    # Player state
    money = 2000000000
    fuel = 0
    crew = 0
    current_system = "Sol"
    current_object = "Earth"

    fuel_cost = 1000000000
    crew_cost = 500000000
    actions_done = {}
    home_planet_result = []

    first_time = True
    
    # Self explanitory object pointers and lists
    fps_text = None
    gui = None
    media = None
    solar_system_objects = []

    player_ship = None
    background = None
    galaxy = None
    
    
    def execute(self):
        # Pre launch set-up
        MyrmidonGame.current_fps = 60
        self.priority = PRIORITY_MAIN_GAME

        # Load all media
        self.media = Media()
        self.media.load_fonts()
        self.media.load_graphics()
        self.media.load_audio()

        # Debug display
        if DEBUG_SHOW_FPS:
            self.fps_text = MyrmidonGame.write_text(0.0, 0.0, font = self.media.fonts['basic'], text = 0)
            self.fps_text.colour = (1, 1, 1, 1)
            self.fps_text.z = -2000

        # Set up starting game objects
        self.galaxy = Galaxy(self)
        self.gui = GUI(self)
        self.switch_game_state_to(GAME_STATE_SOLAR_SYSTEM)

        self.media.audio['ambient'].play(loops = -1)
        
        while True:

            # update debug display
            if DEBUG_SHOW_FPS:
                self.fps_text.text = "fps: " + str(MyrmidonGame.fps)
                
            yield


    def quit_game(self):
        sys.exit()


    def switch_game_state_to(self, state, gui_state = None):
        """
        Pass in a state and this will switch to it.
        It will also clean up everying necessary to go out of the
        previous game state.
        """
        # Undo and destroy everything in the current state
        self.gui.destroy_current_gui_state()
        col = (1.0, 1.0, 1.0)

        if self.game_state == GAME_STATE_SOLAR_SYSTEM:
            for x in self.solar_system_objects:
                x.signal(S_KILL)
            self.solar_system_objects = []
            self.player_ship.signal(S_KILL)
            self.background.signal(S_KILL)
        elif self.game_state == GAME_STATE_GALAXY:
            self.player_ship.signal(S_KILL)
            self.background.signal(S_KILL)

        # Switch to new state
        self.game_state = state

        # Create everything we require
        if state == GAME_STATE_GALAXY:
            self.background = Galaxy_background(self)
            self.gui.fade_toggle()            
            self.gui.switch_gui_state_to(GUI_STATE_GALAXY if gui_state is None else gui_state)
            self.player_ship = Galaxy_player_ship(self)
        elif state == GAME_STATE_SOLAR_SYSTEM:
            self.background = Galaxy_background(self)
            self.solar_system_objects = []
            self.solar_system_objects.append(Solar_system_star(self, self.galaxy.solar_systems[self.current_system]))
            self.gui.fade_toggle()            
            self.gui.switch_gui_state_to(GUI_STATE_SOLAR_SYSTEM if gui_state is None else gui_state)
            self.player_ship = Player_ship(self)


    def do_home_planet_results(self):
        if len(self.home_planet_result) > 0:
            result = self.home_planet_result.pop()
            result[0](self, *result[1])
示例#44
0
 def open(self):
     Media.open(self)
     self.play()
示例#45
0
	def __init__(self, media):
		Media.__init__(self, media)
示例#46
0
 def matchMedia(self, obj):
     url = obj.group(0)
     return Media.path(url)
示例#47
0
文件: channel.py 项目: ebby/brokentv
  def youtube_channel(cls, name=None, user=None, token=None, yt_channel_id=None, yt_playlist_id=None, page_token=None):
    name = name or 'ytchannel'
    channel = Channel(key_name=(yt_channel_id or yt_playlist_id),
                      name=name, privacy=Privacy.FRIENDS, online=True, user=user, youtube=True)
    channel_id = (yt_channel_id or yt_playlist_id)
    medias = []
    all = True

    cached_channel = memcache.get(channel_id)
    #if cached_channel:
    #  return simplejson.loads(cached_channel)


    youtube3 = get_youtube3_service()
    search_response = {}
    if yt_channel_id:
      if yt_channel_id.startswith('HC'):
        channel_response = youtube3.channels().list(
          id=yt_channel_id,
          part='topicDetails',
          maxResults=1
        ).execute()
        if len(channel_response.get('items', [])):
          topic_id = channel_response.get('items')[0]['topicDetails']['topicIds'][0]
          search_response = youtube3.search().list(
            topicId=topic_id,
            part='id,snippet',
            order='date',
            maxResults=(20 if all else 1),
            pageToken=page_token,
            fields='items,nextPageToken',
            type='video'
          ).execute()
      else:
        search_response = youtube3.search().list(
            channelId=yt_channel_id,
            part='id,snippet',
            order='date',
            maxResults=(20 if all else 1),
            pageToken=page_token,
            fields='items,nextPageToken',
            type='video'
          ).execute()
    elif yt_playlist_id:
      search_response = youtube3.playlistItems().list(
          playlistId=yt_playlist_id,
          part='id,snippet',
          maxResults=(20 if all else 1),
          pageToken=page_token,
          fields='items,nextPageToken'
        ).execute()


    logging.info('SEARCH RESPONSE \n \n \n')
    logging.info(search_response)
    next_page_token = search_response.get("nextPageToken")
    if len(search_response.get('items', [])):
      search_ids = ''
      for item in search_response.get('items', []):
        if item['kind'] == 'youtube#searchResult':
          search_ids += item['id']['videoId'] + ','
        elif item['kind'] == 'youtube#playlistItem':
          search_ids += item['snippet']['resourceId']['videoId'] + ','
      videos_response = youtube3.videos().list(
        id=search_ids,
        part="id,snippet,topicDetails,contentDetails,statistics"
      ).execute()

      medias = Media.add_from_snippet(videos_response.get("items", []), approve=True)

      if not all:
        deferred.defer(util.schedule_youtube_channel,
                       name=name,
                       user_id=user.id if user else None,
                       token=token,
                       channel_id=channel_id,
                       yt_channel_id=yt_channel_id,
                       yt_playlist_id=yt_playlist_id,
                       _name='youtube-channel-' + channel_id + '-' + str(uuid.uuid1()),
                       _queue='youtube')

    else:
      logging.error('No search results for youtube channel: ' + str(search_response))

    programs = []
    if user and False:
      programs = programming.Programming.set_user_channel_programs(user.id, channel, medias,
                                                      time=datetime.datetime.now(), reset=True)
    else:
      next_time = datetime.datetime.now()
      for media in medias:
        program = Program.add_program(channel, media, time=next_time)
        if program:
          programs.append(program)
          next_time = next_time + datetime.timedelta(seconds=media.duration)
    if not all:
      broadcast.broadcastNewPrograms(channel, programs, new_channel=True, to_owner=False, token=token)

    if len(medias):
      deferred.defer(programming.Programming.fetch_related_tweets, medias,
                     _name='twitter-' + channel_id + '-' + str(uuid.uuid1()),
                     _queue='twitter',
                     _countdown=30)

    channel_json = channel.toJson()
    channel_json['next_page_token'] = next_page_token
    data_json = {
      'channel': channel_json,
      'programs': [p.toJson() for p in programs]
    }

    memcache.set(channel_id, simplejson.dumps(data_json), time=86400)
    return data_json
示例#48
0
文件: video.py 项目: noonat/elodie
    def __update_using_plist(self, **kwargs):
        """Updates video metadata using avmetareadwrite.

        This method does a lot more than it should. The general steps are...

        1. Check if avmetareadwrite is installed
        2. Export a plist file to a temporary location from the source file
        3. Regex replace values in the plist file
        4. Update the source file using the updated plist and save it to a
           temporary location
        5. Validate that the metadata in the updated temorary movie is valid
        6. Copystat permission and time bits from the source file to the
           temporary movie
        7. Move the temporary file to overwrite the source file

        :param float latitude: Latitude of the file
        :param float longitude: Longitude of the file
        :returns: bool
        """
        if(
            'latitude' not in kwargs and
            'longitude' not in kwargs and
            'time' not in kwargs and
            'title' not in kwargs
        ):
            if(constants.debug is True):
                print 'No lat/lon passed into __create_plist'
            return False

        avmetareadwrite = self.get_avmetareadwrite()
        if(avmetareadwrite is None):
            if(constants.debug is True):
                print 'Could not find avmetareadwrite'
            return False

        source = self.source

        # First we need to write the plist for an existing file
        #   to a temporary location
        with tempfile.NamedTemporaryFile() as plist_temp:
            # We need to write the plist file in a child process
            #   but also block for it to be complete.
            # http://stackoverflow.com/a/5631819/1318758
            avmetareadwrite_generate_plist_command = '%s -p "%s" "%s"' % (
                avmetareadwrite,
                plist_temp.name,
                source
            )
            write_process = subprocess.Popen(
                [avmetareadwrite_generate_plist_command],
                stdout=subprocess.PIPE,
                shell=True
            )
            write_process.communicate()
            if(write_process.returncode != 0):
                if(constants.debug is True):
                    print 'Failed to generate plist file'
                return False

            plist = plist_parser.Plist(plist_temp.name)
            # Depending on the kwargs that were passed in we regex
            #   the plist_text before we write it back.
            plist_should_be_written = False
            if('latitude' in kwargs and 'longitude' in kwargs):
                latitude = str(abs(kwargs['latitude'])).lstrip('0')
                longitude = kwargs['longitude']

                # Add a literal '+' to the lat/lon if it is positive.
                # Do this first because we convert longitude to a string below.
                lat_sign = '+' if latitude > 0 else '-'
                # We need to zeropad the longitude.
                # No clue why - ask Apple.
                # We set the sign to + or - and then we take the absolute value
                #   and fill it.
                lon_sign = '+' if longitude > 0 else '-'
                longitude_str = '{:9.5f}'.format(abs(longitude)).replace(' ', '0')  # noqa
                lat_lon_str = '%s%s%s%s' % (
                    lat_sign,
                    latitude,
                    lon_sign,
                    longitude_str
                )

                plist.update_key('common/location', lat_lon_str)
                plist_should_be_written = True

            if('time' in kwargs):
                # The time formats can be YYYY-mm-dd or YYYY-mm-dd hh:ii:ss
                time_parts = str(kwargs['time']).split(' ')
                ymd, hms = [None, None]
                if(len(time_parts) >= 1):
                    ymd = [int(x) for x in time_parts[0].split('-')]

                    if(len(time_parts) == 2):
                        hms = [int(x) for x in time_parts[1].split(':')]

                    if(hms is not None):
                        d = datetime(ymd[0], ymd[1], ymd[2], hms[0], hms[1], hms[2])  # noqa
                    else:
                        d = datetime(ymd[0], ymd[1], ymd[2], 12, 00, 00)

                    offset = time.strftime("%z", time.gmtime(time.time()))
                    time_string = d.strftime('%Y-%m-%dT%H:%M:%S{}'.format(offset))  # noqa
                    plist.update_key('common/creationDate', time_string)
                    plist_should_be_written = True

            if('title' in kwargs):
                if(len(kwargs['title']) > 0):
                    plist.update_key('common/title', kwargs['title'])
                    plist_should_be_written = True

            if(plist_should_be_written is True):
                plist_final = plist_temp.name
                plist.write_file(plist_final)
            else:
                if(constants.debug is True):
                    print 'Nothing to update, plist unchanged'
                return False

            # We create a temporary file to save the modified file to.
            # If the modification is successful we will update the
            #   existing file.
            # We can't call self.get_metadata else we will run into
            #   infinite loops
            # metadata = self.get_metadata()
            temp_movie = None
            with tempfile.NamedTemporaryFile() as temp_file:
                temp_movie = '%s.%s' % (temp_file.name, self.get_extension())

            # We need to block until the child process completes.
            # http://stackoverflow.com/a/5631819/1318758
            avmetareadwrite_command = '%s -a %s "%s" "%s"' % (
                avmetareadwrite,
                plist_final,
                source,
                temp_movie
            )
            update_process = subprocess.Popen(
                [avmetareadwrite_command],
                stdout=subprocess.PIPE,
                shell=True
            )
            update_process.communicate()
            if(update_process.returncode != 0):
                if(constants.debug is True):
                    print '%s did not complete successfully' % avmetareadwrite_command  # noqa
                return False

            # Before we do anything destructive we confirm that the
            #   file is in tact.
            check_media = Media.get_class_by_file(temp_movie, [self.__class__])
            check_metadata = check_media.get_metadata()
            if(
                (
                    'latitude' in kwargs and
                    'longitude' in kwargs and
                    check_metadata['latitude'] is None and
                    check_metadata['longitude'] is None
                ) or (
                    'time' in kwargs and
                    check_metadata['date_taken'] is None
                )
            ):
                if(constants.debug is True):
                    print 'Something went wrong updating video metadata'
                return False

            # Copy file information from original source to temporary file
            #   before copying back over
            shutil.copystat(source, temp_movie)
            stat = os.stat(source)
            shutil.move(temp_movie, source)
            os.utime(source, (stat.st_atime, stat.st_mtime))

            return True
示例#49
0
 def get( self, media_type, id ):
   """ Get a specific instance """
   self.response.write( Media.render( media_type = media_type, id = id ) )
示例#50
0
文件: server.py 项目: lyager/pyplex
 def getMedia(self, mediaPath):
     result = self.query(mediaPath)
     media = Media(result, self)
     return media.getMediaObject()
示例#51
0
 def get( self, media_type, cursor = None ):
   """Get the first or next page of the collection"""
   self.response.write( Media.render( media_type = media_type, cursor = cursor ) )
示例#52
0
  def fetch(self, collection=None, approve_all=False):
    all_medias = []

    if self.host == MediaHost.YOUTUBE:
      if not self.channel_id:
        yt_service = get_youtube_service()
        try:
          user_entry = yt_service.GetYouTubeUserEntry(username=self.host_id)
        except Exception as e:
          logging.error(e)
          return
        desc = user_entry.content.text
        desc = desc.decode('utf-8').replace("\n", r" ") if desc else None
        
        picture = urlfetch.fetch(user_entry.thumbnail.url)
        self.name = user_entry.title.text
        self.picture = db.Blob(picture.content)
        self.description = desc
        self.link = user_entry.link[0].href
        self.channel_id = re.search('/channel/(.*)', self.link).groups()[0]
        self.put()

      
      youtube3 = get_youtube3_service()
      
      
      publishedAfter = '1970-01-01T00:00:00Z'
      if constants.PUBLISHED_AFTER:
        publishedAfter = constants.PUBLISHED_AFTER
      elif self.last_fetch:
        publishedAfter = self.last_fetch.isoformat('T') + 'Z'
      
      ordering = ['date'] if self.last_fetch else ['date', 'rating', 'viewCount']
      
      for order in ordering:
        medias = []
        next_page_token = ''
        while next_page_token is not None:
          search_response = youtube3.search().list(
            channelId=self.channel_id,
            part='id',
            order=order,
            pageToken=next_page_token,
            publishedAfter=publishedAfter,
            maxResults=20
          ).execute()
          search_ids = ''
          for item in search_response.get('items', []):
            if item['id']['kind'] == 'youtube#video':
              search_ids += item['id']['videoId'] + ','
          videos_response = youtube3.videos().list(
            id=search_ids,
            part="id,snippet,topicDetails,contentDetails,statistics"
          ).execute()
          medias = Media.add_from_snippet(videos_response.get("items", []),
                                          collection=collection,
                                          publisher=self,
                                          enforce_category=len(collection.categories) > 0,
                                          approve=approve_all)
  
          all_medias += medias
          next_page_token = search_response.get('tokenPagination', {}).get('nextPageToken')

      self.last_fetch = datetime.datetime.now()
      self.put()
    if len(all_medias) and not approve_all:
      msg = emailer.Email(emailer.Message.FETCH, data={'count': len(medias)})
      for uid in constants.SUPER_ADMINS:
        user = User.get_by_key_name(uid)
        msg.send(user)