Пример #1
0
def get_command(scheme, hand):
	mimes = {tuple(mime.split("/")) for mime in hand.mimes}
	icons = get_icons(hand.mimes)
	mimeClasses = {type for type,sub in mimes}
	parent = open(f"/proc/{os.getppid()}/cmdline", "rb").read().split(b"\0")[0].decode()
	def test_cond(c):
		type, args = c
		assert type.startswith("cond_")
		type = type[5:]
		return {
			"or": lambda *cs: any(test_cond(c) for c in cs),
			"and": lambda *cs: all(test_cond(c) for c in cs),
			"mime": lambda t, s: (t,s) in mimes,
			"mime2": lambda t: t in mimeClasses,
			"icon": lambda i: i in icons,
			"scheme": lambda s: s == scheme,
			"host": lambda h: h in hand.hosts,
			"parent": lambda n: n == parent,
			"else": lambda: True
		}[type](*args)

	output = f"{hand.url}\n"\
		f"{', '.join(f'{maj}/{min}' for maj, min in mimes)}\n"\
		f"{', '.join(f'@{ic}' for ic in icons)}"

	for cond, cmd in config.config:
		if test_cond(cond):
			util.notify(f"Opening {cmd}", output)
			return cmd
	util.notify(f"Couldn't open :(", output)
Пример #2
0
def __main__():
	argp = argparse.ArgumentParser()
	argp.add_argument("-n", "--dry-run", action="store_true", help="Don't open the file, only figure out how")
	argp.add_argument("-s", "--sync",    action="store_true", help="Don't fork, so you can wait for the process to close") # TODO make detection also async
	argp.add_argument("file")
	args = argp.parse_args()

	try:
		scheme = urllib.parse.urlparse(args.file).scheme
		print(f"[Frozen Tuna] Opening {args.file}", file=sys.stderr)
		h = handler.registry[scheme](args.file)
		print(f"[Frozen Tuna]   Possible mime types: {h.mimes}", file=sys.stderr)
		cmd = get_command(scheme, h)
		print(f"[Frozen Tuna]   {cmd}", file=sys.stderr)
		cmd = list(transform_cmd(cmd, h, os.environ))
		print(f"[Frozen Tuna]   ({cmd})", file=sys.stderr)

	except Exception:
		import traceback
		util.notify("Error", traceback.format_exc())
		raise

	if cmd:
		if not args.dry_run:
			if args.sync:
				os.execlp(*cmd)
			else:
				subprocess.Popen(cmd)
	else:
		util.notify(f"Don't know how to handle {h.url}")
Пример #3
0
	def __init__(self, url):
		super().__init__(url)
		import requests
		import util
		util.notify(f"Getting HTTP...", url)
		self.response = requests.get(url, stream=True)
		self.response.raw.decode_content = True
Пример #4
0
def fetch(city_name, local, remote):
    util.notify('Fetching...', 'green', START_TIME)
    # Check if there already is some data in the local database
    if local.find().count() != 0:
        # Get the most recent date in the local database
        max_date = local.find_one(sort=[('_id', -1)])['_id']
        # Delete the latest document to avoid incomplete data
        local.delete_one({'_id': max_date})
        util.notify(
            'Will only import data for {0} after {1} (included)'.format(
                city_name, max_date), 'yellow', START_TIME)
        # Query the relevant data on the remove server
        cursor = remote.find({'_id': {'$gte': max_date}}, sort=[('_id', 1)])
    else:
        util.notify(
            'Importing all data for {} (this could take a while)'.format(
                city_name), 'yellow', START_TIME)
        # Query the relevant data on the remove server
        cursor = remote.find(sort=[('_id', 1)])

    total = cursor.count()
    util.notify('Found {0} document(s)'.format(total), 'cyan', START_TIME)
    # Insert it locally
    for i, cur in tqdm(enumerate(cursor)):
        local.insert(cur)
    util.notify('Done', 'green')
Пример #5
0
def announce(update, context):
    uid = update.effective_message.chat.id
    with open('.adminid', 'r') as f:
        admin = int(f.read().strip())
    if uid == admin:
        msg = f"❗ <b>Announcement:</b> {' '.join(context.args)}"
        ut.notify(context.job_queue, msg)
Пример #6
0
  def handle_notify_item(self, message):
    if gsettings.get_boolean("show-fullname"):
      sender_name = message["sender"].get("name", message["sender"].get("nick", ""))
    else:
      sender_name = message["sender"].get("nick", message["sender"].get("name", ""))

    notify_text = ""
    if len(message["text"]) > 0: 
      notify_text = message["text"]
    elif message.has_key("stream"):
      if message["stream"] == "images":
        notify_text = _("has shared a photo")
      if message["stream"] == "links":
        notify_text = _("has shared a link")
      if message["stream"] == "videos":
        notify_text = _("has shared a video")
    if message["sender"].has_key("image"):
      image = util.resources.get_avatar_path(message["sender"]["image"])
    else:
      #FIXME - we need to fix finding service icons in the service
      image = util.resources.get_ui_asset("%s.svg" % message["service"])
    if not image:
      #FIXME - we need to fix finding service icons in the service
      image = util.resources.get_ui_asset("%s.png" % message["service"])
    util.notify(sender_name, notify_text, image, 2000)

    return False
Пример #7
0
    def handle_notify_item(self, message):
        if SETTINGS["show_fullname"]:
            sender_name = message["sender"].get(
                "name", message["sender"].get("nick", ""))
        else:
            sender_name = message["sender"].get(
                "nick", message["sender"].get("name", ""))

        notify_text = ""
        if len(message["text"]) > 0:
            notify_text = message["text"]
        elif message.has_key("stream"):
            if message["stream"] == "images":
                notify_text = _("has shared a photo")
            if message["stream"] == "links":
                notify_text = _("has shared a link")
            if message["stream"] == "videos":
                notify_text = _("has shared a video")
        #image = util.resources.get_ui_asset("icons/breakdance/scalable/%s.svg" % message["service"])
        if message["sender"].has_key("image"):
            image = util.resources.get_avatar_path(message["sender"]["image"])
        else:
            image = util.resources.get_ui_asset(
                "icons/breakdance/scalable/%s.svg" % message["service"])
        if not image:
            image = util.resources.get_ui_asset(
                "icons/breakdance/scalable/%s.svg" % message["service"])
        util.notify(sender_name, notify_text, image, 2000)

        return False
Пример #8
0
def restart(update, context):
    uid = update.effective_message.chat.id
    with open('.adminid', 'r') as f:
        admin = int(f.read().strip())
    if uid == admin:
        msg = "⚠ Bot restarted. Please, synchronize bot timer /track."
        ut.notify(context.job_queue, msg)
Пример #9
0
def accept_or_decline_friend(action, user, content):
    """Request/accept/decline friend requests."""
    emails = content['emails']
    others = User.get_all(emails)

    if not others:
        return jsonify(), 418

    if action == 'add':
        [user.add(other) for other in others]

        if other.device:
            notify(
                [other.device],
                'Politically Incorrect',
                '{} added you as a friend!'.format(user.name)
            )

    elif action == 'delete':
        [user.delete(other) for other in others]

    else:
        return jsonify(), 404

    try:
        db.session.commit()
    except:
        db.session.rollback()
        raise

    return jsonify()
Пример #10
0
def accept_or_decline_game(id, action, user, content):
    """Join/invite/decline actions for games."""
    game = Game.get(id)
    player = Player.get(user, game)
    started = False

    if action == 'add':
        player.set_status_joined()
        joined = [p for p in game.players if p.status == Player.JOINED]

        if len(joined) == game.max_players:
            notify([
                p.user.device
                for p in game.players if p.user.device and p != player
            ], 'Politically Incorrect',
                   'The game "{}" has started!'.format(game.name))
            game.start()
            started = True

    elif action == 'delete':
        player.set_status_denied()

    else:
        return jsonify(), 404

    try:
        db.session.commit()
    except:
        db.session.rollback()
        raise

    return jsonify(started=started)
Пример #11
0
 def connection_close(self, ch, close):
   self.connection.close_code = (close.reply_code, close.reply_text)
   ch.connection_close_ok()
   self.connection.sock.close()
   if not self.connection.opened:
     self.connection.failed = True
     notify(self.connection.condition)
Пример #12
0
  def handle_notify_item(self, message):
    if SETTINGS["show_fullname"]:
      sender_name = message["sender"].get("name", message["sender"].get("nick", ""))
    else:
      sender_name = message["sender"].get("nick", message["sender"].get("name", ""))

    notify_text = ""
    if len(message["text"]) > 0: 
      notify_text = message["text"]
    elif message.has_key("stream"):
      if message["stream"] == "images":
        notify_text = _("has shared a photo")
      if message["stream"] == "links":
        notify_text = _("has shared a link")
      if message["stream"] == "videos":
        notify_text = _("has shared a video")
    #image = util.resources.get_ui_asset("icons/breakdance/scalable/%s.svg" % message["service"])
    if message["sender"].has_key("image"):
      image = util.resources.get_avatar_path(message["sender"]["image"])
    else:
      image = util.resources.get_ui_asset("icons/breakdance/scalable/%s.svg" % message["service"])
    if not image:
      image = util.resources.get_ui_asset("icons/breakdance/scalable/%s.svg" % message["service"])
    util.notify(sender_name, notify_text, image, 2000)

    return False
Пример #13
0
def play(id, user, content):
    """
    Handle main gameplay. If the requesting user
    is the current judge, then expect an email
    in the request body and interpret it as
    the round winner chosen by the judge. Otherwise,
    the request body should contain card ids in the
    user's hand, which should be placed on the table.

    request :=
        POST ({
            'cards': [int]
        } | {
            'email': str
        })
    """

    game = Game.get(id)
    player = Player.get(user, game)

    if game.status != Game.ONGOING:
        return jsonify(message='This game isn\'t in-progress.'), 418

    if user == game.judge.user:
        email = content['email']
        winner = next(
            (player for player in game.players if player.user.email == email),
            None)
        winner.add_points(1)
        game.new_round(winner)

    else:
        if player.played:
            return jsonify(), 418

        cards = content['cards']
        map = {card.id: card for card in player.hand}
        cards = [map[card] for card in cards]

        if len(cards) != game.black_card.answers:
            return jsonify(message='Invalid play, mate.'), 418

        player.play_cards(cards)

    notify(
        [p.user.device for p in game.players if p.user.device and p != player],
        'Politically Incorrect',
        'Something happened in "{}"!'.format(game.name))

    for p in game.players:
        p.seen = False

    player.seen = True

    try:
        db.session.commit()
    except:
        db.session.rollback()

    return jsonify()
Пример #14
0
def accept_or_decline_game(id, action, user, content):
    """Join/invite/decline actions for games."""
    game    = Game.get(id)
    player  = Player.get(user, game)
    started = False

    if action == 'add':
        player.set_status_joined()
        joined = [p for p in game.players
                    if p.status == Player.JOINED]

        if len(joined) == game.max_players:
            notify(
                [p.user.device for p in game.players if p.user.device and p != player],
                'Politically Incorrect',
                'The game "{}" has started!'.format(game.name)
            )
            game.start()
            started = True

    elif action == 'delete':
        player.set_status_denied()

    else:
        return jsonify(), 404

    try:
        db.session.commit()
    except:
        db.session.rollback()
        raise

    return jsonify(started=started)
Пример #15
0
def get_pasteboard_file_path():
    """
    获取剪贴板的文件路径
    """

    # 获取系统剪贴板对象
    pasteboard = NSPasteboard.generalPasteboard()
    # 剪贴板里的数据类型
    data_type = pasteboard.types()

    # 如果是直接复制的文件
    if NSFilenamesPboardType in data_type:
        # 获取到这个文件的路径和类型
        file_path = pasteboard.propertyListForType_(NSFilenamesPboardType)[0]
        return file_path, False

    # 剪贴板是png,tiff文件,生成文件返回文件路径
    for file_type, pastedboard_file_type in TYPE_MAP.items():
        if pastedboard_file_type not in data_type:
            continue

        file_path = image_path(file_type)
        data = pasteboard.dataForType_(pastedboard_file_type)
        ret = data.writeToFile_atomically_(file_path, False)
        if not ret:
            notify('从剪贴板写入文件失败')
            return '', True

        return file_path, True

    return '', False
Пример #16
0
def setupAll():
    try:
        run(trucks, [])
        run(compute, [])
        run(stops,[])
        notify("complete setup succeeded!")
    except:
        print traceback.format_exc()
        notify("complete setup failed...")
Пример #17
0
def print_status():
    global tries, start_time

    STATUS = 'tries: {:>10}, run time: {}'

    run_time = time.time() - start_time
    run_time = datetime.timedelta(seconds=run_time)

    util.notify(STATUS.format(tries, run_time))
Пример #18
0
    def is_valid(dev_name):
        util.notify('Validating device name...')

        drv_handle = util.create_drv_handle(dev_name)

        if drv_handle != -1:
            ctypes.windll.kernel32.CloseHandle(drv_handle)
            return True
        else:
            return False
Пример #19
0
def monitor_dos(pid):
    global drv_handle_cache

    while True:
        dev_name = random.choice(drv_handle_cache.keys())
        drv_handle = util.create_drv_handle(dev_name)
        if drv_handle == win32file.INVALID_HANDLE_VALUE:
            util.notify('Got DoS')
            os.kill(pid, signal.SIGTERM)
        else:
            ctypes.windll.kernel32.CloseHandle(drv_handle)
Пример #20
0
 def run(self):
     logger.info('JianzhuThread start, will do %d times'%(Times))
     #logger.info('I will jianzhu: ' + ' '.join(Jianzhu_List))
     if Delay_Time > 0:
         logger.info('I will start jianzhu at ' + util.next_time(Delay_Time))
         time.sleep(Delay_Time)
     inteval = 30
     ci = 1
     # old
     if Times > 0:
         while ci <= Times:
             for i in range(len(Jianzhu_List)):
                 self.do_jianzhu(Jianzhu_List[i])
                 if i < len(Jianzhu_List) - 1:
                     time.sleep(inteval)
             logger.info('sleeping %d seconds in %d time'%(Sleep_Time, ci))
             logger.info('next round will at ' + util.next_time(Sleep_Time))
             ci += 1
             time.sleep(Sleep_Time)
     else:
         while True:
             # get general info
             gi = GeneralInfo()
             next_cd = gi.get_next_CDTime()
             stime = gi.get_serverTime()
             next_jname = self.get_next_jname(gi)
             sp = 0
             if not next_jname:
                 logger.info('I will send notify at server time: ' + util.next_time(gi.get_next_CDTime()-gi.get_serverTime()))
                 time.sleep(max(0, gi.get_next_CDTime() - gi.get_serverTime()))
                 logger.info('All jianzu has upgraded to max level, will exit')
                 util.notify('All jianzu has upgraded to max level')
                 break
             if next_cd > stime:
                 sp = next_cd - stime + 1
             if sp > 0:
                 logger.info('I will start upgrade %s at %s'%(next_jname, util.next_time(sp)))
                 time.sleep(sp)
             else:
                 logger.info('I will start upgrade %s now'%(next_jname))
             res = self.do_jianzhu(next_jname)
             if res.has_key('exception'):
                 msg = res['exception']['message']
                 logger.error('Got Exception "%s", will exit'%(msg))
                 if msg == 'CDTimeNotCool':
                     continue
                 elif msg == 'noBuildTeamUsable':
                     continue
                 elif msg == 'maintenance':
                     time.sleep(2000)
                     continue
                 return
             time.sleep(2)
def submit(news, start=False):
    count = len(news)
    if count > 0:
        import openstack
        otc = openstack.connect()
        for uuid, title in news.viewitems():
            notify("%s %s" % (uuid, title), False)
            dms.send(
                "SP-idavailable", uuid
            )  #name of the queue to send to (title = name of product, uuid = id of product)
            notify("")
    return count
Пример #22
0
  def send_error_notify(self, error):
    error = json.loads(error)["error"]

    if self.notified_errors.has_key(error["account"]["service"]):
      if self.notified_errors[error["account"]["service"]] == error["message"]:
        return
    if util.can_notify:
      icon = util.resources.get_ui_asset("icons/breakdance/scalable/%s.svg" % error["account"]["service"])
      if not icon:
        icon = util.resources.get_ui_asset("gwibber.svg")
      util.notify(error["account"]["service"], error["message"], icon, 2000)
    self.notified_errors[error["account"]["service"]] = error["message"]
Пример #23
0
  def handle_notify_item(self, message):
    if SETTINGS["show_fullname"]:
      sender_name = message["sender"].get("name", message["sender"].get("nick", ""))
    else:
      sender_name = message["sender"].get("nick", message["sender"].get("name", ""))

    #image = util.resources.get_ui_asset("icons/breakdance/scalable/%s.svg" % message["service"])
    image = util.resources.get_avatar_path(message["sender"]["image"])
    if not image:
      image = util.resources.get_ui_asset("icons/breakdance/scalable/%s.svg" % message["service"])
    util.notify(sender_name, message["text"], image, 2000)

    return False
Пример #24
0
 def run(self):
     logger.info('KejiThread start, will do %d times'%(Times))
     #logger.info('I upgrade keji: ' + ' '.join(Kid_List))
     if Delay_Time > 0:
         logger.info('I will start keji at ' + util.next_time(Delay_Time))
         time.sleep(Delay_Time)
     inteval = 30
     ci = 1
     if Times > 0:
         while ci <= Times:
             for i in range(len(Kid_List)):
                 self.do_keji(Kid_List[i])
                 if i < len(Kid_List) - 1:
                     time.sleep(inteval)
             if ci == Times:
                 break
             logger.info('sleeping %d seconds in %d time'%(Sleep_Time, ci))
             logger.info('next round will at ' + util.next_time(Sleep_Time))
             ci += 1
             time.sleep(Sleep_Time)
     else:
         while True:
             # get general info
             gi = GeneralInfo()
             ki = KejiInfo()
             next_keji_cd = gi.get_next_keji_CDTime()
             stime = gi.get_serverTime()
             next_kname = self.get_next_kname(gi, ki)
             sp = 0
             if not next_kname:
                 logger.info('I will send notify at server time: ' + util.next_time(gi.get_next_keji_CDTime() - gi.get_serverTime()))
                 time.sleep(gi.get_next_keji_CDTime() - gi.get_serverTime())
                 logger.info('All keji has upgraded to max level, will exit')
                 util.notify('All keji has upgraded to max level')
                 break
             if next_keji_cd > stime:
                 sp = next_keji_cd - stime + 1
             if sp > 0:
                 logger.info('I will start upgrade %s at %s'%(next_kname, util.next_time(sp)))
                 time.sleep(sp)
             else:
                 logger.info('I will start upgrade %s now'%(next_kname))
             res = self.do_keji(next_kname)
             if res.has_key('exception'):
                 msg = res['exception']['message']
                 logger.error('Got Exception "%s", will exit'%(msg))
                 if msg == 'CDTimeNotCool':
                     continue
                 return
             time.sleep(2)
Пример #25
0
def create_game(user, content):
    """Creates a pending game."""
    name        = content['name']
    max_points  = max(content['max_points'], 5)
    max_players = content['max_players']
    random      = content['random']
    emails      = content['emails']

    if len(emails) < 3:
        return jsonify(message='You need to invite more people!'), 418

    game = Game.create(
        user, name, max_points, min(max_players, len(emails) + 1), random
    )
    users   = User.get_all(emails) + [user]
    players = Player.create_all(users, game)

    player = next(
        (player for player in players if player.user == user),
        None
    )
    player.set_status_joined()

    notify(
        [u.device for u in users if u != user],
        'Politically Incorrect',
        'You\'ve been invited to a game: "{}"!'.format(name)
    )

    try:
        db.session.commit()
    except:
        db.session.rollback()
        raise

    return jsonify(**{
        'id'         : game.id,
        'name'       : game.name,
        'max_points' : game.max_points,
        'max_players': game.max_players,
        'status'     : game.status,
        'players'    : [
            {
                'name'  : p.user.name,
                'email' : p.user.email,
                'status': p.status
            }
            for p in game.players
        ]
    })
Пример #26
0
def callback_err(err_code):
    if err_code == 6:
        util.notify('Waiting for 3 secs due to invalid driver handle...')
        time.sleep(3)

    elif err_code == 998:
        pass
        '''
        if reproducer.reproduce(LAST_FUZZ_INFO_FILE_NAME):
            backup_error()
        '''

    else:
        raise NotImplementedError
Пример #27
0
def main():
    suc_list = []
    fail_list = []
    for uname in users:
        res = tongsang(uname)
        if res.has_key("exception"):
            fail_list.append(uname)
        else:
            suc_list.append(uname)
        time.sleep(2)
    logger.info("tongsang suc list %s" % (unicode(suc_list)))
    if len(fail_list) > 0:
        msg = "tongsang %s failed" % (unicode(fail_list))
        util.notify(msg)
Пример #28
0
  def run(self):
    frame_dec = FrameDecoder()
    seg_dec = SegmentDecoder()
    op_dec = OpDecoder()

    while not self.closed:
      try:
        data = self.sock.recv(64*1024)
        if not data:
          self.detach_all()
          break
        # If we have a security layer and it sends us no decoded data,
        # that's OK as long as its return code is happy.
        if self.security_layer_rx:
          try:
            data = self.security_layer_rx.decode(data)
          except:
            self.detach_all()
            break
      # When we do not use SSL transport, we get periodic 
      # spurious timeout events on the socket.  When using SSL,
      # these events show up as timeout *errors*.  Both should be
      # ignored unless we have aborted.
      except socket.timeout:
        if self.aborted():
          self.close_code = (None, "connection timed out")
          self.detach_all()
          break
        else:
          continue
      except socket.error, e:
        if self.aborted() or str(e) != "The read operation timed out":
          self.close_code = (None, str(e))
          self.detach_all()
          break
        else:
          continue
      frame_dec.write(data)
      seg_dec.write(*frame_dec.read())
      op_dec.write(*seg_dec.read())
      for op in op_dec.read():
        try:
          self.delegate.received(op)
        except Closed, e:
          self.close_code = (None, str(e))
          if not self.opened:
            self.failed = True
            self.closed = True
            notify(self.condition)
Пример #29
0
    def run(self):
        frame_dec = FrameDecoder()
        seg_dec = SegmentDecoder()
        op_dec = OpDecoder()

        while not self.closed:
            try:
                data = self.sock.recv(64 * 1024)
                if not data:
                    self.detach_all()
                    break
                # If we have a security layer and it sends us no decoded data,
                # that's OK as long as its return code is happy.
                if self.security_layer_rx:
                    try:
                        data = self.security_layer_rx.decode(data)
                    except:
                        self.detach_all()
                        break
            # When we do not use SSL transport, we get periodic
            # spurious timeout events on the socket.  When using SSL,
            # these events show up as timeout *errors*.  Both should be
            # ignored unless we have aborted.
            except socket.timeout:
                if self.aborted():
                    self.close_code = (None, "connection timed out")
                    self.detach_all()
                    break
                else:
                    continue
            except socket.error, e:
                if self.aborted() or str(e) != "The read operation timed out":
                    self.close_code = (None, str(e))
                    self.detach_all()
                    break
                else:
                    continue
            frame_dec.write(data)
            seg_dec.write(*frame_dec.read())
            op_dec.write(*seg_dec.read())
            for op in op_dec.read():
                try:
                    self.delegate.received(op)
                except Closed, e:
                    self.close_code = (None, str(e))
                    if not self.opened:
                        self.failed = True
                        self.closed = True
                        notify(self.condition)
Пример #30
0
  def send_error_notify(self, error):
    if not isinstance(error, dict):
      logger.error("Failed to parse error message: %s", error)
      return
    if error.has_key("error"):
      error = json.loads(error)["error"]
    else:
      error = json.loads(error)

    if self.notified_errors.has_key(error["account"]["service"]):
      if self.notified_errors[error["account"]["service"]] == error["message"]:
        return
    if util.can_notify:
      util.notify(error["account"]["service"], error["message"], icon, 2000)
    self.notified_errors[error["account"]["service"]] = error["message"]
Пример #31
0
def run(func, args):
    messages = {
        trucks: "import trucks ",
        compute: "compute truck dates and centers ",
        stops: "compute stops and properties"
    }
    message = messages[func]

    try:
        getTime(func, message, *args)
        # func(*args)
        #notify(message)
    except:
        print traceback.format_exc()
        notify(message + "failed")
Пример #32
0
    def send_error_notify(self, error):
        error = json.loads(error)["error"]

        if self.notified_errors.has_key(error["account"]["service"]):
            if self.notified_errors[error["account"]
                                    ["service"]] == error["message"]:
                return
        if util.can_notify:
            icon = util.resources.get_ui_asset(
                "icons/breakdance/scalable/%s.svg" %
                error["account"]["service"])
            if not icon:
                icon = util.resources.get_ui_asset("gwibber.svg")
            util.notify(error["account"]["service"], error["message"], icon,
                        2000)
        self.notified_errors[error["account"]["service"]] = error["message"]
Пример #33
0
    def handle_notify_item(self, message):
        if SETTINGS["show_fullname"]:
            sender_name = message["sender"].get(
                "name", message["sender"].get("nick", ""))
        else:
            sender_name = message["sender"].get(
                "nick", message["sender"].get("name", ""))

        #image = util.resources.get_ui_asset("icons/breakdance/scalable/%s.svg" % message["service"])
        image = util.resources.get_avatar_path(message["sender"]["image"])
        if not image:
            image = util.resources.get_ui_asset(
                "icons/breakdance/scalable/%s.svg" % message["service"])
        util.notify(sender_name, message["text"], image, 2000)

        return False
Пример #34
0
def isError(toCheck):
    try:
        if toCheck['error']:
            if toCheck['error_code'] == 8:
                # need to refresh token
                refreshToken()
                return 8
            else:
                util.notify(
                    "Error " + str(toCheck['error_code']) + ": " +
                    string.capwords(toCheck['error'].replace("_", " ")))
                util.logError("Error " + str(toCheck['error_code']) + ": " +
                              toCheck['error'])
                return True
    except:
        return False
Пример #35
0
def create_game(user, content):
    """Creates a pending game."""
    name = content['name']
    max_points = max(content['max_points'], 5)
    max_players = content['max_players']
    random = content['random']
    emails = content['emails']

    if len(emails) < 3:
        return jsonify(message='You need to invite more people!'), 418

    game = Game.create(user, name, max_points, min(max_players,
                                                   len(emails) + 1), random)
    users = User.get_all(emails) + [user]
    players = Player.create_all(users, game)

    player = next((player for player in players if player.user == user), None)
    player.set_status_joined()

    notify([u.device for u in users if u != user], 'Politically Incorrect',
           'You\'ve been invited to a game: "{}"!'.format(name))

    try:
        db.session.commit()
    except:
        db.session.rollback()
        raise

    return jsonify(
        **{
            'id':
            game.id,
            'name':
            game.name,
            'max_points':
            game.max_points,
            'max_players':
            game.max_players,
            'status':
            game.status,
            'players': [{
                'name': p.user.name,
                'email': p.user.email,
                'status': p.status
            } for p in game.players]
        })
Пример #36
0
def download(name, image, url, dest=addon.getSetting('download_path')):
    try:
        xbmc.executebuiltin("ActivateWindow(busydialog)")
        import control

        if url == None:
            return control.infoDialog(control.lang(30501).encode('utf-8'))
        headers = ("Authorization",
                   "Bearer " + str(xbmcaddon.Addon().getSetting('rd_access')))
        url = url.split('|')[0]

        content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
        transname = name.translate('\/:*?"<>|').strip('.')
        levels = ['../../../..', '../../..', '../..', '..']

        dest = control.transPath(dest)
        for level in levels:
            try:
                control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except:
                pass
        control.makeFile(dest)
        dest = os.path.join(dest, os.path.splitext(transname)[0])

        control.makeFile(dest)
        dest = os.path.join(dest, transname)

        sysheaders = urllib.quote_plus(json.dumps(headers))

        sysurl = urllib.quote_plus(url)

        systitle = urllib.quote_plus(name)

        sysimage = urllib.quote_plus(image)

        sysdest = urllib.quote_plus(dest)

        script = inspect.getfile(inspect.currentframe())
        cmd = 'RunScript(%s, %s, %s, %s, %s, %s)' % (
            script, sysurl, sysdest, systitle, sysimage, sysheaders)

        xbmc.executebuiltin(cmd)
    except:
        xbmc.executebuiltin("Dialog.Close(busydialog)")
        util.notify(ADDON_ID, "Error Downloading")
Пример #37
0
  def closed(self):
    self.lock.acquire()
    try:
      if self._closed: return

      error = self.error()
      for id in self.results:
        f = self.results[id]
        f.error(error)
      self.results.clear()

      for q in self._incoming.values():
        q.close(error)

      self._closed = True
      notify(self.condition)
    finally:
      self.lock.release()
Пример #38
0
    def onPlayBackEnded(self):
        if self.varHasPlayed == "Yes":
            pass
        else:
            __setting1__ = xbmcaddon.Addon('script.tv.promos').getSetting("StreamUrl")

            if __setting1__ == 'Youtube':
                xbmc.executebuiltin("XBMC.PlayMedia(plugin://plugin.video.youtube/?action=play_video&videoid=" + self.varVideoID + ")")

            if __setting1__ == 'Tv Rage':
                if self.varEpisodeVideo == None:
                    util.notify("Sorry no Promo Found")
                else:
                    varStreamDown1 = xbmcaddon.Addon('script.tv.promos').getSetting("TVRageStream")
                    if varStreamDown1 == 'Download':
                        util.PlayThis(self.varStreamLocation + self.varShowName + '.flv')
                    else:
                        util.PlayThis('http' + self.varEpisodeVideo + '.flv')
Пример #39
0
  def send_error_notify(self, error):
    if not isinstance(error, dict):
      log.logger.error("Failed to parse error message: %s", error)
      return
    if error.has_key("error"):
      error = json.loads(error)["error"]
    else:
      error = json.loads(error)

    if self.notified_errors.has_key(error["account"]["service"]):
      if self.notified_errors[error["account"]["service"]] == error["message"]:
        return
    if util.can_notify:
      icon = util.resources.get_ui_asset("icons/breakdance/scalable/%s.svg" % error["account"]["service"])
      if not icon:
        icon = util.resources.get_ui_asset("gwibber.svg")
      util.notify(error["account"]["service"], error["message"], icon, 2000)
    self.notified_errors[error["account"]["service"]] = error["message"]
Пример #40
0
    def closed(self):
        self.lock.acquire()
        try:
            if self._closed: return

            error = self.error()
            for id in self.results:
                f = self.results[id]
                f.error(error)
            self.results.clear()

            for q in self._incoming.values():
                q.close(error)

            self._closed = True
            notify(self.condition)
        finally:
            self.lock.release()
Пример #41
0
    def stalkPosts(self, page):
        pageName = page['page']
        logger.debug('Starting {} post thread now'.format(pageName))

        while True:
            if pageName in self.deadPages:
                logger.debug(
                    'Closing stalk posts thread for account {}. It has been removed from stalking'
                    .format(pageName))
                return  #Close thread
            logger.debug('Monitoring posts of {} now...'.format(pageName))
            try:
                post = self.getPost(page['userid'])
            except:
                logger.error("Unable to get posts - closing thread"
                             )  # maybe keep trying until success?
                return
            data = extractPostData(post)
            if data != []:
                posts = [
                    p for p in post['items']
                    for posts in db.fetch('pages', 'page', pageName)['posts']
                ]
                posts_id = []
                for p in posts:
                    posts_id.append(p["id"].split("_")[0])
                # let's grab only first few
                data = data[:5]
                for d in data:
                    d['id'] = d['id'].split("_")[0]
                    if d['id'] not in posts_id:
                        logger.info('Post to add: {}'.format(d))
                        if page['referenceId'] == "":
                            logger.info(
                                "Cannot notify, referenceId is empty. I'm notifying it to admin (it is a debug feature, everyone must have a referenceId in future)"
                            )
                            notify(parsePost(d, pageName), config["adminId"])
                        else:
                            notify(parsePost(d, pageName), page['referenceId'])
                        db.append('pages', 'page', pageName, 'posts', d)
            timeToSleep = 20
            logger.debug('[page:{}] Waiting {} seconds'.format(
                pageName, timeToSleep))
            time.sleep(timeToSleep)
Пример #42
0
 def run(self):
     logger.info('weipai Thread start, will weipai type %s'%(Type))
     if Delay_Time > 0:
         logger.info('I will start weipai at ' + util.next_time(Delay_Time))
         time.sleep(Delay_Time)
     cnt = 1
     while True:
         try:
             ml = self.get_max_level(Type)
             if int(ml) >= MaxLevel:
                 msg = 'Weipai reach max level %s, TotalCost %d'%(ml, TotalCost)
                 logger.info(msg)
                 util.notify(msg)
                 break
             logger.info('Type:%s MaxLevel:%s'%(Type, ml))
             res = self.do_weipai(Type, ml)
             if res[0].has_key('exception'):
                 msg = res[0]['exception']['message']
                 logger.info('got exception %s, TotalCost %d'%(msg, TotalCost))
                 if msg == 'CDTimeNotCool':
                     gi = GeneralInfo()
                     sp = gi.get_weipai_CDTime() - gi.get_serverTime()
                     logger.info('Next round weipai will start at ' + util.next_time(sp))
                     time.sleep(sp)
                     continue
                 else:
                     break
             try:
                 eq = res[1]['resArr']['userEquip']
                 logger.info('Got Equip level=%s id=%s color=%s name=%s salePrice=%s maxPiece=%s currPiece=%s'%(ml, eq['id'], eq['type']['color'], eq['type']['name'], eq['type']['salePrice'], eq['maxPiece'], eq['currPiece']))
                 price = int(eq['type']['salePrice']) * int(eq['currPiece']) / int(eq['maxPiece'])
                 if int(eq['type']['color']) <= SellColor:
                     self.sell(eq['id'], price)
                 else:
                     logger.info('I will keep it')
             except:
                 pass
             logger.info('finished %d time, TotalCost %d'%(cnt, TotalCost))
             cnt += 1
             time.sleep(2)
         except:
             logger.info(traceback.format_exc())
             time.sleep(10)
Пример #43
0
def get_pasteboard_img_path():
    """获取剪贴板图片文件路径"""

    file_path, remove_raw = get_pasteboard_file_path()
    if not file_path:
        notify('请先截图或者复制一张图片')
        return ''

    file_name = os.path.split(file_path)[-1]
    file_type = file_name.split('.')[-1]

    # 检查是否是图片类型的文件
    if file_type not in ALLOW_FILE_TYPES:
        notify('文件类型{0}不在支持列表[png、jpeg、jpg、tiff]'.format(file_type))
        return ''

    file_path = convert_compress_img(file_path, remove_raw)

    return file_path
def search(daysBack=7):
    import xml.etree.cElementTree as ET
    url = SITE["SEARCH"].format(daysBack)
    news, offset, rowsBreak, keys, ns = dict(), 0, 50000, [], {
        "atom": "http://www.w3.org/2005/Atom",
        "opensearch": "http://a9.com/-/spec/opensearch/1.1/"
    }
    while offset < rowsBreak:  #next pagination page:
        rsp = util.urlOpen(url + str(offset))
        root = ET.ElementTree(file=rsp).getroot()
        if offset == 0:
            rowsBreak = int(root.find("opensearch:totalResults", ns).text)
        for e in root.iterfind("atom:entry", ns):
            title, uuid = e.find("atom:title", ns).text, e.find("atom:id",
                                                                ns).text
            if not util.exists(title): news[uuid] = title

        offset += 100  #ultimate DHuS pagination page size limit (rows per page).
    notify("%d/%d" % (len(news), rowsBreak))
    return news
Пример #45
0
  def run(self):
    frame_dec = FrameDecoder()
    seg_dec = SegmentDecoder()
    op_dec = OpDecoder()

    while not self.closed:
      try:
        data = self.sock.recv(64*1024)
        if not data:
          self.detach_all()
          break
        # If we have a security layer and it sends us no decoded data,
        # that's OK as long as its return code is happy.
        if self.security_layer_rx:
          status, data = self.security_layer_rx.decode(data)
          if not status:
            self.detach_all()
            break
      except socket.timeout:
        if self.aborted():
          self.close_code = (None, "connection timed out")
          self.detach_all()
          break
        else:
          continue
      except socket.error, e:
        self.close_code = (None, str(e))
        self.detach_all()
        break
      frame_dec.write(data)
      seg_dec.write(*frame_dec.read())
      op_dec.write(*seg_dec.read())
      for op in op_dec.read():
        try:
          self.delegate.received(op)
        except Closed, e:
          self.close_code = (None, str(e))
          if not self.opened:
            self.failed = True
            self.closed = True
            notify(self.condition)
Пример #46
0
def playRecording(params):
    ipaddress = addon.getSetting("ipaddress")
    recording = "http://" + ipaddress + "/PVR/Records/session?recordId=" + str(
        params['id'])
    response = urllib2.urlopen(recording)
    if response and response.getcode() == 200:
        ticket = json.loads(response.read())
        if ticket.has_key('pcLockReason'):
            util.notify('plugin.video.eetv',
                        "Unable to Play " + ticket['pcLockReason'])
        else:
            url = "http://" + ipaddress + "/PVR/Records/getVideo?sessionId=" + ticket[
                'id']
            params['url'] = url
            params['label'] = params['label']
            params['thumb'] = params['icon']
            util.playEE(params)
    else:
        util.notify('plugin.video.eetv',
                    'Could not Get Playback Token' % (url))
    pass
Пример #47
0
    def stalkStories(self, page):
        pageName = page['page']
        logger.debug('Starting {} story thread now'.format(pageName))
        self.alivePages.append(pageName)

        while True:
            if pageName in self.deadPages:
                logger.debug(
                    'Closing stalk stories thread for account {}. It has been removed from stalking'
                    .format(pageName))
                return  #Close thread
            logger.debug('Monitoring stories of {} now...'.format(pageName))
            try:
                story = self.getStory(page['userid'])
            except:
                logger.error("Unable to get story - closing thread")
                return
            data = extractStoryData(story)
            if data != []:
                stories = [
                    story
                    for story in db.fetch('pages', 'page', pageName)['stories']
                ]
                storiesId = [story['id'] for story in stories]
                for d in data:
                    if d['id'] not in storiesId:
                        logger.info('Story to add: {}'.format(d))
                        if page['referenceId'] == "":
                            logger.info(
                                "Cannot notify, referenceId is empty. I'm notifying it to admin (it is a debug feature, everyone must have a referenceId in future)"
                            )
                            notify(parseStory(d, pageName), config["adminId"])
                        else:
                            notify(parseStory(d, pageName),
                                   page['referenceId'])
                        db.append('pages', 'page', pageName, 'stories', d)
            timeToSleep = 20
            logger.debug('[page:{}] Waiting {} seconds'.format(
                pageName, timeToSleep))
            time.sleep(timeToSleep)
Пример #48
0
def unrestrict(parameters):
    cj_rd = cookielib.CookieJar()
    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
    opener_rd.addheaders = [
        ("Authorization", "Bearer " +
         str(xbmcaddon.Addon('script.realdebrid.mod').getSetting('rd_access')))
    ]

    if 'url' in parameters:
        link = parameters['url']
    else:
        link = util.searchDialog("Enter link to unrestrict")

    if link:
        data_rd = urllib.urlencode({'link': link})

        error = True
        attempts = 0
        while error:
            try:
                resp = opener_rd.open(
                    'https://api.real-debrid.com/rest/1.0/unrestrict/link',
                    data_rd)
                content = resp.read()

                credJSON = json.loads(content)
                error = True
                return credJSON
            except Exception as e:
                util.logError("realdebrid error: " + str(e))
                attempts = attempts + 1
                if attempts > 3:
                    error = True
                    util.notify("Unable to unrestrict link")
                    break
                elif "Unauthorized" in e:
                    refreshToken()

    return False
Пример #49
0
    def onPlayBackEnded(self):
        if self.varHasPlayed == "Yes":
            pass
        else:
            __setting1__ = xbmcaddon.Addon('script.tv.promos').getSetting(
                "StreamUrl")

            if __setting1__ == 'Youtube':
                xbmc.executebuiltin(
                    "XBMC.PlayMedia(plugin://plugin.video.youtube/?action=play_video&videoid="
                    + self.varVideoID + ")")

            if __setting1__ == 'Tv Rage':
                if self.varEpisodeVideo == None:
                    util.notify("Sorry no Promo Found")
                else:
                    varStreamDown1 = xbmcaddon.Addon(
                        'script.tv.promos').getSetting("TVRageStream")
                    if varStreamDown1 == 'Download':
                        util.PlayThis(self.varStreamLocation +
                                      self.varShowName + '.flv')
                    else:
                        util.PlayThis('http' + self.varEpisodeVideo + '.flv')
Пример #50
0
    def addPage(self, pageName, referenceId=''):
        self.istance.searchUsername(pageName)
        if self.istance.LastJson['status'] == 'fail':
            logger.error("There was an error while getting userid")
            notify('There was an error while getting userid',
                   config["adminId"])
            return fail(self.istance.LastJson['message'])

        if db.fetch('pages', 'page', pageName) != None:
            return fail('Page {} already registered!'.format(pageName))
        data = {
            'page': pageName,
            'stories': [],
            'created_at': str(time.time()),
            'userid': str(self.istance.LastJson['user']['pk']),
            'referenceId': str(referenceId)
        }
        if db.save('pages', data):
            self.pendingPages.append(data)
            logger.info('Registered {}'.format(pageName))
            return success('Page {} registered'.format(pageName))
        return fail(
            'Page {} not registered cause database error'.format(pageName))
Пример #51
0
def showLiveTV():
    ipaddress = addon.getSetting("ipaddress")
    if ipaddress == '':
        xbmc.executebuiltin(
            'XBMC.Notification(Info:,"IP Address Not Set",3000,' +
            addon.getAddonInfo('icon') + ')')
    else:
        playlist = "http://" + ipaddress + "/Live/Channels/getList?tvOnly=0&avoidHD=0&allowHidden=0&fields=name,id,zap,isDVB,hidden,rank,isHD,logo"
        response = urllib2.urlopen(playlist)
        if response and response.getcode() == 200:
            channels = json.loads(response.read())
            for channel in channels:
                if channel['hidden'] == False and (channel['zap'] < 225
                                                   or channel['zap'] > 300):
                    params = {'playlivetv': 1}
                    params['label'] = str(
                        channel['zap']) + ' ' + channel['name']
                    params[
                        'url'] = "http://" + ipaddress + "/Live/Channels/get?channelId=" + channel[
                            'id']
                    params['id'] = channel['id']
                    if channel.has_key('logo') == True:
                        params['thumb'] = channel['logo']
                    else:
                        params[
                            'thumb'] = "http://" + ipaddress + "/Live/Channels/getLogo?zap=" + str(
                                channel['zap'])
                    params['zap'] = channel['zap']
                    thumb = params['thumb']
                    util.addMenuItem(params['label'], util.makeLink(params),
                                     thumb, thumb, False)
            util.endListing()
        else:
            util.notify('plugin.video.eetv',
                        'Could not open URL %s to create menu' % (url))
    pass
Пример #52
0
def upload_img2github():
    if not check_config():
        return

    img_path = get_pasteboard_img_path()

    if img_path:
        notify("开始上传图片到github,请稍等")
        result = upload2github()
        if result:
            notify(result)
            os.remove(img_path)
        else:
            # width, height = get_img_size(img_path)
            image_name = os.path.split(img_path)[-1]
            # markdown_img = IMG_TPL.format(image_url(image_name), width, height)
            markdown_img = IMG_TPL.format(image_url(image_name))
            print markdown_img
            write_to_pasteboard(markdown_img)
            notify('Markdown格式Image已在Clipboard')
Пример #53
0
 def post(self):
   user = users.get_current_user()
   item = model.Item.get( self.request.get( "key" ) )
   logging.info( "got item %s" % item.title )
   if item.status == "INPROGRESS":
     # current max
     amount = float( self.request.get( "amount" ) )
     logging.info( "got amount %f" % amount )
     if amount > float( item.bid_info()['bid'] ):
       balance = model.Profile.find( user ).preapproval_amount
       if int(amount*100) <= balance: # TODO check preapproval expiry
         logging.info( "adding bid" )
         model.Bid( bidder=user, amount=int(amount*100), item=item ).save()
         util.notify_all(user, "You bid $%.2f for %s" % ( amount, item.title ) )
       else:
         util.notify( user, "Bid exceeds balance of $%.2f. Update your profile!" % float( balance / 100 ) ) # no good
     else:
       util.notify( user, "Bid must be more than $%.2f" % float( item.bid_info()['bid'] ) ) # no good
   else:
     util.notify( user, "Item '%s' is no longer being auctioned" % item.title ) # no good
Пример #54
0
 def run(self):
     logger.info("weipai Thread start, will weipai type %s" % (Type))
     if Delay_Time > 0:
         logger.info("I will start weipai at " + util.next_time(Delay_Time))
         time.sleep(Delay_Time)
     cnt = 1
     first_time = True
     rc = RoundControl()
     while True:
         try:
             ml = self.get_max_level(Type)
             if first_time:
                 first_time = False
             else:
                 if int(ml) >= MaxLevel:
                     msg = "Weipai reach max level %s, TotalCost %d" % (ml, TotalCost)
                     logger.info(msg)
                     util.notify(msg)
                     break
             logger.info("Type:%s MaxLevel:%s" % (Type, ml))
             if not rc.can_continue(ml):
                 rc.reset()
                 gi = GeneralInfo()
                 sp = gi.get_weipai_CDTime() - gi.get_serverTime() - 15
                 logger.info("Break by RoundControl, Next round weipai will start at " + util.next_time(sp))
                 time.sleep(sp)
                 continue
             res = self.do_weipai(Type, ml)
             # res = util.send_command('weipai', Type, ml)
             if res[0].has_key("exception"):
                 msg = res[0]["exception"]["message"]
                 logger.info("got exception %s, TotalCost %d" % (msg, TotalCost))
                 if msg == "CDTimeNotCool":
                     gi = GeneralInfo()
                     sp = max(gi.get_weipai_CDTime() - gi.get_serverTime(), 0)
                     logger.info("Next round weipai will start at " + util.next_time(sp))
                     time.sleep(sp)
                     continue
                 elif msg == "maintenance":
                     logger.info("Got Exception %s" % (msg))
                     sp = 3600
                     logger.info("Next round weipai will start at " + util.next_time(sp))
                     time.sleep(sp)
                     continue
                 else:
                     logger.info("Exit for Exception %s" % (msg))
                     break
             try:
                 eq = res[1]["resArr"]["userEquip"]
                 logger.info(
                     "Got Equip level=%s id=%s color=%s name=%s salePrice=%s maxPiece=%s currPiece=%s"
                     % (
                         ml,
                         eq["id"],
                         eq["type"]["color"],
                         eq["type"]["name"],
                         eq["type"]["salePrice"],
                         eq["maxPiece"],
                         eq["currPiece"],
                     )
                 )
                 price = int(eq["type"]["salePrice"]) * int(eq["currPiece"]) / int(eq["maxPiece"])
                 if int(eq["type"]["color"]) <= SellColor:
                     self.sell(eq["id"], price)
                 else:
                     if int(eq["type"]["color"]) > 5:
                         msg = "Got Equip %s %s/%s, TotalCost %d" % (
                             eq["type"]["name"],
                             eq["currPiece"],
                             eq["maxPiece"],
                             TotalCost,
                         )
                         logger.info(msg)
                         util.notify(msg)
                     else:
                         logger.info("I will keep it")
             except:
                 pass
             logger.info("finished %d time, TotalCost %d" % (cnt, TotalCost))
             cnt += 1
             time.sleep(2)
         except:
             logger.info(traceback.format_exc())
             time.sleep(10)
Пример #55
0
 def session_completed(self, ch, cmp):
   ch.session.sender.completed(cmp.commands)
   if cmp.timely_reply:
     ch.session_known_completed(cmp.commands)
   notify(ch.session.condition)
Пример #56
0
 def session_attached(self, ch, a):
   notify(ch.session.condition)
Пример #57
0
 def connection_close_ok(self, ch, close_ok):
   self.connection.opened = False
   self.connection.closed = True
   notify(self.connection.condition)
Пример #58
0
 def connection_open_ok(self, ch, open_ok):
   if _have_sasl:
     self.connection.security_layer_rx = self.sasl
   self.connection.opened = True
   notify(self.connection.condition)
Пример #59
0
 def connection_open(self, ch, open):
   self.connection.opened = True
   ch.connection_open_ok()
   notify(self.connection.condition)