Esempio n. 1
0
def add_posts():

    ch_name = request.form.get("ch_name")

    if Channel.exists(ch_name):
        return Channel.jsonify_posts(ch_name)
    else:
        return jsonify({"error": True})
Esempio n. 2
0
def channel_exists():
    ch_name = request.form.get("channel")
    ch_owner = request.form.get("owner")

    if Channel.exists(ch_name):
        return jsonify({"success": False})
    else:
        # add new channel immediately to avoid duplicate being added at same time
        Channel(ch_name, ch_owner)  # create new channel object
        return jsonify({"success": True})
Esempio n. 3
0
File: apiv1.py Progetto: joyider/OSP
    def post(self):
        """
            Creates a New Channel
        """
        if 'X-API-KEY' in request.headers:
            requestAPIKey = apikey.apikey.query.filter_by(
                key=request.headers['X-API-KEY']).first()
            if requestAPIKey != None:
                if requestAPIKey.isValid():
                    args = channelParserPost.parse_args()
                    newChannel = Channel.Channel(int(requestAPIKey.userID),
                                                 str(uuid.uuid4()),
                                                 args['channelName'],
                                                 int(args['topicID']),
                                                 args['recordEnabled'],
                                                 args['chatEnabled'],
                                                 args['commentsEnabled'],
                                                 args['description'])
                    db.session.add(newChannel)
                    db.session.commit()

                    return {
                        'results': {
                            'message': 'Channel Created',
                            'apiKey': newChannel.streamKey
                        }
                    }, 200
        return {'results': {'message': "Request Error"}}, 400
Esempio n. 4
0
    def post(self):
        """
            Creates a New Channel
        """
        if 'X-API-KEY' in request.headers:
            requestAPIKey = apikey.apikey.query.filter_by(key=request.headers['X-API-KEY']).first()
            if requestAPIKey is not None:
                if requestAPIKey.isValid():
                    args = channelParserPost.parse_args()
                    newChannel = Channel.Channel(int(requestAPIKey.userID), str(uuid.uuid4()), args['channelName'], int(args['topicID']), args['recordEnabled'], args['chatEnabled'], args['commentsEnabled'], args['description'])

                    userQuery = Sec.User.query.filter_by(id=int(requestAPIKey.userID)).first()

                    # Establish XMPP Channel
                    from app import ejabberd
                    sysSettings = settings.settings.query.all()[0]
                    ejabberd.create_room(newChannel.channelLoc, 'conference.' + sysSettings.siteAddress, sysSettings.siteAddress)
                    ejabberd.set_room_affiliation(newChannel.channelLoc, 'conference.' + sysSettings.siteAddress, int(requestAPIKey.userID) + "@" + sysSettings.siteAddress, "owner")

                    # Default values
                    for key, value in globalvars.room_config.items():
                        ejabberd.change_room_option(newChannel.channelLoc, 'conference.' + sysSettings.siteAddress, key, value)

                    # Name and title
                    ejabberd.change_room_option(newChannel.channelLoc, 'conference.' + sysSettings.siteAddress, 'title', newChannel.channelName)
                    ejabberd.change_room_option(newChannel.channelLoc, 'conference.' + sysSettings.siteAddress, 'description', userQuery.username + 's chat room for the channel "' + newChannel.channelName + '"')

                    db.session.add(newChannel)
                    db.session.commit()

                    return {'results': {'message':'Channel Created', 'apiKey':newChannel.streamKey}}, 200
        return {'results': {'message':"Request Error"}}, 400
Esempio n. 5
0
    def listen(self, host='', port=9999):
        # define host como o ip local
        if not host:
            host = socket.gethostbyname(socket.gethostname())

        self.server_address = (host, port)

        # Create a TCP/IP socket
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # Bind the socket to the port
        self.server_socket.bind(self.server_address)
        print('Conectando em {} porta {}'.format(*self.server_address))

        # Por padrão cria 5 canais
        if self.channels_amount < 1:
            self.channels_amount = 5
        self.channels_list = [
            Channel() for num in range(0, self.channels_amount)
        ]

        # Listen for incoming connections
        self.server_socket.listen(10)

        # Add server socket to the list of readable connections
        self.connected_list.append(self.server_socket)
Esempio n. 6
0
def logout():
    try:
        del_user = User(session['user'], session["channel"])
        del_from = Channel(session["channel"], 0)
    except KeyError:
        return redirect("/", "303")
    try:
        users.remove(del_user)
        channels[channels.index(del_from)].users.remove(session['user'])
    except ValueError:
        pass
    session.clear()
    print('登出!当前用户:', users)
    return redirect("/")
Esempio n. 7
0
def disconnect():
    pass
    try:
        del_user = User(session['user'], session["channel"])
        del_from = Channel(session["channel"], 0)
        try:
            channels[channels.index(del_from)].users.remove(session['user'])
        except ValueError:
            pass
        nickname_array = json.dumps(channels[session["channel"]].users)
        print(nickname_array)
        emit("current_client_list", {"users": nickname_array},
             room=session["channel"])
        print('掉线: ', session['user'])
    except KeyError:
        pass
Esempio n. 8
0
def channels_load():
    global _channels_list
    try:
        with open(settings.PERSISTENCE_PATH + 'channels.pickle', 'rb') as handle:
            _channels_list = pickle.load(handle)

            for channel_name, channel_data in _channels_list.items():
                globals.channel_list[channel_name] = Channel(channel_name, channel_data["motd"],
                                                             channel_data["moderators"], channel_data["banned"])

            print("[%s] Loaded persisted channels from file"
                  % datetime.now().strftime(settings.DATETIME_FORMAT))
    except IOError:
        _channels_list = {}
        print("[%s] Failed to load persisted channels from file"
              % datetime.now().strftime(settings.DATETIME_FORMAT))
Esempio n. 9
0
def test_state():
    chan = "#chan"

    # join
    state = State()
    user = User("oreqizer", None)
    state.join(user, chan)
    assert len(state.channels) == 1, f"state.join: state.channels: {len(state.channels)} == 1"
    ch = state.channels[chan]
    assert len(user.channels) == 1, f"state.join: user.channels: {len(user.channels)} == 1"
    assert len(ch.users) == 1, f"state.join: ch.users: {len(ch.users)} == 1"

    # part
    state = State()
    user = User("oreqizer", None)
    state.join(user, chan)
    ch = state.channels[chan]
    state.part(user, chan)
    assert len(user.channels) == 0, f"state.part: user.channels: {len(user.channels)} == 0"
    assert len(ch.users) == 0, f"state.part: ch.users: {len(ch.users)} == 0"

    # get_channel
    state = State()
    user = User("oreqizer", None)
    assert_throw(lambda: state.get_channel(chan))
    state.join(user, chan)
    ch = state.channels[chan]
    assert state.get_channel(
        chan) == ch, f"state.get_channel: {state.get_channel(chan).name} == {ch.name}"

    # get_user_channel
    state = State()
    user = User("oreqizer", None)
    assert_throw(lambda: state.get_user_channel(user, chan))
    state.users[user.nickname] = user
    assert_throw(lambda: state.get_user_channel(user, chan))
    ch = Channel(chan)
    state.channels[chan] = ch
    assert_throw(lambda: state.get_user_channel(user, chan))
    state.join(user, chan)
    assert state.get_user_channel(
        user, chan) == ch, f"state.get_user_channel: {state.get_user_channel(user, chan).name} == {ch.name}"

    print("test_state OK")
Esempio n. 10
0
def add_channel():
    # id = request.json['id']
    name = request.json['name']
    keyname = request.json['keyname']
    type = request.json['type']
    url = request.json['url']

    new_channel = Channel(name, keyname, type, url)
    thread_channel = new_channel
    db.session.add(new_channel)
    db.session.commit()
    threads = []
    if new_channel.id:
        t = threading.Thread(target=recorder, args=(thread_channel, False,))
        threads.append(t)
        pid = threading.current_thread().ident
        t.start()

    return channel_schema.jsonify(new_channel)
Esempio n. 11
0
def create_channel():
    if request.method == "GET":
        return render_template("create_channel.html")
    else:
        # 已经注册过
        if session.get("user"):
            # POST方法提交建立频道名称
            new_channel_name = request.form.get("channel_name")
            # index递增
            new_channel = Channel(index=len(channels), name=new_channel_name)
            # 如果当前频道列表中存在该频道,则返回原处,并提示
            if new_channel.name in [c.name for c in channels]:
                flash("该名称已被使用!")
                return redirect("/create_channel", "303")
            channels.append(new_channel)
            flash("频道创建成功!")
            return redirect("/channels")
        # 若尚未注册,返回、报错
        else:
            flash("尚未注册!")
            return redirect("/", "303")
Esempio n. 12
0
def newRestream(message):
    restreamChannel = message['restreamChannelID']
    channelQuery = Channel.Channel.query.filter_by(
        id=int(restreamChannel)).first()
    if channelQuery is not None:
        if channelQuery.owningUser == current_user.id:
            restreamName = message['name']
            restreamURL = message['restreamURL']
            newRestreamObject = Channel.restreamDestinations(
                channelQuery.id, restreamName, restreamURL)

            db.session.add(newRestreamObject)
            db.session.commit()

            restreamQuery = Channel.restreamDestinations.query.filter_by(
                name=restreamName,
                url=restreamURL,
                channel=int(restreamChannel),
                enabled=False).first()
            restreamID = restreamQuery.id

            emit('newRestreamAck', {
                'restreamName': restreamName,
                'restreamURL': restreamURL,
                'restreamID': str(restreamID),
                'channelID': str(restreamChannel)
            },
                 broadcast=False)
        else:
            db.session.commit()
            db.session.close()
            return abort(401)
    else:
        db.session.commit()
        db.session.close()
        return abort(500)
    db.session.commit()
    db.session.close()
    return 'OK'
Esempio n. 13
0
def test_user():
    user = User("oreqizer", None)
    ch = Channel("#chan")

    # join
    user.join(ch)
    assert len(user.channels) == 1, f"user.join: {len(user.channels)} == 1"

    assert_throw(lambda: user.join(ch))

    # part
    user.part(ch)
    assert len(user.channels) == 0, f"user.part: {len(user.channels)} == 0"

    assert_throw(lambda: user.part(ch))

    # joined
    assert not user.joined(ch), f"user.joined: False"
    user.join(ch)
    assert user.joined(ch), f"user.joined: True"

    print("test_user OK")
Esempio n. 14
0
def new_channel(ch_name):
    Channel.emit_channel(ch_name)
Esempio n. 15
0
def get_channels():
    return Channel.jsonify_channels()
Esempio n. 16
0
def test_channel():
    ch = Channel("#chan")
    user = User("oreqizer", None)

    # join
    ch.join(user)
    assert len(ch.users) == 1, f"ch.join: {len(ch.users)} == 1"

    assert_throw(lambda: ch.join(user))

    # part
    ch.part(user)
    assert len(ch.users) == 0, f"ch.part: {len(ch.users)} == 0"

    assert_throw(lambda: ch.part(user))

    # has
    assert not ch.has(ch), f"ch.joined: False"
    ch.join(user)
    assert ch.has(user), f"ch.joined: True"

    # send
    ch.send(ChannelMessage(user, "kek"))
    assert len(ch.messages) == 1, f"ch.send: {len(ch.messages)} == 1"
    ch.messages = []

    # replay
    now = 1337
    m1 = ChannelMessage(user, "lol")
    m1.timestamp = now - 1
    ch.send(m1)

    m2 = ChannelMessage(user, "kek")
    m2.timestamp = now + 1
    ch.send(m2)
    res = ch.replay(now)
    assert len(res) == 1, f"ch.replay: {len(res)} == 1"
    assert res[0].text == m2.text, f"ch.replay: {res[0].text} == {m2.text}"

    print("test_channel OK")
Esempio n. 17
0
# Check for environment variables
if not os.getenv("FLASK_APP"):
    raise RuntimeError("-- Environment variable FLASK_APP is not set")

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"

# app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")

socketio = SocketIO(app)
Session(app)

# create a 'general' channel so at least one channel exists
Channel("general", "chatterbox admin")

# ROUTES ###############################################


@app.route("/")
def index():
    return render_template("index.html")


# add new name
@app.route("/add_newname", methods=["POST"])
def add_newname():
    new_name = request.form.get("new_name")

    if (Display_names.exists(new_name)):
Esempio n. 18
0
import json
from classes import (Channel, Message, User)

app = Flask(__name__)
app.config["SECRET_KEY"] = "1234567890"
app.config["SESSION_TYPE"] = "filesystem"
SESSION_TYPE = 'filesystem'
socketio = SocketIO(app)
Session(app)

# 当前频道列表
channels = []
# 当前用户列表
users = []

channels.append(Channel(index=0, name="第一组"))
channels.append(Channel(index=1, name="第二组"))
channels.append(Channel(index=2, name="第三组"))
channels.append(Channel(index=3, name="第四组"))
channels.append(Channel(index=4, name="第五组"))
channels.append(Channel(index=5, name="第六组"))
channels.append(Channel(index=6, name="第七组"))
channels.append(Channel(index=7, name="第八组"))
channels.append(Channel(index=8, name="第九组"))
channels.append(Channel(index=9, name="第十组"))


@app.route("/", methods=["GET", "POST"])
def index():
    # 显示index页面
    if request.method == "GET":
Esempio n. 19
0
def index():
	history, video = request.cookies.get('history'), request.args.get('url')
	history, video = dbcontrol.recents(history, video)
	resp = make_response(render_template('home.html', vid = video, history = [Channel(i) for i in history.split(";")]))
	resp.set_cookie('history', history)
	return resp