Example #1
0
def upload_video(upload_dict: dict) -> None:
    upload_way_dict = {'bd': BDUpload,
                       's3': S3Upload}
    upload_way = upload_way_dict.get(config['upload_by'])
    uploader = upload_way()
    user_config = get_user(upload_dict['User'])
    result = uploader.upload_item(f"{upload_dict['Path']}", upload_dict['Title'])
    if not result:
        raise RuntimeError('Upload error')
    if config['upload_by'] == 'bd':
        share_url = uploader.share_item(upload_dict['Title'])
        if config['enable_mongodb']:
            data = {"Title": upload_dict['Origin_Title'],
                    "Date": upload_dict['Date'],
                    "Link": share_url,
                    "ASS": upload_dict['ASS']}
            insert_video(upload_dict['User'], data)
    elif config['upload_by'] == 's3':
        if config['enable_mongodb']:
            share_url = f"gets3/{quote(upload_dict['Title'])}"
            data = {"Title": upload_dict['Origin_Title'],
                    "Date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    "Link": share_url,
                    "ASS": upload_dict['ASS']}
            insert_video(upload_dict['User'], data)
    else:
        raise RuntimeError(f'Upload {upload_dict["Title"]} failed')
    pub = Publisher()
    data = {'Msg': f"[下载提示] {upload_dict['Title']} 已上传, 请查看https://matsuri.design/",
            'User': user_config['user']}
    pub.do_publish(data, 'bot')
Example #2
0
 def __init__(self, size):
   Publisher.__init__(self)
   self.size = size
   self.count = size ** 3
   self.points = np.arange(0, self.count)
   self.point_numbers = np.arange(0, self.count)
   self.clear()
def send_hls(title, ddir, path):
    pub = Publisher()
    hls_dict = {
        'Title': title,
        'Ddir': ddir,
        'Path': path,
    }
    pub.do_publish(hls_dict, 'hls')
Example #4
0
File: main.py Project: jj4jj/sdv
 def test_push_online():
     dbc.createKey("online")
     pub = Publisher(config.REDIS_MQ_HOST, config.REDIS_MQ_PORT, config.REDIS_MQ_DB)
     import random
     while True:
         add = random.randint(-100,100);
         dbc.incKey("online","2003", add)
         pub.publish('online', {'server':'2003', "op":"inc", "value":add, "time": datasets.current_ms()})
         time.sleep(1)
 def upload_record(self, ddir: str) -> None:
     pub = Publisher()
     upload_dict = {
         'Title': self.video_dict['Title'] + '.txt',
         'Target': self.video_dict['Target'],
         'Path': f'{ddir}/{self.video_dict["Title"]}.txt',
         'User': self.video_dict['User'],
         'Record': True,
         'Origin_Title': self.video_dict['Origin_Title']
     }
     pub.do_publish(upload_dict, 'upload')
Example #6
0
 def Next(self):
     self.CurrentLevel += 1
     if self.CurrentLevel < len(self.Levels):
         self.Level = self.Levels[self.CurrentLevel](self.Window)
         self.Level.Number = self.CurrentLevel + 1  # Use 1-based here.
         Publisher.sendMessage("level.started", self.Level)
         self.PlayedLevels.append(self.Level)
     else:
         self.Level = None
         Publisher.sendMessage("game.over", self.PlayedLevels)
     pyglet.media.load(data.filepath("sound/start1.wav"), streaming=False).play()
Example #7
0
 def add_node(self):
     node = Node(self)
     id = "new_node"
     ctr = 1
     while self.get_node(id) != None:
         id = "new_node({0})".format(ctr)
         ctr += 1
     node.id(id)
     self.nodes.append(node)
     pub.sendMessage("node_added", {"node": node})
     return node
Example #8
0
 def onkeypress(self, message):
     key = int(message.topic[-1])
     if key == pyglet.window.key.DOWN:
         if self.currentSelection < len(self.labels)-1:
             self.currentSelection += 1
     elif key == pyglet.window.key.UP:
         if self.currentSelection > 0:
             self.currentSelection -= 1
     elif key in (pyglet.window.key.ENTER, pyglet.window.key.RETURN):
         action = ("new", "exit")[self.currentSelection]
         
         Publisher.sendMessage("game.%s" % action)
         
     self.menuBullet.y = self.ypositions[self.currentSelection]
     self.highlight(self.currentSelection)
Example #9
0
 def __init__(self):
     handlers = [(r"/", MainHandler),
                 (r'/login', LoginHandler),
                 (r'/register', RegisterHandler),
                 (r'/createGame', CreateGameHandler),
                 (r'/game', GameHandler),
                 (r'/joinGame/([0-9]+)', JoinGameHandler),
                 (r'/quitGame', QuitGameHandler),
                 (r'/roomAction', RoomActionHandler),
                 (r'/setQuestion', SetQuestionHandler),
                 (r'/subscribe/(\w+)', SubscribeHandler),
                 (r'/inTurn/(\w+)', InTurnActionHandler),
                 (r'/chat', ChatHandler),
                 ]
     settings = dict(
         cookie_secret="43oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
         login_url="/login",
         template_path=os.path.join(os.path.dirname(__file__), "templates"),
         static_path=os.path.join(os.path.dirname(__file__), "static"),
         xsrf_cookies=True,
         debug=True,
         )
     self.db = scoped_session(sessionmaker(bind=engine))
     self.db.query(Game).delete()
     self.db.query(GamePlayer).delete()
     self.db.commit()
     create_all()
     self.auth = AuthManager(self.db)
     publishers['hall'] = Publisher()
     tornado.web.Application.__init__(self, handlers, **settings)
Example #10
0
 def tick(self, dt):
     if self.State == "FADEIN":
         self.Opacity += dt / self.FadeTime * 255
         if self.Opacity >= 255:
             self.Opacity = 255
             self.State = "COUNTING"
         self.setOpacity()
     elif self.State == "COUNTING":
         self.Timeout -= dt
         if self.Timeout <= 0:
             self.State = "FADEOUT"
     elif self.State == "FADEOUT":
         self.Opacity -= dt / self.FadeTime * 255
         if self.Opacity <= 0:
             self.stop()
             Publisher.sendMessage("instruction.complete", self)
         self.setOpacity()
def send_upload(video_dict, path):
    if not config['enable_upload']:
        return
    pub = Publisher()
    ass, txt = get_trans_ass(video_dict['Title'], video_dict['Start_timestamp'], video_dict['End_timestamp'])
    upload_dict = {
        'Title': video_dict['Title'],
        'Filename': video_dict['Filename'],
        'Target': video_dict['Target'],
        'Date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'Path': path,
        'User': video_dict['User'],
        'Origin_Title': video_dict['Origin_Title'],
        'ASS': ass,
        'Txt': txt
    }
    pub.do_publish(upload_dict, 'upload')
Example #12
0
def upload_record(upload_dict: dict) -> None:
    user_config = get_user(upload_dict['User'])
    uploader = BDUpload()
    result = uploader.upload_item(upload_dict['Path'], upload_dict['Title'])
    if not result:
        raise RuntimeError('Upload error')
    if config['upload_by'] == 'bd':
        share_url = uploader.share_item(upload_dict['Title'])
        if config['enable_mongodb']:
            data = {"Title": upload_dict['Origin_Title'],
                    "Date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    "Record": share_url}
            insert_video(upload_dict['User'], data)
            pub = Publisher()
            data = {'Msg': f"[同传提示] {upload_dict['Title']} 已记录, 请查看https://matsuri.design/",
                    'User': user_config['user']}
            pub.do_publish(data, 'bot')
def upload_video(upload_dict: dict) -> None:
    upload_way_dict = {'bd': BDUpload, 's3': S3Upload}
    upload_way = upload_way_dict.get(config['upload_by'])
    uploader = upload_way()
    user_config = get_user(upload_dict['User'])
    result = uploader.upload_item(f"{upload_dict['Path']}",
                                  upload_dict['Filename'])
    if not result:
        raise RuntimeError('Upload error')
    if config['upload_by'] == 'bd':
        share_url = uploader.share_item(upload_dict['Filename'])
        if config['enable_mongodb']:
            data = {
                "Title": upload_dict['Origin_Title'],
                "Date": upload_dict['Date'],
                "Link": share_url,
                "ASS": upload_dict['ASS'],
                "Txt": upload_dict['Txt']
            }
            insert_video(upload_dict['User'], data)
    elif config['upload_by'] == 's3':
        if config['enable_mongodb']:
            share_url = f'https://matsuri.design/{config["s3_bucket"]}/{quote(upload_dict["Filename"])}'
            m3u8_url = f'https://matsuri.design/{config["s3_bucket"]}/{quote(upload_dict["Title"]) + ".m3u8"}'
            data = {
                "Title": upload_dict['Origin_Title'],
                "Date": upload_dict['Date'],
                "Link": share_url,
                "ASS": upload_dict['ASS'],
                "Txt": upload_dict['Txt'],
                "M3U8": m3u8_url
            }
            insert_video(upload_dict['User'], data)
    else:
        raise RuntimeError(f'Upload {upload_dict["Filename"]} failed')
    pub = Publisher()
    data = {
        'Msg':
        f"[下载提示] {upload_dict['Title']} 已上传, 请查看https://matsuri.design/",
        'User': user_config['user']
    }
    pub.do_publish(data, 'bot')
Example #14
0
 def post(self):
     name = self.get_argument('name')
     user = self.current_user        
     if self.db.query(GamePlayer).filter(GamePlayer.user==self.current_user).count() > 0:
         self.write(u'你已经在房间' + str(user.game_play.game.id) + u'里')
         return
     game = Game.create(name, user)
     publishers[game.channel] = Publisher()
     HallMessager.publish(self, 'add', game)
     self.db.add(game)
     self.redirect('/game')
Example #15
0
    def tick(self, dt):
        tipped = self.Teeter.tick(dt)
        if tipped:
            Publisher.sendMessage("level.ended", self)

        self.Pipe.tick(dt)

        for obj in self.CurrentObjects:
            obj.tick(dt)
            # Did the object fall off the screen?
            if obj.y < 0:
                # Oh no, the level is lost!
                self.CurrentObjects = []
                self.Won = False
                Publisher.sendMessage("level.ended", self)
            elif self.Teeter.intersects(obj):
                self.LandPlayer.play()
                self.Teeter.hold(obj)
                self.CurrentObjects.remove(obj)
                if self.NextObjectInQueue == self.NullObject and not self.CurrentObjects:
                    self.Won = True
                    Publisher.sendMessage("level.ended", self)

        if self.Instruction:
            self.Instruction.tick(dt)
Example #16
0
 def __init__(self):
     pyglet.window.Window.__init__(self, width=800, height=600, caption="Chubby Chaser v%s" % constants.VERSION)
     keys = key.KeyStateHandler()
     self.push_handlers(keys)
     self.fps = pyglet.clock.ClockDisplay()
     pyglet.clock.schedule_interval(self.tick, 1/30.0)
     
     self.State = splashstate.SplashState(self)
     Publisher.subscribe(self.onGameNew, "game.new")
     Publisher.subscribe(self.onGameOver, "game.over")
     Publisher.subscribe(self.onGameExit, "game.exit")
Example #17
0
    def get_endpoint(self, endpoint):
        """
        Parse /instrument/channel into specific channel handlers.
        """
        if not endpoint.startswith('/'): return
        try:
            _, name, channel = endpoint.split('/', 3)
        except ValueError:
            return
        if name not in INSTRUMENTS:
            raise HTTPError(404, "Instrument %s is not online" % name)

        # There is role reversal with publisher and subscriber for the control
        # channel: here the instrument is acting as a single subscriber to
        # all of the web clients who are publishing commands to control it.
        if channel == 'control':
            return lambda *args, **kw: Publisher(
                INSTRUMENTS[name].channel[channel], *args, **kw)
def process_video(video_dict):
    """
    处理直播视频,包含bot的发送,视频下载,视频上传和存入数据库
    :param video_dict: 含有直播视频数据的dict
    :return: None
    """
    user_config: dict = get_user(video_dict['User'])
    if not user_config['download']:
        return None
    ddir: str = get_ddir(user_config)
    check_ddir_is_exist(ddir)
    logger.info(f'{video_dict["Provide"]} Found A Live, starting downloader')
    video_dict['Origin_Title'] = video_dict['Title']
    video_dict['Title'] = AdjustFileName(video_dict['Title']).adjust(ddir)
    video_dict['Start_timestamp'] = int(datetime.now().timestamp() * 1000)
    if video_dict["Provide"] == 'Youtube':
        result: str = downloader(r"https://www.youtube.com/watch?v=" + video_dict['Ref'], video_dict['Title'],
                                 config['proxy'], ddir, user_config, config['youtube_quality'])
    else:
        result: str = downloader(video_dict['Ref'], video_dict['Title'], config['proxy'], ddir, user_config)
    pub = Publisher()
    if result:
        video_dict['End_timestamp'] = int(datetime.now().timestamp() * 1000)
        data = {'Msg': f"[下载提示] {result} 已下载完成,等待上传",
                'User': user_config['user']}
        logger.warning(data)
        pub.do_publish(data, 'bot')
    if config['enable_upload']:
        upload_dict = {
            'Title': result,
            'Target': video_dict['Target'],
            'Date': video_dict['Date'],
            'Path': f'{ddir}/{result}',
            'User': video_dict['User'],
            'Origin_Title': video_dict['Origin_Title'],
            'ASS': get_ass(video_dict)
        }
        pub.do_publish(upload_dict, 'upload')
        pub.do_publish(video_dict['Target'], 'cq')
Example #19
0
    def get_endpoint(self, endpoint):
        """
        Parse /instrument/channel into specific channel handlers.
        """
        if not endpoint.startswith('/'): return
        try:
            _, name, channel = endpoint.split('/', 3)
        except ValueError:
            return
        if name not in INSTRUMENTS:
            INSTRUMENTS[name] = instrument.Instrument(name=name)
        #print "NICE connection to",name,channel,INSTRUMENTS[name],INSTRUMENTS[name].channel[channel]
        #print INSTRUMENTS[name].channel[channel].channel_state()

        # There is role reversal with publisher and subscriber for the control
        # channel: the instrument is acting as a single subscriber for all
        # the web clients who are publishing commands to control it.
        if channel == 'control':
            return lambda *args, **kw: Subscriber(
                INSTRUMENTS[name].channel[channel], *args, **kw)
        elif channel in INSTRUMENTS[name].channel:
            return lambda *args, **kw: Publisher(
                INSTRUMENTS[name].channel[channel], *args, **kw)
Example #20
0
def doSomething1():
    print '--- SENDING topic1 message ---'
    pub.sendMessage('topic1', 'message1')
    print '---- SENT topic1 message ----'
Example #21
0
# ------------ create some listeners --------------

def listener1(msg, extra=None):
    print 'Function listener1 received', msg.data

class Listener:    
    def onTopic1(self, msg, extra=None):
        print 'Method Listener.onTopic1 received', `msg.data`
    def onTopic2(self, msg):
        print 'Method Listener.onTopic2 received', `msg.data`
    def __call__(self, msg):
        print 'Listener() received', `msg.data`

# ------------ register listeners ------------------

pub.subscribe(listener1, 'topic1')

listener2 = Listener()
pub.subscribe(listener2) # ALL topics!
pub.subscribe(listener2.onTopic1, 'topic1')
pub.subscribe(listener2.onTopic2, 'topic2')

# ------------ create a couple of senders --------------

def doSomething1():
    print '--- SENDING topic1 message ---'
    pub.sendMessage('topic1', 'message1')
    print '---- SENT topic1 message ----'
    
def doSomething2():
    print '--- SENDING topic2 message ---'
Example #22
0
 def remove_node(self, node):
     if not node is None:
         self.nodes.remove(node)
         pub.sendMessage("node_removed", {"node": node})
Example #23
0
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

try:
    from pubsub import Publisher
    WxPublisher = Publisher()
except ImportError:
    from pubsub import pub
    WxPublisher = pub.getDefaultPublisher()


class Publisher(object):

    def __init__(self):
        self._listeners = {}

    def publish(self, topic, data):
        self._sendMessage(topic, data)

    def subscribe(self, listener, topic, key=None):
        """Start to listen to messages with the specified ``topic``.
 def uploader(filename, path):
     upload_dict = {'Path': path, 'Filename': filename, 'Is_m3u8': True}
     pub = Publisher()
     pub.do_publish(upload_dict, 'upload')
Example #25
0
 def on_mouse_press(self, x, y, button, mods):
     if button == pyglet.window.mouse.LEFT:
         Publisher.sendMessage("click.left")
Example #26
0
 def Start(self):
     self.setInstruction(self.Instructions[0])
     Publisher.subscribe(self.onInstructionComplete, "instruction.complete")
     self.setNextItem()
def send_bot(result, user):
    pub = Publisher()
    data = {'Msg': f"[下载提示] {result} 已下载完成,等待上传",
            'User': user}
    logger.warning(data)
    pub.do_publish(data, 'bot')
Example #28
0
def doSomething2():
    print '--- SENDING topic2 message ---'
    pub.sendMessage('topic2', 123)
    print '---- SENT topic2 message ----'
Example #29
0
from pubsub import Broker, Publisher, Subscriber
br = Broker('./store/')
p1 = Publisher('p1', br)
p1.addTopic('t1')
p2 = Publisher('p2', br)
p2.addTopic('t2')
c1 = Subscriber('c1', br)
c1.addTopic('t1')
c2 = Subscriber('c2', br)
c2.addTopic('t2')
p2.publish('t2', 'hello t2')
p1.publish('t1', 'hello t1')
Example #30
0
#!/usr/bin/python

from message_bus import MessageBus
from pubsub import Publisher, Subscriber
from flask import Flask
import time

bus = MessageBus()
bus.add_topic('saleem')

publisher = Publisher('Pub1')
bus.bind('saleem', publisher)

sub1 = Subscriber('Sub1')
sub2 = Subscriber('Sub2')
bus.bind('saleem', sub1)
bus.bind('saleem', sub2)

publisher.publish('Hello Saleem')

for x in xrange(20):
    publisher.publish('Pub1 : %s: Counter ' % (x))

time.sleep(1)
sub3 = Subscriber('Sub3')
bus.bind('saleem', sub3)
Example #31
0
 def subscribe(self):
     for callback, event in self.Subscriptions:
         Publisher.subscribe(callback, event)
Example #32
0
 def on_key_press(self, symbol, modifiers):
     Publisher.sendMessage("keypress.%s" % symbol, modifiers)
Example #33
0
class TrueFilter(Filter):
    def _check(self, k, v, msg):
        return True


r = Reader(config.crypto.slack)
r.start()

cmd_filter = RegexFilter(text='^![a-z]+',
                         id='CMD_FILTER',
                         topic='cmd',
                         user=True)
ch_filter = ChannelFilter(type='message',
                          id="CH_FILTER",
                          topic="ch_",
                          user=True)
msg_filter = Filter(type='message', id='MSG_FILTER', topic='msg', user=True)
at_filter = AtFilter(text='^<@(?P<user>\w+)>',
                     id='AT_FILTER',
                     topic='cmd',
                     user=True,
                     bot=r._id)

s = Stream(cmd_filter, ch_filter, msg_filter, at_filter)
p = Publisher('tcp://*:4930')
p.open()
for event, topics in s(r.events):
    if topics:
        p.publish('firehose', event)
    for topic in topics:
        p.publish(topic, event)
Example #34
0
 def on_change(self, key):
     if self.loaded:
         self.network.save()
         pub.sendMessage("node_changed", {"node": self, "key": key})