Esempio n. 1
0
def index(request):
    # Validate token from Slack.
    token = request.GET['token']
    if (token != 'RNmcnBKCdOZBfs3S7habfT85'):
        return JsonResponse({'text': 'ERROR: Invalid token %s' % token})

    # Fetch channel if it exists, else create a new Channel object.
    channel_id = request.GET['channel_id']
    try:
        channel = Channel.objects.get(channel_id=channel_id)
    except Channel.DoesNotExist:
        channel = Channel(channel_id=channel_id)
        channel.save()

    # Parse command from user.
    command = request.GET['text']
    args = command.split(' ')
    if (len(args) < 1 or args[0] == 'help'):
        return showHelp()
    elif (args[0] == 'startGame'):
        return startGame(args, request.GET['user_name'], channel)
    elif (args[0] == 'makeMove'):
        return makeMove(args, request.GET['user_name'], channel)
    elif (args[0] == 'showBoard'):
        return showBoard(channel)
    else:
        return showHelp()
 def post(self, *args, **kwargs):
     db_connection = self.get_db_connection()
     already_joined = True
     channel_repo = ChannelRepository(db_connection)
     channel_name = self.get_argument('channel')
     channel = yield channel_repo.filter({'name': channel_name})
     if not channel:
         channel = Channel(name=channel_name)
         yield channel_repo.save(channel)
     channel_user_repo = ChannelUserRepository(db_connection)
     channel_user = yield channel_user_repo.filter({
         'user': self.current_user,
         'channel': channel
     })
     if not channel_user:
         already_joined = False
         channel_user = ChannelUser(channel=channel,
                                    user=self.current_user,
                                    admin=True)
         yield channel_user_repo.save(channel_user)
         message_text = '{} has subscribed to the channel'.format(
             self.current_user.name)
         message = Message(channel=channel, text=message_text)
         message_repo = MessageRepository(db_connection)
         yield message_repo.save(message)
         yield message_repo.publish_message(message)
     yield self.release_db_connection(db_connection)
     self.write_json_response({
         'status': True,
         'channel': {
             'name': channel.name,
             'id': channel.id,
             'already_joined': already_joined,
         }
     })
Esempio n. 3
0
def new_channel():
    """Create a new channel"""

    if request.method == 'POST':
        error = None

        # Get user input
        channel_name = request.form.get('channel_name')

        # Form validation
        if not channel_name:
            error = 'Enter channel name'
        elif channel_name in channels.keys():
            error = 'Channel already exists'

        # Create channel if no error
        if error is None:
            ch = Channel(channel_name)
            channels[f'{channel_name}'] = ch

            return redirect(url_for('index'))

        # Display error in form
        flash(error)

    return render_template('new_channel.html')
 def setupChannels(self):
     cfg = configparser.ConfigParser()
     cfg.read("config/channels.ini")
     for section in cfg.sections():
         validToken = False
         while not validToken:
             try:
                 channel = Channel.Channel(int(section), self._helix, self)
                 for option in cfg.options(section):
                     category = Category.Category(option, section)
                     emoteList = cfg[section][option].split(",")
                     for emote in emoteList:
                         category.addEmote(emote)
                     channel.addCategory(category)
                 self.addChannel(channel)
                 validToken = True
             except requests.exceptions.HTTPError as http_err:
                 statusCode = http_err.response.status_code
                 if statusCode == 401:
                     print(
                         "401 Unauthorized error, refreshing access token")
                     self.refreshToken()
                 else:
                     print("Other error received:", statusCode)
                     break
     self.hasChannels = True
Esempio n. 5
0
def channel(channel_name):
    new_channel_form = NewChannelForm()
    new_post_form = NewPostForm()
    if request.method == "POST":
        if new_channel_form.submit.data and new_channel_form.validate_on_submit(
        ):
            channel = Channel(name=new_channel_form.channel_name.data)
            db.session.add(channel)
            db.session.commit()
            new_channel_form.channel_name.data = ""
            return redirect(url_for("channel", channel_name=channel_name))
        elif new_post_form.submit.data and new_post_form.validate_on_submit():
            post = Post(body=new_post_form.post_body.data,
                        timestamp=datetime.utcnow(),
                        user_id=current_user.id,
                        channel_id=Channel.query.filter_by(
                            name=channel_name).first().id)
            db.session.add(post)
            db.session.commit()
            new_post_form.post_body.data = ""
            return redirect(url_for("channel", channel_name=channel_name))

    channels = Channel.query.all()
    if not any(channel_name == channel.name for channel in channels):
        return redirect(url_for("channels"))
    cur_channel = Channel.query.filter_by(name=channel_name).first()
    posts = cur_channel.posts
    return render_template("channel.html",
                           new_channel_form=new_channel_form,
                           new_post_form=new_post_form,
                           channels=channels,
                           posts=posts)
Esempio n. 6
0
def add_channel():
    if current_user.type != 'Brand/Agency':
        flash('You cannot add a channel because of your account type!')
        return redirect(url_for('marketplace'))
    form = CreateChannelForm()
    if form.validate_on_submit():
        if db.session.query(Channel).filter_by(link=form.link.data).first():
            flash('Such marketplace already exists!')
            return redirect(url_for('add_channel'))
        try:
            # some magic with api inside ChannelInfo object
            ci = ChannelInfo(form.link.data)
            form.name.data = ci.name
            new_channel = Channel(name=ci.name,
                                  link=ci.chat_id, description=form.description.data,
                                  subscribers=ci.subscribers,
                                  price=form.price.data, secret=getrandompassword(), category=form.category.data,
                                  image=ci.photo, admin_id=current_user.id)

            db.session.add(new_channel)
            db.session.commit()

            flash('Great! Now you can confirm ownership in account settings section!')

            return redirect(url_for('settings'))
        except NameError:
            flash('No such channel found or incorrect link given!')
            return redirect(url_for('add_channel'))

    return render_template('profile/add_channel.html', form=form)
Esempio n. 7
0
 def delete_scene(self, args, guild, channel, scenario, sc, user):
     messages = []
     search = ''
     if len(args) == 1:
         if not sc:
             raise Exception('No scene provided for deletion')
     else:
         search = ' '.join(args[1:])
         sc = Scene().find(guild.name, str(channel.id), str(scenario.id),
                           search)
     if not sc:
         return [f'{search} was not found. No changes made.']
     else:
         search = str(sc.name)
         scenario_id = str(sc.scenario_id) if sc.scenario_id else ''
         channel_id = str(sc.channel_id) if sc.channel_id else ''
         sc.character.archive(user)
         sc.archived = True
         sc.updated_by = str(user.id)
         sc.updated = T.now()
         sc.save()
         messages.append(f'***{search}*** removed')
         if scenario_id:
             secenario = Scenario().get_by_id(scenario_id)
             messages.append(secenario.get_string(channel))
         elif channel_id:
             channel = Channel().get_by_id(channel_id)
             messages.append(channel.get_string())
         return messages
Esempio n. 8
0
def create_channel():
    req = request.get_json()
    name = req['name']
    creator = current_user
    # Check if the creator has created a channel with that name before
    bad_name = str.strip(name.lower()) in [channel.name.lower() for channel in creator.channels]
    if bad_name:
        return jsonify(
            {
                'success': False,
                'error': 'Channel name already exisits for this user'
            }
        )

    new_channel = Channel(name=name, creator=creator)
    db.session.add(new_channel)
    db.session.commit()

    socketio.emit('new channel',
                  {
                      'name': name,
                      'creator': current_user.username
                  },
                  broadcast=True
                  )
    return jsonify(
        {
            'success': True,
        }
    )
Esempio n. 9
0
 def on_join(self, channel_name):
     if not channel_name.startswith('#'):
         emit('error', {'message': 'Channel name should start with a #'})
         return
     channel = Channel.get(channel_name)
     if current_user.is_authenticated:
         if channel is None:
             channel = Channel(channel_name)
             db.session.add(channel)
         if channel not in current_user.channels:
             current_user.channels.append(channel)
             join_room(channel_name)
         current_user.last_channel = channel
         db.session.commit()
         data = {
             'channel': {
                 'name': channel_name
             },
             'user': current_user.name
         }
     else:
         if channel is None:
             data = {'channel': None}
         else:
             join_room(channel_name)
             data = {'channel': {'name': channel_name}}
     emit('channel-joined', data, room=channel_name, include_self=True)
Esempio n. 10
0
def add_channel(update, context):
    temp = update.message.reply_text('لطفا صبر کنید...')
    try:
        channel_sent_list = update.effective_message.text.split('\n')
    except ValueError:
        update.message.reply_text('ورودی اشتباه')
        return ADD_CHANNELS

    channel_store_list = []
    for channel in Channel.get_all():
        channel_store_list.append(channel.username)
    for username in channel_sent_list:
        if username.__contains__('t.me') or username.__contains__(
                'telegram.me'):
            try:
                username = '******' + \
                    re.search(r'\/\w{5,}', username).group(0).replace('/', '')
            except Exception:
                continue
        if username not in channel_store_list:
            channel_name = get_channel_name(username)
            if channel_name:
                Channel(username=username, name=channel_name.get_text()).add()
            else:
                update.message.reply_text(
                    'کانال {} وجود ندارد'.format(username))
    update.message.bot.edit_message_text(
        chat_id=update.message.chat_id,
        message_id=temp.message_id,
        text='اکنون /done را برای ذخیره سازی کانال ها ارسال کنید')
    return ADD_CHANNELS
Esempio n. 11
0
def emap_process(emap_version, emap_path):
    emap = open(emap_path, 'r')
    for index, line in enumerate(emap):
        if line[0] == "#":
            continue
        if len(line.split()) < 10:
            continue
        contents = line.split()
        crate = int(contents[1])
        slot = int(contents[2])
        dcc = int(contents[4])
        spigot = int(contents[5])
        fiber = int(contents[6])
        fiber_channel = int(contents[7])
        subdet = str(contents[8])
        ieta = int(contents[9])
        iphi = int(contents[10])
        depth = int(contents[11])

        channel = Channel(subdet=subdet,
                          ieta=ieta,
                          iphi=iphi,
                          depth=depth,
                          crate=crate,
                          slot=slot,
                          dcc=dcc,
                          spigot=spigot,
                          fiber=fiber,
                          fiber_channel=fiber_channel,
                          emap_version=emap_version,
                          index=index)
        channel.save()
Esempio n. 12
0
 def _add_channel_to_database(self, channel, url):
     self.session = self.Session()
     self.session.add(
         Channel(
             channel_id=channel.id,
             channel_name=channel.title,
             channel_title=channel.title,
             channel_url=url,
             account_id=self.account.account_id,
             channel_is_mega_group=channel.megagroup,
             channel_is_group=True,
             channel_is_private=channel.restricted,
             channel_is_broadcast=channel.broadcast,
             channel_access_hash=channel.access_hash,
             channel_size=0,
             channel_is_enabled=True,
             channel_tcreate=datetime.now(),
         ))
     try:
         self.session.commit()
     except IntegrityError:
         self.session.rollback()
     except InterfaceError:
         pass
     self.session.close()
     self.channel_list.append(channel.id)
     self.channel_meta[channel.id] = {
         'channel_id': channel.id,
         'channel_title': channel.title,
         'channel_url': url,
         'channel_size': 0,
         'channel_texpire': datetime.now() + timedelta(hours=3)
     }
Esempio n. 13
0
def process_emap(version, path):
    print "Bad!"
    from models import Channel
    emap = open(path, 'r')
    for line in emap:
        if line[0] == "#":
            continue
        if len(line.split()) < 10:
            continue
        contents = line.split()
        crate = int(contents[1])
        slot = int(contents[2])
        dcc = int(contents[4])
        spigot = int(contents[5])
        fiber = int(contents[6])
        fiber_channel = int(contents[7])
        subdet = str(contents[8])
        ieta = int(contents[9])
        iphi = int(contents[10])
        depth = int(contents[11])

        channel = Channel(subdet=subdet,
                          ieta=ieta,
                          iphi=iphi,
                          depth=depth,
                          crate=crate,
                          slot=slot,
                          dcc=dcc,
                          spigot=spigot,
                          fiber=fiber,
                          fiber_channel=fiber_channel,
                          emap_version=version)
        db.session.add(channel)
        db.session.commit()
Esempio n. 14
0
def initChannel(userid):
    #Refreshes the channel api
    chan = Channel.get_by_key_name(userid)
    if not chan:
        chan = Channel(key_name = userid)
    chan.token = channel.create_channel(userid, duration_minutes=5)
    chan.put()
    return chan.token
Esempio n. 15
0
    def __init__(self):
        self.players = []
        self.history = []

        self.channel = Channel('game')

        self.turn = random.randint(0, 1)
        self.started = False
Esempio n. 16
0
 def open(self, channel):
     #logging.info("opened connection")
     self.board_name = 'board:' + channel
     publisher.subscribe(self.board_name, self.on_new_board_message)
     self.channel = Channel(self.board_name)
     # when client connects send all commands written
     for cmd in iter(self.channel.get_commands()):
         self.write_message(cmd)
Esempio n. 17
0
    def setUp(self):
        user = User.objects.create(username='******')
        user.save()

        channel = Channel(creator=user)
        channel.save()

        self.queue = QueueManager(channel=channel.id)
Esempio n. 18
0
def init_add_channels():
    global session, SERVER_MODE, engine

    # Lets get the first account
    account = session.query(Account).first()

    CHANNELS = [
        {
            'channel_name':
            'Informer monitoring',
            'channel_id':
            os.environ[
                'TELEGRAM_NOTIFICATIONS_CHANNEL_ID'],  # Enter your own Telegram channel ID for monitoring here
            'channel_url':
            os.environ['TELEGRAM_NOTIFICATIONS_CHANNEL_URL'],
            'channel_is_private':
            False if os.environ['TELEGRAM_NOTIFICATIONS_CHANNEL_IS_PRIVATE']
            == '0' else True
        },
    ]

    # Lets import the CSV with the channel list
    with open(os.environ['TELEGRAM_CHANNEL_MONITOR_LIST']) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count != 0:
                print(f'Adding channel {row[0]} => {row[1]}')
                CHANNELS.append({
                    'channel_name': row[0],
                    'channel_url': row[1]
                })
            line_count += 1

    logging.info(f'Inserting {line_count} channels to database')

    for channel in CHANNELS:
        logging.info(
            f"{sys._getframe().f_code.co_name}: Adding channel {channel['channel_name']} to database"
        )

        channel_url = channel[
            'channel_url'] if 'channel_url' in channel else None
        channel_id = channel['channel_id'] if 'channel_id' in channel else None
        channel_is_group = channel[
            'channel_is_group'] if 'channel_is_group' in channel else False
        channel_is_private = channel[
            'channel_is_private'] if 'channel_is_private' in channel else False

        session.add(
            Channel(channel_name=channel['channel_name'],
                    channel_url=channel_url,
                    channel_id=channel_id,
                    account_id=account.account_id,
                    channel_tcreate=datetime.now(),
                    channel_is_group=channel_is_group,
                    channel_is_private=channel_is_private))
    session.commit()
Esempio n. 19
0
def save_measure_in_db(session, data, point):
    objects = []
    value = data.pop(0)

    my_ssid = Ssid(value[0])
    my_bssid = Bssid(value[1])
    my_measure = Measure(value[2])
    my_channel = Channel(value[3])
    my_security = Security(value[4])
    my_point = Point(point)

    entry = session.query(Ssid).filter(Ssid.ssid_value.like(value[0])).first()
    if entry is None:
        my_ssid.measure.append(my_measure)
        objects.append(my_ssid)
    else:
        entry.measure.append(my_measure)

    entry = session.query(Bssid).filter(Bssid.bssid_value.like(
        value[1])).first()
    if entry is None:
        my_bssid.measure.append(my_measure)
        objects.append(my_bssid)
    else:
        entry.measure.append(my_measure)

    entry = session.query(Channel).filter(Channel.channel_number.like(
        value[3])).first()
    if entry is None:
        my_channel.measure.append(my_measure)
        objects.append(my_channel)
    else:
        entry.measure.append(my_measure)

    entry = session.query(Security).filter(
        Security.security_type.like(value[4])).first()
    if entry is None:
        my_security.measure.append(my_measure)
        objects.append(my_security)
    else:
        entry.measure.append(my_measure)

    entry = session.query(Point).filter(Point.x_location == point.x).filter(
        Point.y_location == point.y).first()
    if entry is None:
        my_point.measure.append(my_measure)
        objects.append(my_point)
    else:
        entry.measure.append(my_measure)

    objects.append(my_measure)

    session.add_all(objects)
    session.commit()
    if len(data) != 0:
        save_measure_in_db(session, data, point)
    else:
        return
Esempio n. 20
0
def add():
    if request.method == 'POST':
        c = Channel()
        c.title = request.form.get('title', '').strip()
        c.link = request.form.get('link', '').strip()
        c.type = request.form.get('type', 'in')
        c.put()
        return redirect('/admin/channel', code=303)
    return render_template('admin/channel/add.html')
Esempio n. 21
0
def download_video_detail(video):
    """
    """
    from youtube import get_video_detail
    detail = get_video_detail(video.video_id)
    global ThreadSession
    session = ThreadSession()
    # 获取video对象
    from models import Video, VideoTag, Channel
    # 填入数据
    snippet = detail["snippet"]
    contentDetails = detail["contentDetails"]
    statistics = detail["statistics"]
    status = detail["status"]
    # status
    video.license = status["license"]
    # video.embedable = status["embedable"] key_error
    # iframe播放器URL
    video.player_url = detail["player"]["embedHtml"]
    # 统计 statistics
    video.view_count = int(statistics["viewCount"])
    video.like_count = int(statistics["likeCount"])
    video.dislike_count = int(statistics["dislikeCount"])
    video.favorite_count = int(statistics["favoriteCount"])
    video.comment_count = int(statistics["commentCount"])
    # 内容细节 contentDetails
    video.duration = contentDetails["duration"]
    video.dimension = contentDetails["dimension"]
    video.definition = contentDetails["definition"]
    # todo 会自动转换false吗?
    video.has_caption = contentDetails["caption"]
    video.is_licensed_content = contentDetails["licensedContent"]
    video.projection = contentDetails["projection"]
    # snippet
    video.title = snippet["title"]
    video.description = snippet["description"]
    video.published_at = snippet["publishedAt"]
    # todo 会自动转换成json吗?
    # video.thumbails = snippet["thumbails"] KeyError
    video.category_id = int(snippet["categoryId"])

    session.commit()
    # 处理tag
    tags = snippet["tags"]
    for tag in tags:
        _tag = VideoTag(name=tag)
        session.add(_tag)
        session.commit()
        video.tags.append(_tag)
    # 处理channel
    channel = Channel(channel_title=snippet["channelTitle"], 
                    channel_id=snippet["channelId"])
    session.add(channel)
    session.commit()
    ThreadSession.remove()
    return None
Esempio n. 22
0
    def update_subscriptions(self):
        log.info('running update subscriptions')
        head = {'referer': 'http://' + 'www.hominem.se'}
        payload = {
            'key': settings.APIKEY,
            'part': 'snippet',
            'channelId': 'UCvVx_jTHBKt0HW-iEkZnXTg',
            'maxResults': '50'
        }
        nextpage = None
        more = True
        while more:
            try:
                r = requests.get(
                    'https://www.googleapis.com/youtube/v3/subscriptions',
                    headers=head,
                    params=payload)
            except requests.RequestException as e:
                log.error("Exception in requests.get when searching: " +
                          str(e))
                return

            subscriptions = json.loads(r.text)
            if 'nextPageToken' in subscriptions:
                nextpage = subscriptions['nextPageToken']
                payload['pageToken'] = nextpage
                more = True
            else:
                nextpage = None
                more = False

            existing_subs = Channel.objects.all()
            log.info('Got ' + str(len(subscriptions['items'])) +
                     ' subscriptions')
            for sub in subscriptions['items']:
                s = sub['snippet']
                title = s['title']
                channelId = s['resourceId']['channelId']
                publishedAt = timezone.datetime.strptime(
                    s['publishedAt'], '%Y-%m-%dT%H:%M:%S.%fZ')
                pub = timezone.make_aware(publishedAt, timezone=None)
                description = s['description']
                thumb = s['thumbnails']['default']['url']

                channels = Channel.objects.filter(title_text=title)
                if len(channels) == 0:
                    q = Channel(channel_id=channelId,
                                title_text=title,
                                description_text=description,
                                thumbnail=thumb,
                                pub_date=pub,
                                latest_video=pub)
                    q.save()
                    log.info("Added new channel: " + title)
                else:
                    log.info("Channel " + title + "already exists")
Esempio n. 23
0
def create_channel(name, description, visibility):
    channel = Channel(name=name,
                      description=description,
                      visibility=visibility)
    creator = User.query.first()
    memberOf = MemberOf(is_owner=True, user=creator, channel=channel)
    db.session.add(channel)
    db.session.add(memberOf)
    db.session.commit()
    return "Added a channel"
Esempio n. 24
0
def requestjoin(user, args, socket):
    if not args and len(args) > 0:
        return

    channame = args

    # Check if channel name is valid
    if not re.match("^[A-Za-z0-9.-]*$", channame):
        user_controller.user_sendSocketMessage(
            socket, "notice", "channel,requestjoin",
            "Channel name can only contain alphabets, numbers, dash or period."
        )
        return

    if channame.lower() not in channels:
        chan = Channel.Channel(channame, "Topic not set.", True, False, None,
                               None)
        db.createChannel(chan)
        channels[channame.lower()] = chan
    else:
        chan = channels[channame.lower()]

    if user.ivleid in chan.joined:
        user_controller.user_sendSocketMessage(
            socket, "notice", "channel,requestjoin",
            "You are already in " + chan.name + ".")
        return

    # Check user access
    access = chan.accesscontrollist.get(user.ivleid)
    if access == 0 and not chan.public or access < 0:
        user_controller.user_sendSocketMessage(
            socket, "notice", "channel,requestjoin",
            "You do not have access to " + chan.name + ".")
        return

    # Notify and update
    user.joined[chan.name.lower()] = chan

    for u in chan.joined:
        if u != user.ivleid:
            user_controller.user_send(
                chan.joined[u], "channel", "join",
                chan.name + "," + json.dumps(user.infoToObject()))

    if user.ivleid not in chan.joined:
        chan.joined[user.ivleid] = user

    user_controller.user_send(user, "channel", "joinedchannel",
                              json.dumps(chan.infoToObject()))
    user_controller.user_send(
        user, "channel", "canvasdata",
        chan.name + "," + json.dumps(chan.canvas.toObject()))
    return
Esempio n. 25
0
def addchannel():
    data = json.loads(request.data.decode())
    title = data["title"]
    errors = {}
    try:
        channel = Channel(title)
        db.session.add(channel)
        db.session.commit()
        return jsonify({"succes": True})
    except:
        errors.append("Unable to add channel to database.")
        return jsonify({"error": errors})
Esempio n. 26
0
 def insert(self, chan):
     c = Channel()
     c.name = chan['Name']
     c.stream = chan['Stream']
     c.url = chan['Url']
     c.logo = chan['Logo']
     c.feed = chan['Feed']
     self.db.session.add(c)
     try:
         self.db.session.commit()
     except IntegrityError as e:
         self.db.session.rollback()
Esempio n. 27
0
def add_channel():
    form = ChannelForm(request.form)
    if request.method == 'POST' and form.validate():
        channel = Channel(name = form.name.data)
        channel.owner_id = g.user.id
        db.session.add(channel)
        db.session.commit()
        return redirect(url_for('channel_view', id=channel.id))
    return render_template('add_channel.html',
        title = 'Add channel',
        user = g.user,
        form = form)
Esempio n. 28
0
def init_add_channels():
    global session, SERVER_MODE, engine

    # Lets get the first account
    account = session.query(Account).first()

    CHANNELS = [
        {
            'channel_name': 'Informer monitoring',
            'channel_id':
            1234567,  # Enter your own Telegram channel ID for monitoring here
            'channel_url': 'https://t.me/joinchat/Blahblahblah',
            'channel_is_private': True
        },
    ]

    # Lets import the CSV with the channel list
    with open('channels.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count != 0:
                print(f'Adding channel {row[0]} => {row[1]}')
                CHANNELS.append({
                    'channel_name': row[0],
                    'channel_url': row[1]
                })
            line_count += 1

        logging.info('Inserted {} channels to database'.format(line_count))

    for channel in CHANNELS:
        logging.info('{}: Adding channel {} to database'.format(
            sys._getframe().f_code.co_name, channel['channel_name']))

        channel_url = channel[
            'channel_url'] if 'channel_url' in channel else None
        channel_id = channel['channel_id'] if 'channel_id' in channel else None
        channel_is_group = channel[
            'channel_is_group'] if 'channel_is_group' in channel else False
        channel_is_private = channel[
            'channel_is_private'] if 'channel_is_private' in channel else False

        session.add(
            Channel(channel_name=channel['channel_name'],
                    channel_url=channel_url,
                    channel_id=channel_id,
                    account_id=account.account_id,
                    channel_tcreate=datetime.now(),
                    channel_is_group=channel_is_group,
                    channel_is_private=channel_is_private))
    session.commit()
Esempio n. 29
0
def create(source, generator=sws.Diver()):
    ''' create sourcefile instance for monfile '''
    headerdict = generator.get_header(source)
    mon = MonFile()
    header = headerdict['HEADER']
    mon.company = header.get('COMPANY', None)
    mon.compstat = header.get('COMP.STATUS', None)
    if 'DATE' in header and 'TIME' in header:
        dt = header.get('DATE') + ' ' + header.get('TIME')
        mon.date = datetime.datetime.strptime(dt, '%d/%m/%Y %H:%M:%S')
    else:
        mon.date = datetime.datetime.now()
    mon.monfilename = header.get('FILENAME', None)
    mon.createdby = header.get('CREATED BY', None)
    mon.num_points = int(header.get('Number of points', '0'))

    s = headerdict['Logger settings']
    mon.instrument_type = s.get('Instrument type', None)
    mon.status = s.get('Status', None)
    serial = s.get('Serial number', None)
    if serial is not None:
        serial = re.split(r'[-\s+]', serial)[1]
    mon.serial_number = serial
    mon.instrument_number = s.get('Instrument number', None)
    mon.location = s.get('Location', None)
    mon.sample_period = s.get('Sample period', None)
    mon.sample_method = s.get('Sample method', 'T')
    mon.num_channels = int(s.get('Number of channels', '1'))

    s = headerdict['Series settings']
    mon.start_date = datetime.datetime.strptime(s['Start date / time'],
                                                '%H:%M:%S %d/%m/%y')
    mon.end_date = datetime.datetime.strptime(s['End date / time'],
                                              '%H:%M:%S %d/%m/%y')

    channels = []
    for i in range(mon.num_channels):
        channel = Channel(number=i + 1)
        name = 'Channel %d' % (i + 1)
        s = headerdict[name]
        channel.identification = s.get('Identification', name)
        t = s.get('Reference level', '0 -')
        channel.reference_level, channel.reference_unit = re.split(r'\s+', t)
        channel.range, channel.range_unit = re.split(r'\s+',
                                                     s.get('Range', '0 -'))

        # omit degree symbol
        channel.reference_unit = ''
        channel.range_unit = ''

        channels.append(channel)
    return (mon, channels)
Esempio n. 30
0
    def post(self, hash):
        hash = hash.lower()
        target = Account.all().filter('hash =', hash).get()
        if not target:
            target = Account.all().filter('hashes =', hash).get()
        source = Account.all().filter('api_key =',
                                      self.request.get('api_key')).get()

        channel = Channel.all().filter('target =',
                                       target).filter('source =',
                                                      source).get()
        approval_notice = None
        if not channel and source and target:
            channel = Channel(target=target,
                              source=source,
                              outlet=target.get_default_outlet())
            channel.put()
            approval_notice = channel.get_approval_notice()
            channel.send_activation_email()

        if channel:
            notice = Notification(channel=channel,
                                  text=strip_tags(self.request.get('text')),
                                  icon=source.source_icon)
            for arg in ['title', 'link', 'icon', 'sticky', 'tags']:
                value = strip_tags(self.request.get(arg, None))
                if value:
                    setattr(notice, arg, value)
            notice.put()

            # Increment the counter on the channel to represent number of notices sent
            channel.count += 1
            channel.put()

            if channel.status == 'enabled':
                notice.dispatch()
                self.response.out.write("OK\n")

            elif channel.status == 'pending':
                self.response.set_status(202)
                if approval_notice:
                    approval_notice.dispatch()
                    self.response.out.write("OK\n")
                else:
                    self.response.out.write("202 Pending approval")
            elif channel.status == 'disabled':
                self.response.set_status(202)
                self.response.out.write("202 Accepted but disabled")
        else:
            self.error(404)
            self.response.out.write("404 Target or source not found")