Beispiel #1
0
    def run(self):
        port = None
        if self.use_unix_socket:
            socket_family = socket.AF_UNIX

            if self.lirc_file is not None:
                port = self.lirc_file
        else:
            socket_family = socket.AF_INET
            port = (socket.gethostname(), app.lirc_port)

        s = socket.socket(socket_family, socket.SOCK_STREAM)

        log("[LircServer] Using port " + str(port))

        if self.use_unix_socket:
            if os.access(port, os.F_OK):
                try:
                    os.remove(port)
                except OSError:
                    self.mainapp.die("[LircServer] Can't delete file: " +
                                     app.lirc_file)
                    return

        logger.info("[LircServer] LIRC Server Listening on " + str(port))

        try:
            s.bind(port)
            if self.use_unix_socket:
                os.chmod(port, 0666)
        except Exception, e:
            self.mainapp.die("[LircServer] Can't bind socket: " + str(e[1]))
            return
Beispiel #2
0
  def run(self):
    port = None
    if self.use_unix_socket:
        socket_family = socket.AF_UNIX
        
        if self.lirc_file is not None:
            port = self.lirc_file
    else:
        socket_family = socket.AF_INET
        port = (socket.gethostname(), app.lirc_port)

    s = socket.socket(socket_family, socket.SOCK_STREAM)
    
    log("[LircServer] Using port " + str(port))

    if self.use_unix_socket:
        if os.access(port, os.F_OK):
            try:
              os.remove(port)
            except OSError:
              self.mainapp.die("[LircServer] Can't delete file: " + app.lirc_file)
              return

    logger.info("[LircServer] LIRC Server Listening on " + str(port))

    try:
        s.bind(port)
        if self.use_unix_socket:
            os.chmod(port, 0666)
    except Exception, e:
        self.mainapp.die("[LircServer] Can't bind socket: " + str(e[1]))
        return
def default(workout_id):
    api = shodan.Shodan(SHODAN_API_KEY)
    page_template = 'index.jinja'

    workout = ds_client.get(ds_client.key('cybergym-workout', workout_id))

    if workout:
        if workout['type'] == 'shodan':
            if request.method == 'POST':
                logger.info(f'POST to /{workout_id}')
                try:
                    query = request.form.get('shodan_query')
                    page_num = request.form.get('page_number')
                    result = api.search(query, limit=10)
                    result_count = api.count(query)
                    print(result.keys())

                    return render_template(
                        page_template,
                        shodanResults=result,
                        resultCount=result_count,
                        query=query,
                        page_num=page_num,
                        workoutid=workout_id,
                    )
                except shodan.APIError as e:
                    logger.info(e)
                    e_template = 'invalid_query.jinja'
                    return render_template(e_template)
            return render_template(page_template)
        else:
            return redirect(f'/invalid/{workout_id}')
    else:
        return redirect(f'/invalid/{workout_id}')
Beispiel #4
0
 def decorated(self, *args, **kwargs):
     if config().config.testing_mode:
         GlobalLogger.info(
             'Skipping function "{}" - running in testing mode.'.format(
                 func.__name__))
         return
     return func(self, *args, **kwargs)
Beispiel #5
0
class BluetoothServer (threading.Thread, utils.NonBlockingThread):
  port = None
  queue = None
  mainapp = None
  
  def __init__(self, mainapp, queue):
    self.mainapp = mainapp
    self.queue = queue
    threading.Thread.__init__ (self)
    
  def run(self):
    log("[BluetoothServer] Initializing Bluetooth Server")
    
    stype = bluetooth.RFCOMM
    port = bluetooth.PORT_ANY
    
    server_sock = bluetooth.BluetoothSocket(stype)
    server_sock.bind(("", port))
    server_sock.listen(5)
    
    try:
        bluetooth.advertise_service(server_sock, "Bluemote Service", globals.UUID)
    except bluetooth.BluetoothError, be:
        self.mainapp.die("[BluemoteServer] Can't advertise service. Are the drivers running? Is there a bluetooth device?: " + str(be))
        return

    server_sock.settimeout(2)
    
    while True: # main accept() loop
      if not self.active:
          break

      logger.info("[BluetoothServer] Waiting for bluetooth connections...")

      client_sock = None
      while client_sock == None:
        if not self.active:
          break
                
        try:
          client_sock, address = server_sock.accept()
        except:
          pass
        
      if client_sock == None:
        continue

      logger.info("[BluetoothServer] Accepted connection from " + str(address))
        
      t = BluetoothClientHandle(client_sock, self)
      t.start()

    server_sock.close()
    
    log("[BluetoothServer] Bye bye.")
    
    return True
Beispiel #6
0
def test():
    logger.info('Testing mode')
    from sys import argv
    argv = argv[1:]
    args = {'all': False,
            'color': False,
            'num_answers': 1,
            'pos': 1,
            'query': argv}
    result = howdoi_call(args)
    print(' ')
    print(result)
Beispiel #7
0
    def is_due(self):
        """See :meth:`~celery.schedule.schedule.is_due`."""
        due = self.schedule.is_due(self.last_run_at)

        logger.debug('task {0} due : {1}'.format(self.name, due))
        if not self.enabled:
            logger.info('task {0} is disabled. not triggered.'.format(
                self.name))
            # if the task is disabled, we always return false, but the time that
            # it is next due is returned as usual
            return celery.schedules.schedstate(is_due=False, next=due[1])

        return due
Beispiel #8
0
def loader(workout_id):
    key = ds_client.key('cybergym-workout', workout_id)
    workout = ds_client.get(key)

    if workout:
        if workout['type'] == 'shodan':
            data = populate_datastore(workout_id=workout_id)
            logger.info(data)
            return redirect(f'/shodan_lite/{workout_id}')
        else:
            return redirect(f'/shodan_lite/invalid/{workout_id}')
    else:
        return redirect(f'/shodan_lite/invalid/{workout_id}')
Beispiel #9
0
def main():

    # Get the dispatcher to register handlers
    bot = telepot.DelegatorBot(token, [
        (per_inline_from_id(), create_open(HowDoIBot, timeout=30)),
        (per_chat_id(), create_open(HowDoIBot, timeout=10)),
    ])
    logger.info('Starting bot')
    # bot.message_loop({'inline_query': on_inline_query,
    #                   'chosen_inline_result': on_chosen_inline_result,
    #                   'chat': on_chat_message},
    #                  run_forever='Listening ...')
    bot.message_loop(run_forever='Listening ...')
Beispiel #10
0
    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type != 'text':
            logger.info('{} message received'.format(content_type))
            return

        command = msg['text'].strip().lower()

        if ('/start' in command):
            self.start(msg)
        elif ('/howdoi' in command):
            self.howdoi(msg)
        else:
            logger.critical(msg)
Beispiel #11
0
class BluetoothClientHandle(threading.Thread, utils.NonBlockingThread):
  def __init__(self, socket, srv):
    self.socket = socket
    self.srv = srv
    self.queue = srv.queue
    threading.Thread.__init__ (self)
    
  def run (self):
    
    log("[BluetoothClientHandle] Taking connection")
    while True:
        
      if not self.srv.active:
        break
      
      log("[BluetoothClientHandle] waiting data...")
        
      try:
        buff = self.socket.recv(globals.MAX_MSG_SIZE)
        if not buff: break
      except bluetooth.BluetoothError, e:
        print "Error receiving: %s (%s)" % (e, self.socket)
        break

      log("[BluetoothClientHandle] got: " + buff)
      self.queue.addCommand(buff);
    
    logger.info("[BluetoothClientHandle] Connection finished")
      
    self.socket.close()
def data(workout_id):
    page_template = 'raw_data.jinja'
    workout = ds_client.get(ds_client.key('cybergym-workout', workout_id))

    if workout:
        if workout['type'] == 'shodan':
            if request.method == "POST":
                logger.info(f"POSTING to /data/{workout_id}")
                return render_template(page_template, rawData=request.form.get('data'), workoutid=workout_id,)
            if request.method == "GET":
                logger.info(f'GET /data/{workout_id}')
                print(type(request.get_data()))
        else:
            return redirect(f'/invalid/{workout_id}')
    else:
        return redirect(f'/invalid/{workout_id}')
Beispiel #13
0
    def on_inline_query(self, msg):
        query_id, from_id, query_string = telepot.glance(
            msg, flavor='inline_query')
        logger.info('Inline ping from {}'.format(from_id))

        def compute_answer():
            link_results = _get_links(msg['query'])
            results = [w.split('/')[-1].replace('-', ' ')
                       for w in link_results]
            articles = [{'type': 'article',
                         'id': str(hex(getrandbits(64))[2:]),
                         'title': title,
                         'message_text': text}
                        for title, text in zip(results, link_results)]
            return articles

        self.answerer.answer(msg, compute_answer)
Beispiel #14
0
 def howdoi(self, msg):
     content_type, chat_type, chat_id = telepot.glance(msg)
     msg['text'] = ' '.join(msg['text'].split()[1:])
     logger.info("How do I received! [{}]".format(msg['text']))
     self.bot.sendChatAction(chat_id, 'typing')
     args = {'all': True,
             'color': False,
             'num_answers': 1,
             'pos': 1,
             'query': msg['text']}
     try:
         result = howdoi_call(args)
         # result = self.escape_markdown(result)
     except ReadTimeoutError:
         result = 'Timeout finding some answer, sorry :('
     except Exception as e:
         logger.critical(e)
     # self.sender.sendMessage(result, chat_id=chat_id)
     self.bot.sendMessage(chat_id, result)
Beispiel #15
0
 def sync(self):
     if not self.save_entry_back:
         logger.info('Without save entry back to redis...')
         return
     logger.info('Writing modified entries...')
     _tried = set()
     try:
         while self._dirty:
             name = self._dirty.pop()
             _tried.add(name)
             # Saving the entry back into Redis DB.
             try:
                 self.rdb.set(name, self.schedule[name].jsondump())
             except KeyError:
                 logger.warning("rdb key %s may be already removed." % name)
     except Exception as exc:
         # retry later
         self._dirty |= _tried
         logger.error('Error while sync: %r', exc, exc_info=1)
Beispiel #16
0
    def __init__(self, *args, **kwargs):
        if hasattr(current_app.conf, 'CELERY_REDIS_SCHEDULER_URL'):
            logger.info('backend scheduler using %s',
                        current_app.conf.CELERY_REDIS_SCHEDULER_URL)
        else:
            logger.info('backend scheduler using %s',
                        current_app.conf.CELERY_REDIS_SCHEDULER_URL)

        self.update_interval = current_app.conf.get(
            'UPDATE_INTERVAL') or timedelta(seconds=10)

        # how long we should hold on to the redis lock in seconds
        if 'CELERY_REDIS_SCHEDULER_LOCK_TTL' in current_app.conf:
            lock_ttl = current_app.conf.CELERY_REDIS_SCHEDULER_LOCK_TTL
        else:
            lock_ttl = 30

        if lock_ttl < self.update_interval.seconds:
            lock_ttl = self.update_interval.seconds * 2
        self.lock_ttl = lock_ttl

        # sync schedule to db when beat closed
        self.save_entry_back = current_app.conf.get("REDIS_SAVE_ENTRY_BACK",
                                                    "True")

        # keeping modified entries by name for sync later on
        self._dirty = set()
        self._schedule = {}  # keeping dynamic schedule from redis DB here
        # self.data is used for statically configured schedule
        self.schedule_url = current_app.conf.CELERY_REDIS_SCHEDULER_URL
        self.rdb = StrictRedis.from_url(self.schedule_url)
        self._last_updated = None
        self._lock_acquired = False
        self._lock = self.rdb.lock('celery:beat:task_lock',
                                   timeout=self.lock_ttl)
        self._lock_acquired = self._lock.acquire(blocking=False)
        self.Entry.scheduler = self
        self.old_task_dict = {}
        self.heap_to_none = False

        # This will launch setup_schedule if not lazy
        super(RedisScheduler, self).__init__(*args, **kwargs)
Beispiel #17
0
    def init(self):
        self.initlog()
        logger.info("[MainAppServer] Welcome to btlirc Server 0.1")

        lircServer = LircServer(self)
        queue = CommandQueue(self, lircServer)
        queue.start()
        lircServer.start()

        # start bluetooth server
        btServer = BluetoothServer(self, queue)
        btServer.start()

        signal.signal(signal.SIGTERM, lambda *args: self.exit())

        while True:
            if self._exit:
                break

            try:
                sleep(10)
            except KeyboardInterrupt:
                print "[MainAppServer] ** Got KeyboardInterrupt **"
                break

        log("[MainAppServer] Shutting down btlirc server.")

        #lircServer.join()
        self.killthread(btServer, "Bluetooth Server")
        self.killthread(queue, "Command Queue")
        self.killthread(lircServer, "LIRC Server")

        if self._errors:
            logger.info("[MainAppServer] ** Exit with error: " + self._errmsg)

        logger.info("[MainAppServer] Bye bye.")
Beispiel #18
0
  def init(self):
    self.initlog();
    logger.info("[MainAppServer] Welcome to btlirc Server 0.1")

    lircServer = LircServer(self);
    queue = CommandQueue(self, lircServer)
    queue.start()
    lircServer.start()

    # start bluetooth server
    btServer = BluetoothServer(self, queue)
    btServer.start() 
    
    signal.signal(signal.SIGTERM, lambda *args: self.exit())

    while True:
        if self._exit: 
            break
        
        try:
            sleep(10)
        except KeyboardInterrupt:
            print "[MainAppServer] ** Got KeyboardInterrupt **"
            break
    
    log("[MainAppServer] Shutting down btlirc server.")
      
    #lircServer.join()
    self.killthread(btServer, "Bluetooth Server")
    self.killthread(queue, "Command Queue")
    self.killthread(lircServer, "LIRC Server")
   
    if self._errors:
      logger.info("[MainAppServer] ** Exit with error: " + self._errmsg)
      
    logger.info("[MainAppServer] Bye bye.")
Beispiel #19
0
class LircServer(threading.Thread, utils.NonBlockingThread):
    use_unix_socket = False
    clients = []
    lirc_file = None

    def __init__(self, mainapp):
        self.lirc_file = app.lirc_file
        self.mainapp = mainapp
        self.clients = []

        if platform.system() == 'Linux':
            self.use_unix_socket = True

        threading.Thread.__init__(self)

    def run(self):
        port = None
        if self.use_unix_socket:
            socket_family = socket.AF_UNIX

            if self.lirc_file is not None:
                port = self.lirc_file
        else:
            socket_family = socket.AF_INET
            port = (socket.gethostname(), app.lirc_port)

        s = socket.socket(socket_family, socket.SOCK_STREAM)

        log("[LircServer] Using port " + str(port))

        if self.use_unix_socket:
            if os.access(port, os.F_OK):
                try:
                    os.remove(port)
                except OSError:
                    self.mainapp.die("[LircServer] Can't delete file: " +
                                     app.lirc_file)
                    return

        logger.info("[LircServer] LIRC Server Listening on " + str(port))

        try:
            s.bind(port)
            if self.use_unix_socket:
                os.chmod(port, 0666)
        except Exception, e:
            self.mainapp.die("[LircServer] Can't bind socket: " + str(e[1]))
            return

        s.listen(15)
        s.settimeout(2)

        while True:
            if not self.active:
                break

            log("[LircServer] Waiting for connections...")

            conn = None
            while conn == None:
                if not self.active:
                    break

                try:
                    conn, addr = s.accept()
                except socket.timeout, err:
                    pass

            if conn == None:
                continue

            logger.info("[LircServer] Connection received..." + str(addr) +
                        " - " + str(conn))

            self.handleClient(conn)
Beispiel #20
0
 def __init__(self):
     self.database_connection = MySQLdb.connect(address, username, password,
                                                db_name)
     self.cursor = self.database_connection.cursor()
     logger.info("Database initialized")