示例#1
0
	def generateChunkName(self, commonId, firstHash, secondHash):
		loc4 = []
		for char in commonId:
			loc4.append(ord(char))
		loc6 = []
		loc6.extend(Common().createByteArray(secondHash[2:15]))
		loc6.extend(loc4)
		loc6.extend(Common().createByteArray(firstHash))
		newString = Common().ByteArrayToString(loc6)
		return base64.standard_b64encode(newString).replace("+","-").replace("/","_")[2:34]
示例#2
0
    def __ticking(self, book_result, has_task_today=True):
        self.__helper.clear_status()
        now = Common.get_today()
        curr_time = BookScheduler.__get_time_in_second(now.hour, now.minute,
                                                       now.second)

        next_ticking = BookScheduler.__get_time_in_second(
            Constants.TIME_UNIT_HOUR, 0) - curr_time

        if has_task_today:
            interval = self.__timings.interval
            min_value = interval

            for item in self.__timings.specials:
                shm = item.start.split(':')
                ehm = item.end.split(':')
                s_time = BookScheduler.__get_time_in_second(
                    int(shm[0]), int(shm[1]))
                e_time = BookScheduler.__get_time_in_second(
                    int(ehm[0]), int(ehm[1]))
                if s_time <= curr_time <= e_time:
                    if book_result:
                        interval = e_time - curr_time + 1
                    else:
                        interval = item.interval
                    break
                elif s_time > curr_time:
                    min_value = min(min_value, s_time - curr_time)

            next_ticking = min(min_value, interval, next_ticking)

        self.__logger.log('next ticking after %d seconds...' % next_ticking)
        self.__timer = threading.Timer(next_ticking, self.run)
        self.__timer.start()
        self.__logger.log('ticking down...')
	def generateKey(self, mediaid, size = 32):
		# Below: Do some black magic
		eq1 = int(int(Math.floor(Math.sqrt(6.9) * Math.pow(2, 25))) ^ mediaid)
		eq2 = int(Math.floor(Math.sqrt(6.9) * Math.pow(2, 25)))
		eq3 = (mediaid ^ eq2) ^ (mediaid ^ eq2) >> 3 ^ eq1 * 32
		# Below: Creates a 160-bit SHA1 hash 
		shaHash = sha.new(self.createString([20, 97, 1, 2]) + str(eq3)) 
		finalHash = shaHash.digest()
		hashArray = Common().createByteArray(finalHash)
		# Below: Pads the 160-bit hash to 256-bit using zeroes, incase a 256-bit key is requested
		padding = [0]*4*3
		hashArray.extend(padding)
		keyArray = [0]*size
		# Below: Create a string of the requested key size
		for i, item in enumerate(hashArray[:size]):
			keyArray[i] = item
		return Common().ByteArrayToString(keyArray)
示例#4
0
 def __add_signature_to_query_params(params):
     """
     :type params: dict
     """
     op = collections.OrderedDict(sorted(params.items(),
                                         key=lambda t: t[0]))
     queries = urllib.urlencode(op)
     params['signature'] = Common.md5(queries)
     return params
示例#5
0
 def get_reservation_list(self):
     url = UrlBuilder().schema(self.SCHEMA).host(self.HOST).segments(
         self.LIST_SEGMENTS).build()
     if url:
         params = self.__create_query_params_with_token()
         response = requests.get(url=url, params=params)
         encrypted = self.__get_data_from_response(response)
         if encrypted:
             json_string = Common.decrypt_content_by_aes(
                 encrypted, self.secret_key, self.aes_iv)
             return json.loads(json_string)
     return False
	def ooyalaDecrypt(self, data):
		
		print "Ooyala: --> Attempting to decrypt SMIL..."
		
		crypt = {'KEY':'4b3d32bed59fb8c54ab8a190d5d147f0e4f0cbe6804c8e0721175ab68b40cb01','IV':'00020406080a0c0ea0a2a4a6a8aaacae'}
		decodedByteArray = Base64Decoder().decode(data)
		data = Common().ByteArrayToString(decodedByteArray)
		aes_key = unhexlify(crypt['KEY'])
		iv_bytes = iv=unhexlify(crypt['IV'])
		d = iv_bytes + data
		cipher = AES_CBC(aes_key, padding=noPadding(), keySize=32)
		v = cipher.decrypt(d)
		length = struct.unpack('>I', v[:4])[0]
		compressed = v[4:length+4]
		decompressed = zlib.decompress(compressed)
		
		print "Ooyala: --> SMIL decrypted successfully."
		
		return decompressed[16:]
示例#7
0
    def send_mail(self, open_id, group_id, record_list):
        json_string = json.dumps(record_list)
        encrypted = Common.encrypt_content_by_aes(json_string, self.secret_key,
                                                  self.aes_iv)
        params = {
            'open_id': open_id,
            'group_id': group_id,
            'encrypted': encrypted
        }
        params = self.__create_query_params_with_token(params)
        params = self.__add_signature_to_query_params(params)

        url = UrlBuilder().schema(self.SCHEMA).host(self.HOST).segments(
            self.MAIL_SEGMENTS).build()
        if url:
            response = requests.post(url, data=params)
            if response.ok:
                json_obj = response.json()
                return json_obj and json_obj.get('error_code') == 0
        return False
示例#8
0
    def run(self):
        self.__logger.log('book scheduler ticking!')

        has_task = False
        tomorrow = Common.get_tomorrow()
        day_after_tomorrow = Common.get_day_after_tomorrow()
        more = Common.get_datetime_with_interval(3)
        all_dates = [
            Common.format_date(tomorrow, Common.DATETIME_PATTERN_YYYYMMDD),
            Common.format_date(day_after_tomorrow,
                               Common.DATETIME_PATTERN_YYYYMMDD),
            Common.format_date(more, Common.DATETIME_PATTERN_YYYYMMDD)
        ]
        try:
            date_strings = self.__helper.should_book(all_dates)
        except requests.exceptions.RequestException, _:
            has_task = True
            self.__logger.error(
                'cannot fetch records from 50.tsinghua with a network error, please check your network.'
            )
            date_strings = []
示例#9
0
	def transformWidth(self, width):
		widthStr = Common().int2base(width, 32)
		return widthStr[::-1]
示例#10
0
	def transformBitrate(self, bitrate):
		bitrateStr = Common().int2base(bitrate, 33)
		return bitrateStr
示例#11
0
	def transformChunkIndex(self, index):
		chunkIndex = Common().int2base(index, 35)
		if len(chunkIndex) > 1:
			return chunkIndex[::-1]
		else:
			return chunkIndex
示例#12
0
	def getChunkUrl(self, embedCode, version, index, start, br, width):
		local7 = self.getRevisionAndVersion(version)[1];
		local8 = self.generateCommondId(local7, self.transformChunkIndex(index), self.transformBitrate(br), self.transformWidth(width))
		local9 = Common().int2base(start,16);
		finalString = self.generateFinalString(embedCode, local8, self.generateFirstHash(local8), self.generateSecondHash(local9))
		return finalString
示例#13
0
    def notify_all(self, record_list, **kwargs):
        mail_sender = kwargs.get('mail_sender')
        mail_receivers = kwargs.get('mail_receivers')
        group_id = kwargs.get('group_id')
        open_id = kwargs.get('open_id')

        if self.remote:
            info_list = []
            for record in record_list:
                start_time = self.__convert_datetime_str_to_timestamp(
                    record.get('query_date'), record.get('start_time_str'))
                end_time = self.__convert_datetime_str_to_timestamp(
                    record.get('query_date'), record.get('end_time_str'))
                item = {
                    'stadium_name': record.get('stadium_name'),
                    'site_name': record.get('site_name'),
                    'start_time': start_time,
                    'end_time': end_time,
                    'thu_account': record.get('thu_account'),
                    'cost': record.get('cost'),
                }
                info_list.append(item)

            self.__notify_all_by_remote_sender(record_list=info_list,
                                               group_id=group_id,
                                               open_id=open_id)
        else:
            stadium_name = None
            site_name = ''
            cost = 0.0
            book_start = sys.maxint
            book_end = 0
            book_date = None
            thu_account = None

            for record in record_list:
                stadium_name = record.get(
                    'stadium_name') if stadium_name is None else stadium_name
                site_name += (' '
                              if site_name else '') + record.get('site_name')
                cost += record.get('cost')
                book_start = min(
                    book_start,
                    SectionIterator.decode(record.get('start_time_str')))
                book_end = max(
                    book_end,
                    SectionIterator.decode(record.get('end_time_str')))
                book_date = record.get(
                    'query_date') if book_date is None else book_date
                thu_account = record.get(
                    'thu_account') if thu_account is None else thu_account

            book_time = TimeInterval(
                SectionIterator.encode(book_start),
                SectionIterator.encode(book_end)).get_section_str()
            ymd = book_date.split('-')
            index = calendar.weekday(int(ymd[0]), int(ymd[1]), int(ymd[2]))
            weekday = Constants.WEEK_NAMES_EN[index]
            info = {
                'location':
                stadium_name + ' ' + site_name,
                'book_datetime':
                book_date + ' ' + weekday + ' ' + book_time,
                'owner':
                thu_account,
                'cost':
                cost,
                'curr_datetime':
                Common.format_datetime(datetime.datetime.now(),
                                       Common.DATETIME_PATTERN_YYYYMMDDHHMMSS)
            }
            self.__notify_all_by_local_sender(info=info,
                                              mail_sender=mail_sender,
                                              mail_receivers=mail_receivers)