Пример #1
0
def main():

    ########################################### ENCODING ##########################################################

    mode = int(input("please choose mode:\n1.Encode then Decode the same files\n2.Encode only\n3.Decode only\n"))
    block_size = int(input("Block Size = (4 is recommended) "))

    if mode != 3:
        imagePath = input("image name: (e.g. test.png) ")
        # name of the encoded file that will be created
        encodedFile = input("output encoded file name: (e.g. encoded.npy) ")
        # name of the file to save the probability 1D numpy array in it
        probabiltyFile = input("output probability file name: (e.g. probability.npy) ")
        float_type = "float type: (float64 is recommended) "
    if mode == 2:
        utility.encode(block_size, imagePath, encodedFile,probabiltyFile, float_type)
        return
    ########################################### DECODING ##########################################################
    # rows = 183
    # columns = 275
    columns = int(input("number of columns (WIDTH) of the original image: (e.g. 256) "))
    rows = int(input("number of rows (HEIGHT) of the original image: (e.g. 256) "))
    resultImage = input("output image name: (e.g. result.png) ")
    # name of the encoded file to be decoded
    if mode == 3:
        encodedFile = input("encoded file name: ( e.g. encoded.npy) ")
        # name of the file having the probabilty 1D numpy array
        probabiltyFile = input("probability file name: ( e.g. probability.npy) ")
    elif mode == 1:
        utility.encode(block_size, imagePath, encodedFile, probabiltyFile, float_type)
    utility.decode(block_size, rows, columns, probabiltyFile, encodedFile, resultImage)
Пример #2
0
def main():

    ############################### ENCODING ###############################
    mode = int(
        input(
            "please choose mode:\n1.Encode then Decode the same files\n2.Encode only\n3.Decode only\n"
        ))
    sliding_window_size = int(input("Sliding Window Size = (e.g. 13) "))
    look_ahead_size = int(input("Look Ahead Buffer Size = (e.g. 7) "))
    if mode != 3:
        imagePath = input("image name: (e.g. test.png) ")
        encodedFile = input("output encoded file name: (e.g. encoded.npy) ")

    if mode == 2:
        utility.encode(sliding_window_size, look_ahead_size, imagePath,
                       encodedFile)
        return
    ############################### DECODING ###############################

    columns = int(
        input("number of columns (WIDTH) of the original image: (e.g. 256) "))
    rows = int(
        input("number of rows (HEIGHT) of the original image: (e.g. 256) "))
    resultImage = input("output image name: (e.g. result.png) ")
    if mode == 3:
        encodedFile = input("encoded file name: ( e.g. encoded.npy) ")
    elif mode == 1:
        utility.encode(sliding_window_size, look_ahead_size, imagePath,
                       encodedFile)
    utility.decode(sliding_window_size, look_ahead_size, rows, columns,
                   resultImage, encodedFile)
Пример #3
0
 def load(self):
     self.db_open()
     for key in self.database.keys():
         value = utility.decode(self.database[key])
         key = utility.decode(key)
         self.dict.update({key: value})
     self.db_close()
Пример #4
0
def login():
    login_progress = xbmcgui.DialogProgress()
    login_progress.create('Netflix', utility.get_string(30200) + '...')
    utility.progress_window(login_progress, 25, utility.get_string(30201))
    connect.session.cookies.clear()
    content = utility.decode(connect.load_site(utility.main_url + 'Login'))
    if not 'Sorry, Netflix ' in content:
        match = re.compile('name="authURL" value="(.+?)"', re.DOTALL).findall(content)
        utility.log('Setting authorization url: ' + match[0])
        utility.set_setting('authorization_url', match[0])
        match = re.compile('locale: "(.+?)"', re.DOTALL).findall(content)
        utility.set_setting('language', match[0])
        post_data = {'authURL': utility.get_setting('authorization_url'), 'email': utility.get_setting('username'),
                     'password': utility.get_setting('password'), 'RememberMe': 'on'}
        utility.progress_window(login_progress, 50, utility.get_string(30202))
        content = utility.decode(connect.load_site(utility.main_url + 'Login?locale=' +
                                                   utility.get_setting('language'), post=post_data))
        if 'id="page-LOGIN"' in content:
            utility.notification(utility.get_string(30303))
            return False
        match = re.compile('"apiUrl":"(.+?)",').findall(content)
        utility.set_setting('api_url', match[0])
        post_data = utility.my_list % utility.get_setting('authorization_url')
        content = utility.decode(connect.load_site(utility.evaluator(), post=post_data))
        matches = json.loads(content)['value']
        match = matches['lolomos'].keys()
        utility.set_setting('root_list', match[0])
        match = matches['lists'].keys()
        utility.set_setting('my_list', match[1])
        match = matches['lists'][utility.get_setting('my_list')]['trackIds']['trackId']
        utility.set_setting('track_id', unicode(match))
        connect.save_session()
        utility.progress_window(login_progress, 75, utility.get_string(30203))
        if not (utility.get_setting('selected_profile') or (utility.get_setting('single_profile') == 'true')):
            profiles.choose()
        elif not (utility.get_setting('single_profile') == 'true') and (utility.get_setting('show_profiles') == 'true'):
            profiles.choose()
        elif not ((utility.get_setting('single_profile') and utility.get_setting('show_profiles')) == 'true'):
            profiles.load()
        #if not utility.get_setting('is_kid') == 'true':
            #match = re.compile('"version":{"app":"(.+?)"').findall(content)
            #utility.set_setting('lolomos', match[0])
            #3a5922fa-a4a9-41d8-a08c-9e84c2d32be4_ROOT
        if login_progress:
            if not utility.progress_window(login_progress, 100, utility.get_string(30204)):
                return False
            xbmc.sleep(500)
            login_progress.close()
        return True
    else:
        utility.notification(utility.get_string(30300))
        if login_progress:
            login_progress.close()
        return False
Пример #5
0
    def forward(self, loc_data, conf_data, priors):

        #         loc_data   = prediction[:,:,:4]
        #         conf_data  = prediction[:,:,4:]

        num_priors = priors.shape[0]
        batch_size = loc_data.shape[0]

        output = np.zeros(shape=(batch_size, self.num_classes, self.top_k, 5),
                          dtype=np.float32)

        conf_preds = conf_data.swapaxes(2, 1)

        for i in range(batch_size):
            decoded_boxes = decode(loc=loc_data[i],
                                   priors=priors,
                                   variances=self.variances)

            conf_scores = conf_preds[i].copy()

            for cl in range(1, self.num_classes):
                c_mask = np.greater(conf_scores[cl], self.conf_thresh)
                scores = conf_scores[cl][c_mask]
                scores = np.float32(scores)

                if scores.shape[0] == 0:
                    continue

                l_mask = c_mask.reshape(-1, 1).repeat(4, axis=-1)
                boxes = decoded_boxes[l_mask].reshape(-1, 4).astype(np.float32)
                #                 print(boxes.shape)

                boxes = torch.from_numpy(boxes).float()
                scores = torch.from_numpy(scores).float()

                ids, count = nms(boxes, scores, self.nms_thresh, self.top_k)

                #                ids, count = non_maximum_supression(boxes    = boxes,
                #                                                    scores   = scores,
                #                                                    overlap  = self.nms_thresh,
                #                                                    top_k    = self.top_k)
                ##
                #                 print(ids.shape)
                #                 print(count)
                ids = np.int32(ids)
                count = np.int32(count)

                scores = scores[ids[:count]]
                scores = np.expand_dims(scores, axis=1)

                output[i, cl, :count] = np.concatenate(
                    (scores, boxes[ids[:count]]), axis=-1)

#         flt = output.ascontiguousarray().reshape(batch_size, -1, 5)
#         idx  = np.argsort(flt[:,:,0], axis=-1)
#         rank = np.argsort(idx, axis=-1)

#         flt[rank < self.top_k].ex

        return output
Пример #6
0
def videos(url, video_type, run_as_widget=False):
    post_data = ''
    i = 1
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    if 'recently-added' in url:
        post_data = utility.recently_added % utility.get_setting(
            'authorization_url')
    elif 'genre' in url:
        post_data = utility.genre % (url.split('?')[1],
                                     utility.get_setting('authorization_url'))
    elif 'my-list' in url:
        post_data = utility.my_list % utility.get_setting('authorization_url')
    content = utility.decode(
        connect.load_site(utility.evaluator(), post=post_data))
    matches = json.loads(content)['value']['videos']
    for video_id in matches:
        if not run_as_widget:
            utility.progress_window(loading_progress, i * 100 / len(matches),
                                    matches[video_id]['title'])
        video(unicode(video_id), '', '', False, False, video_type, url)
        i += 1
    if utility.get_setting('force_view') == 'true' and not run_as_widget:
        xbmc.executebuiltin('Container.SetViewMode(' +
                            utility.get_setting('view_id_videos') + ')')
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #7
0
def genres(video_type):
    post_data = ''
    match = []
    xbmcplugin.addSortMethod(plugin_handle, xbmcplugin.SORT_METHOD_LABEL)
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    if video_type == 'tv':
        post_data = '{"paths":[["genres",83,"subgenres",{"from":0,"to":20},"summary"],["genres",83,"subgenres",' \
                    '"summary"]],"authURL":"%s"}' % utility.get_setting('authorization_url')
    elif video_type == 'movie':
        post_data = '{"paths":[["genreList",{"from":0,"to":24},["id","menuName"]],["genreList"]],"authURL":"%s"}' \
                    % utility.get_setting('authorization_url')
    else:
        pass
    content = utility.decode(connect.load_site(utility.evaluator(), post=post_data))
    matches = json.loads(content)['value']['genres']
    for item in matches:
        try:
            match.append((unicode(matches[item]['id']), matches[item]['menuName']))
        except Exception:
            try:
                match.append((unicode(matches[item]['summary']['id']), matches[item]['summary']['menuName']))
            except Exception:
                pass
    for genre_id, title in match:
        if video_type == 'tv':
            add.directory(title, utility.main_url + '/browse/genre/' + genre_id + '?bc=83', 'list_videos', '',
                          video_type)
        elif not genre_id == '83' and video_type == 'movie':
            add.directory(title, utility.main_url + '/browse/genre/' + genre_id, 'list_videos', '', video_type)
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #8
0
def genres(video_type):
    post_data = ''
    match = []
    xbmcplugin.addSortMethod(plugin_handle, xbmcplugin.SORT_METHOD_LABEL)
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    if video_type == 'tv':
        post_data = utility.series_genre % utility.get_setting(
            'authorization_url')
    elif video_type == 'movie':
        post_data = utility.movie_genre % utility.get_setting(
            'authorization_url')
    else:
        pass
    content = utility.decode(
        connect.load_site(utility.evaluator(), post=post_data))
    matches = json.loads(content)['value']['genres']
    for item in matches:
        try:
            match.append(
                (unicode(matches[item]['id']), matches[item]['menuName']))
        except Exception:
            try:
                match.append((unicode(matches[item]['summary']['id']),
                              matches[item]['summary']['menuName']))
            except Exception:
                pass
    for genre_id, title in match:
        if video_type == 'tv':
            add.directory(title, 'genre?' + genre_id, 'list_videos', '',
                          video_type)
        elif not genre_id == '83' and video_type == 'movie':
            add.directory(title, 'genre?' + genre_id, 'list_videos', '',
                          video_type)
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #9
0
def videos(url, video_type, run_as_widget=False):
    post_data = ''
    i = 1
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    if 'recently-added' in url:
        post_data = utility.recently_added % utility.get_setting('authorization_url')
    elif 'genre' in url:
        post_data = utility.genre % (url.split('?')[1], utility.get_setting('authorization_url'))
    elif 'my-list' in url:
        post_data = utility.my_list % utility.get_setting('authorization_url')
    content = utility.decode(connect.load_site(utility.evaluator(), post=post_data))
    matches = json.loads(content)['value']['videos']
    for video_id in matches:
        if not run_as_widget:
            utility.progress_window(loading_progress, i * 100 / len(matches), matches[video_id]['title'])
        video(unicode(video_id), '', '', False, False, video_type, url)
        i += 1
    if utility.get_setting('force_view') == 'true' and not run_as_widget:
        xbmc.executebuiltin('Container.SetViewMode(' + utility.get_setting('view_id_videos') + ')')
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #10
0
def search(search_string, video_type, run_as_widget=False):
    i = 1
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    post_data = '{"paths":[["search","%s",{"from":0,"to":48},["summary","title"]],["search","%s",["id","length",' \
                '"name","trackIds","requestId"]]],"authURL":"%s"}' % (search_string, search_string,
                                                                      utility.get_setting('authorization_url'))
    content = utility.decode(connect.load_site(utility.evaluator(), post=post_data))
    try:
        matches = json.loads(content)['value']['videos']
        for k in matches:
            if not run_as_widget:
                utility.progress_window(loading_progress, i * 100 / len(matches), '...')
            video(unicode(matches[k]['summary']['id']), '', '', False, False, video_type, '')
            i += 1
        if utility.get_setting('force_view') and not run_as_widget:
            xbmc.executebuiltin('Container.SetViewMode(' + utility.get_setting('view_id_videos') + ')')
        xbmcplugin.endOfDirectory(plugin_handle)
    except Exception:
        utility.notification(utility.get_string(30306))
        pass
Пример #11
0
def choose():
    profiles = []
    content = utility.decode(connect.load_site(utility.profile_url))
    match = json.loads(content)['profiles']
    for item in match:
        profile = {
            'name': item['firstName'],
            'token': item['guid'],
            'is_kid': item['experience'] == 'jfk'
        }
        profiles.append(profile)
    if len(match) > 0:
        dialog = xbmcgui.Dialog()
        nr = dialog.select(utility.get_string(30103),
                           [profile['name'] for profile in profiles])
        if nr >= 0:
            selected_profile = profiles[nr]
        else:
            selected_profile = profiles[0]
        connect.load_site(utility.profile_switch_url +
                          selected_profile['token'])
        utility.set_setting('selected_profile', selected_profile['token'])
        utility.set_setting('is_kid',
                            'true' if selected_profile['is_kid'] else 'false')
        utility.set_setting('profile_name', selected_profile['name'])
        connect.save_session()
    else:
        utility.log('Choose profile: no profiles were found!',
                    loglevel=xbmc.LOGERROR)
Пример #12
0
def search(search_string, video_type, run_as_widget=False):
    i = 1
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    post_data = '{"paths":[["search","%s",{"from":0,"to":48},["summary","title"]],["search","%s",["id","length",' \
                '"name","trackIds","requestId"]]],"authURL":"%s"}' % (search_string, search_string,
                                                                      utility.get_setting('authorization_url'))
    content = utility.decode(
        connect.load_site(utility.evaluator_url %
                          (utility.get_setting('netflix_application'),
                           utility.get_setting('netflix_version')),
                          post=post_data))
    try:
        matches = json.loads(content)['value']['videos']
        for k in matches:
            if not run_as_widget:
                utility.progress_window(loading_progress,
                                        i * 100 / len(matches), '...')
            video(unicode(matches[k]['summary']['id']), '', '', False, False,
                  video_type, '')
            i += 1
        if utility.get_setting('force_view') and not run_as_widget:
            xbmc.executebuiltin('Container.SetViewMode(' +
                                utility.get_setting('view_id_videos') + ')')
        xbmcplugin.endOfDirectory(plugin_handle)
    except Exception:
        utility.notification(utility.get_string(30306))
        pass
Пример #13
0
def choose():
    profiles = []
    content = utility.decode(connect.load_site(utility.profile_url))
    match = re.compile(
        '"experience":"(.+?)".+?guid":"(.+?)".+?profileName":"(.+?)"',
        re.DOTALL).findall(content)
    for is_kid, token, name in match:
        profile = {
            'name': utility.unescape(name),
            'token': token,
            'is_kid': is_kid == 'jfk'
        }
        profiles.append(profile)
    if len(match) > 0:
        dialog = xbmcgui.Dialog()
        nr = dialog.select(utility.get_string(30103),
                           [profile['name'] for profile in profiles])
        if nr >= 0:
            selected_profile = profiles[nr]
        else:
            selected_profile = profiles[0]
        connect.load_site(utility.profile_switch_url +
                          selected_profile['token'])
        utility.set_setting('selected_profile', selected_profile['token'])
        utility.set_setting('is_kid',
                            'true' if selected_profile['is_kid'] else 'false')
        utility.set_setting('profile_name', selected_profile['name'])
        connect.save_session()
        get_my_list_change_authorisation()
    else:
        utility.log('Choose profile: no profiles were found!',
                    loglevel=xbmc.LOGERROR)
Пример #14
0
def genres(video_type):
    post_data = ''
    match = []
    xbmcplugin.addSortMethod(plugin_handle, xbmcplugin.SORT_METHOD_LABEL)
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    if video_type == 'tv':
        post_data = utility.series_genre % utility.get_setting('authorization_url')
    elif video_type == 'movie':
        post_data = utility.movie_genre % utility.get_setting('authorization_url')
    else:
        pass
    content = utility.decode(connect.load_site(utility.evaluator(), post=post_data))
    matches = json.loads(content)['value']['genres']
    for item in matches:
        try:
            match.append((unicode(matches[item]['id']), matches[item]['menuName']))
        except Exception:
            try:
                match.append((unicode(matches[item]['summary']['id']), matches[item]['summary']['menuName']))
            except Exception:
                pass
    for genre_id, title in match:
        if video_type == 'tv':
            add.directory(title, 'genre?' + genre_id, 'list_videos', '', video_type)
        elif not genre_id == '83' and video_type == 'movie':
            add.directory(title, 'genre?' + genre_id, 'list_videos', '', video_type)
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #15
0
def mqtt_callback(topic, msg):
    global SubscribeDict

    print("subscribe_callback:", SubscribeDict)

    topic = utility.decode(topic)
    msg = utility.decode(msg)
    if (topic == "password"):
        SubscribeDict["password"] = msg
        database.set("gate_password", msg)
        database.commit()
    if (topic == "doors_that_open"):
        SubscribeDict["doors_that_open"] = ujson.loads(msg)

    print('---------')
    print("topic:", topic)
    print("msg:", msg)
Пример #16
0
def get_my_list_change_authorisation():
    """
    Looks like this function was intended for the owners list.
    There is now xsrf element in the site anymore
    this have to be changed or obsulate
    """
    content = utility.decode(connect.load_site(utility.main_url + "/WiHome"))
    match = re.compile('"xsrf":"(.+?)"', re.DOTALL).findall(content)
    if match:
        utility.set_setting("my_list_authorization", match[0])
Пример #17
0
def get_my_list_change_authorisation():
    """
    Looks like this function was intended for the owners list.
    There is now xsrf element in the site anymore
    this have to be changed or obsulate
    """
    content = utility.decode(connect.load_site(utility.main_url + '/WiHome'))
    match = re.compile('"xsrf":"(.+?)"', re.DOTALL).findall(content)
    if match:
        utility.set_setting('my_list_authorization', match[0])
Пример #18
0
def main():

    ########################################### ENCODING ##########################################################
    block_size = 4
    imagePath = "test2.png"
    # name of the encoded file that will be created
    encodedFile = "encoded.npy"
    # name of the file to save the probabilty 1D numpy array in it
    probabiltyFile = "probability.npy"
    float_type = 'float64' #you can choose numpy float types as float64(default and recommended), float32, float16
    utility.encode(block_size, imagePath, encodedFile,probabiltyFile, float_type)

    ########################################### DECODING ##########################################################
    columns = 256 #Width
    rows = 256 #Hieght
    resultImage = "result2.png"
    # name of the encoded file to be decoded
    encodedFile = "encoded.npy"
    # name of the file having the probabilty 1D numpy array
    probabiltyFile = "probability.npy"
    utility.decode(block_size, rows, columns, probabiltyFile, encodedFile, resultImage)
Пример #19
0
def add(video_id):
    post_data = utility.my_list % utility.get_setting('authorization_url')
    content = utility.decode(
        connect.load_site(utility.evaluator(), post=post_data))
    match = json.loads(content)['value']['videos']
    headers = {
        'Access-Control-Request-Headers': 'content-type, accept',
        'Access-Control-Request-Method': 'POST',
        'Origin': 'http://www.netflix.com'
    }
    content = utility.decode(
        connect.load_site(utility.evaluator() + '&method=call',
                          options=True,
                          headers=headers))
    print content
    cookies = {
        'lhpuuidh-browse-' + utility.get_setting('selected_profile'):
        urllib.quote_plus(
            utility.get_setting('language').split('-')[1] + ':' +
            utility.get_setting('language').upper() + ':' +
            utility.get_setting('root_list')),
        'SecureNetflixId':
        'v%3D2%26mac%3DAQEAEQABABRkPnYy2LvtMo02JH3beZhI4vKJAM2mLeM.%26dt%3D1449696369549'
    }
    post_data = utility.add_list % (
        utility.get_setting('root_list'), utility.get_setting('my_list'),
        video_id, utility.get_setting('track_id'), unicode(
            len(match)), utility.get_setting('authorization_url'))
    headers = {
        'Referer': 'http://www.netflix.com/browse',
        'Origin': 'http://www.netflix.com'
    }
    print post_data
    content = utility.decode(
        connect.load_site(utility.evaluator() + '&method=call',
                          cookies=cookies,
                          headers=headers,
                          post=post_data))
    print content
Пример #20
0
def video_info(video_id):
    content = ''
    cache_file = xbmc.translatePath(utility.cache_dir() + video_id + '.cache')
    if xbmcvfs.exists(cache_file):
        file_handler = xbmcvfs.File(cache_file, 'rb')
        content = file_handler.read()
        file_handler.close()
    if not content:
        content = connect.load_site(utility.main_url + '/JSON/BOB?movieid=' + video_id)
        file_handler = xbmcvfs.File(cache_file, 'wb')
        file_handler.write(content)
        file_handler.close()
    return utility.clean_content(utility.decode(content))
Пример #21
0
def view_activity(video_type, run_as_widget=False):
    count = 0
    video_ids = []
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    content = utility.decode(
        connect.load_site(utility.main_url + '/WiViewingActivity'))
    series_id = re.compile('(<li .*?data-series=.*?</li>)',
                           re.DOTALL).findall(content)
    for i in range(1, len(series_id), 1):
        entry = series_id[i]
        if not run_as_widget:
            utility.progress_window(loading_progress,
                                    (count + 1) * 100 / len(series_id), '...')
        match_id = re.compile('data-movieid="(.*?)"', re.DOTALL).findall(entry)
        if match_id:
            video_id = match_id[0]
        match = re.compile('class="col date nowrap">(.+?)<',
                           re.DOTALL).findall(entry)
        date = match[0]
        match_title1 = re.compile('class="seriestitle">(.+?)</a>',
                                  re.DOTALL).findall(entry)
        match_title2 = re.compile('class="col title">.+?>(.+?)<',
                                  re.DOTALL).findall(entry)
        if match_title1:
            title = utility.unescape(match_title1[0]).replace('</span>', '')
        elif match_title2:
            title = match_title2[0]
        else:
            title = ''
        title = date + ' - ' + title
        if video_id not in video_ids:
            video_ids.append(video_id)
            # due to limitations in the netflix api, there is no way to get the series_id of an
            # episode, so the 4 param is set to True to treat tv episodes the same as movies.
            added = video(video_id, title, '', True, False, video_type, '')
            if added:
                count += 1
            if count == 20:
                break
    if utility.get_setting('force_view') and not run_as_widget:
        xbmc.executebuiltin('Container.SetViewMode(' +
                            utility.get_setting('view_id_activity') + ')')
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #22
0
def video_info(video_id):
    content = ''
    cache_file = xbmc.translatePath(utility.cache_dir() + video_id + '.cache')
    if xbmcvfs.exists(cache_file):
        file_handler = xbmcvfs.File(cache_file, 'rb')
        content = file_handler.read()
        file_handler.close()
    if not content:
        content = connect.load_site(utility.main_url + '/JSON/BOB?movieid=' +
                                    video_id)
        file_handler = xbmcvfs.File(cache_file, 'wb')
        file_handler.write(content)
        file_handler.close()
    return utility.clean_content(utility.decode(content))
Пример #23
0
def add(video_id):
    post_data = utility.my_list % utility.get_setting('authorization_url')
    content = utility.decode(connect.load_site(utility.evaluator(), post=post_data))
    match = json.loads(content)['value']['videos']
    headers = {'Access-Control-Request-Headers': 'content-type, accept','Access-Control-Request-Method': 'POST',
               'Origin': 'http://www.netflix.com'}
    content = utility.decode(connect.load_site(utility.evaluator()+'&method=call', options=True, headers=headers))
    print content
    cookies = {'lhpuuidh-browse-' + utility.get_setting('selected_profile'): urllib.quote_plus(utility.get_setting('language').split('-')[1] + ':' + utility.get_setting('language').upper() + ':' + utility.get_setting('root_list')), 'SecureNetflixId': 'v%3D2%26mac%3DAQEAEQABABRkPnYy2LvtMo02JH3beZhI4vKJAM2mLeM.%26dt%3D1449696369549'}
    post_data = utility.add_list % (utility.get_setting('root_list'),
                                    utility.get_setting('my_list'),
                                    video_id,
                                    utility.get_setting('track_id'),
                                    unicode(len(match)),
                                    utility.get_setting('authorization_url'))
    headers = {'Referer': 'http://www.netflix.com/browse',
               'Origin': 'http://www.netflix.com'}
    print post_data
    content = utility.decode(connect.load_site(utility.evaluator()+'&method=call',
                                               cookies=cookies,
                                               headers=headers,
                                               post=post_data))
    print content
Пример #24
0
def series_info(series_id):
    content = ''
    cache_file = xbmc.translatePath(utility.cache_dir() + series_id + '_episodes.cache')
    if xbmcvfs.exists(cache_file) and (time.time() - xbmcvfs.Stat(cache_file).st_mtime() < 60 * 5):
        file_handler = xbmcvfs.File(cache_file, 'rb')
        content = file_handler.read()
        file_handler.close()
    if not content:
        url = utility.series_url % (utility.get_setting('api_url'), series_id)
        content = connect.load_site(url)
        file_handler = xbmcvfs.File(cache_file, 'wb')
        file_handler.write(content)
        file_handler.close()
    return utility.decode(content)
Пример #25
0
def main():

    ############################### ENCODING ###############################

    sliding_window_size = 12
    look_ahead_size = 7
    imagePath = "test2.png"
    encodedFile = "encoded.npy"

    utility.encode(sliding_window_size, look_ahead_size, imagePath,
                   encodedFile)

    ############################### DECODING ###############################

    sliding_window_size = 12
    look_ahead_size = 7
    rows = 256  #height
    columns = 256  #width
    resultImage = "result2.png"
    encodedFile = "encoded.npy"

    utility.decode(sliding_window_size, look_ahead_size, rows, columns,
                   resultImage, encodedFile)
Пример #26
0
def video_info(video_id):
    content = ''
    cache_file = xbmc.translatePath(utility.cache_dir() + video_id + '.cache')
    if xbmcvfs.exists(cache_file):
        file_handler = xbmcvfs.File(cache_file, 'rb')
        content = file_handler.read()
        file_handler.close()
    if not content:
        post_data = utility.video_info % (video_id, video_id, video_id, video_id,
                                         utility.get_setting('authorization_url'))
        content = connect.load_site(utility.evaluator(), post=post_data)
        file_handler = xbmcvfs.File(cache_file, 'wb')
        file_handler.write(content)
        file_handler.close()
    return utility.decode(content)
Пример #27
0
def view_activity(video_type, run_as_widget=False):
    count = 0
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    content = utility.decode(
        connect.load_site(utility.activity_url %
                          (utility.get_setting('api_url'),
                           utility.get_setting('authorization_url'))))
    matches = json.loads(content)['viewedItems']
    try:
        for item in matches:
            series_id = 0
            is_episode = False
            video_id = unicode(item['movieID'])
            date = item['dateStr']
            try:
                series_id = item['series']
                series_title = item['seriesTitle']
                title = item['title']
                title = series_title + ' ' + title
            except Exception:
                title = item['title']
            if not run_as_widget:
                utility.progress_window(loading_progress,
                                        (count + 1) * 500 / len(matches),
                                        title)
            title = date + ' - ' + title
            if series_id > 0:
                is_episode = True
            added = video(video_id, title, '', is_episode, False, video_type,
                          '')
            if added:
                count += 1
            if count == 20:
                break
    except Exception:
        utility.notification(utility.get_string(30306))
        pass
    if utility.get_setting('force_view') and not run_as_widget:
        xbmc.executebuiltin('Container.SetViewMode(' +
                            utility.get_setting('view_id_activity') + ')')
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #28
0
def video_info(video_id):
    content = ''
    cache_file = xbmc.translatePath(utility.cache_dir() + video_id + '.cache')
    if xbmcvfs.exists(cache_file):
        file_handler = xbmcvfs.File(cache_file, 'rb')
        content = file_handler.read()
        file_handler.close()
    if not content:
        postdata = '{"paths":[["videos",{media_id},["bookmarkPosition","details","episodeCount","maturity","queue",' \
                   '"releaseYear","requestId","runtime","seasonCount","summary","title","userRating","watched"]],' \
                   '["videos",{media_id},"boxarts",["_342x192","_665x375"],"jpg"]],"authURL":"{authorization_url}"}' \
            .replace('{media_id}', video_id).replace('{authorization_url}', utility.get_setting('authorization_url'))
        content = connect.load_site(utility.evaluator(), post=postdata)
        file_handler = xbmcvfs.File(cache_file, 'wb')
        file_handler.write(content)
        file_handler.close()
    return utility.decode(content)
Пример #29
0
def series_info(series_id):
    content = ''
    cache_file = xbmc.translatePath(utility.cache_dir() + series_id +
                                    '_episodes.cache')
    if xbmcvfs.exists(cache_file) and (
            time.time() - xbmcvfs.Stat(cache_file).st_mtime() < 60 * 5):
        file_handler = xbmcvfs.File(cache_file, 'rb')
        content = file_handler.read()
        file_handler.close()
    if not content:
        url = utility.series_url % (utility.get_setting('netflix_application'),
                                    utility.get_setting('netflix_version'),
                                    series_id)
        content = connect.load_site(url)
        file_handler = xbmcvfs.File(cache_file, 'wb')
        file_handler.write(content)
        file_handler.close()
    return utility.decode(content)
Пример #30
0
def view_activity(video_type, run_as_widget=False):
    count = 0
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    content = utility.decode(connect.load_site(utility.activity_url % (
    utility.get_setting('netflix_application'), utility.get_setting('netflix_id'),
    utility.get_setting('authorization_url'))))
    matches = json.loads(content)['viewedItems']
    try:
        for item in matches:
            series_id = 0
            is_episode = False
            video_id = unicode(item['movieID'])
            date = item['dateStr']
            try:
                series_id = item['series']
                series_title = item['seriesTitle']
                title = item['title']
                title = series_title + ' ' + title
            except Exception:
                title = item['title']
            if not run_as_widget:
                utility.progress_window(loading_progress, (count + 1) * 500 / len(matches), title)
            title = date + ' - ' + title
            if series_id > 0:
                is_episode = True
            added = video(video_id, title, '', is_episode, False, video_type, '')
            if added:
                count += 1
            if count == 20:
                break
    except Exception:
        utility.notification(utility.get_string(30306))
        pass
    if utility.get_setting('force_view') and not run_as_widget:
        xbmc.executebuiltin('Container.SetViewMode(' + utility.get_setting('view_id_activity') + ')')
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #31
0
def view_activity(video_type, run_as_widget=False):
    count = 0
    video_ids = []
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    content = utility.decode(connect.load_site(utility.main_url + '/WiViewingActivity'))
    series_id = re.compile('(<li .*?data-series=.*?</li>)', re.DOTALL).findall(content)
    for i in range(1, len(series_id), 1):
        entry = series_id[i]
        if not run_as_widget:
            utility.progress_window(loading_progress, (count + 1) * 100 / len(series_id), '...')
        match_id = re.compile('data-movieid="(.*?)"', re.DOTALL).findall(entry)
        if match_id:
            video_id = match_id[0]
        match = re.compile('class="col date nowrap">(.+?)<', re.DOTALL).findall(entry)
        date = match[0]
        match_title1 = re.compile('class="seriestitle">(.+?)</a>', re.DOTALL).findall(entry)
        match_title2 = re.compile('class="col title">.+?>(.+?)<', re.DOTALL).findall(entry)
        if match_title1:
            title = utility.unescape(match_title1[0]).replace('</span>', '')
        elif match_title2:
            title = match_title2[0]
        else:
            title = ''
        title = date + ' - ' + title
        if video_id not in video_ids:
            video_ids.append(video_id)
            # due to limitations in the netflix api, there is no way to get the series_id of an
            # episode, so the 4 param is set to True to treat tv episodes the same as movies.
            added = video(video_id, title, '', True, False, video_type, '')
            if added:
                count += 1
            if count == 20:
                break
    if utility.get_setting('force_view') and not run_as_widget:
        xbmc.executebuiltin('Container.SetViewMode(' + utility.get_setting('view_id_activity') + ')')
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #32
0
 def send_text(self, phone, text):
     condition = text.replace('\n', '').replace(' ', '')
     try:
         if condition != '':
             self.driver.get("https://web.whatsapp.com/send?phone=" +
                             format(phone))
             try:
                 self.driver.switch_to_alert().accept()
             except:
                 pass
             texts = text.split('\n')
             for _text in texts:
                 __text = utility.decode(_text)
                 self.element_presence(
                     By.XPATH,
                     '/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2][@data-tab="1"]',
                     30)
                 self.driver.find_element(
                     By.XPATH,
                     '/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2][@data-tab="1"]'
                 ).send_keys(__text)
                 self.driver.find_element(
                     By.XPATH,
                     '/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2][@data-tab="1"]'
                 ).send_keys(Keys.SHIFT + Keys.ENTER)
             self.element_presence(
                 By.XPATH,
                 '/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2][@data-tab="1"]',
                 30)
             self.driver.find_element(
                 By.XPATH,
                 '/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2][@data-tab="1"]'
             ).send_keys(Keys.ENTER)
             time.sleep(1)
             self.element_absence(By.XPATH, '//span[@data-icon="msg-time"]',
                                  100)
             return True
         else:
             return False
     except Exception as e:
         return e
Пример #33
0
def choose():
    profiles = []
    content = utility.decode(connect.load_site(utility.profile_url))
    match = json.loads(content)['profiles']
    for item in match:
        profile = {'name': item['firstName'], 'token': item['guid'], 'is_kid': item['experience'] == 'jfk'}
        profiles.append(profile)
    if len(match) > 0:
        dialog = xbmcgui.Dialog()
        nr = dialog.select(utility.get_string(30103), [profile['name'] for profile in profiles])
        if nr >= 0:
            selected_profile = profiles[nr]
        else:
            selected_profile = profiles[0]
        connect.load_site(utility.profile_switch_url + selected_profile['token'])
        utility.set_setting('selected_profile', selected_profile['token'])
        utility.set_setting('is_kid', 'true' if selected_profile['is_kid'] else 'false')
        utility.set_setting('profile_name', selected_profile['name'])
        connect.save_session()
    else:
        utility.log('Choose profile: no profiles were found!', loglevel=xbmc.LOGERROR)
Пример #34
0
def genres(video_type):
    post_data = ''
    match = []
    xbmcplugin.addSortMethod(plugin_handle, xbmcplugin.SORT_METHOD_LABEL)
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    if video_type == 'tv':
        post_data = '{"paths":[["genres",83,"subgenres",{"from":0,"to":20},"summary"],["genres",83,"subgenres",' \
                    '"summary"]],"authURL":"%s"}' % utility.get_setting('authorization_url')
    elif video_type == 'movie':
        post_data = '{"paths":[["genreList",{"from":0,"to":24},["id","menuName"]],["genreList"]],"authURL":"%s"}' \
                    % utility.get_setting('authorization_url')
    else:
        pass
    content = utility.decode(
        connect.load_site(utility.evaluator_url %
                          (utility.get_setting('netflix_application'),
                           utility.get_setting('netflix_version')),
                          post=post_data))
    matches = json.loads(content)['value']['genres']
    for k in matches:
        try:
            match.append((unicode(matches[k]['id']), matches[k]['menuName']))
        except Exception:
            try:
                match.append((unicode(matches[k]['summary']['id']),
                              matches[k]['summary']['menuName']))
            except Exception:
                pass
    for genre_id, title in match:
        if video_type == 'tv':
            add.directory(
                title,
                utility.main_url + '/browse/genre/' + genre_id + '?bc=83',
                'list_videos', '', video_type)
        elif not genre_id == '83' and video_type == 'movie':
            add.directory(title,
                          utility.main_url + '/browse/genre/' + genre_id,
                          'list_videos', '', video_type)
    xbmcplugin.endOfDirectory(plugin_handle)
Пример #35
0
def choose():
    profiles = []
    content = utility.decode(connect.load_site(utility.profile_url))
    match = re.compile('"experience":"(.+?)".+?guid":"(.+?)".+?profileName":"(.+?)"', re.DOTALL).findall(content)
    for is_kid, token, name in match:
        profile = {"name": utility.unescape(name), "token": token, "is_kid": is_kid == "jfk"}
        profiles.append(profile)
    if len(match) > 0:
        dialog = xbmcgui.Dialog()
        nr = dialog.select(utility.get_string(30103), [profile["name"] for profile in profiles])
        if nr >= 0:
            selected_profile = profiles[nr]
        else:
            selected_profile = profiles[0]
        connect.load_site(utility.profile_switch_url + selected_profile["token"])
        utility.set_setting("selected_profile", selected_profile["token"])
        utility.set_setting("is_kid", "true" if selected_profile["is_kid"] else "false")
        utility.set_setting("profile_name", selected_profile["name"])
        connect.save_session()
        get_my_list_change_authorisation()
    else:
        utility.log("Choose profile: no profiles were found!", loglevel=xbmc.LOGERROR)
Пример #36
0
def choose():
    profiles = []
    content = utility.decode(connect.load_site(utility.profile_url))
    match = re.compile('"experience":"(.+?)".+?guid":"(.+?)".+?firstName":"(.+?)"', re.DOTALL).findall(content)
    for is_kid, token, name in match:
        profile = {'name': utility.unescape(name), 'token': token, 'is_kid': is_kid == 'jfk'}
        profiles.append(profile)
    if len(match) > 0:
        dialog = xbmcgui.Dialog()
        nr = dialog.select(utility.get_string(30103), [profile['name'] for profile in profiles])
        if nr >= 0:
            selected_profile = profiles[nr]
        else:
            selected_profile = profiles[0]
        connect.load_site(utility.profile_switch_url + selected_profile['token'])
        utility.set_setting('selected_profile', selected_profile['token'])
        utility.set_setting('is_kid', 'true' if selected_profile['is_kid'] else 'false')
        utility.set_setting('profile_name', selected_profile['name'])
        connect.save_session()
        get_my_list_change_authorisation()
    else:
        utility.log('Choose profile: no profiles were found!', loglevel=xbmc.LOGERROR)
Пример #37
0
def login():
    login_progress = xbmcgui.DialogProgress()
    login_progress.create('Netflix', utility.get_string(30200) + '...')
    utility.progress_window(login_progress, 25, utility.get_string(30201))
    connect.session.cookies.clear()
    content = utility.decode(connect.load_site(utility.main_url + '/Login'))
    match = re.compile('"locale":"(.+?)"',
                       re.DOTALL | re.IGNORECASE).findall(content)
    if match and not utility.get_setting('language'):
        utility.log('Setting language: ' + match[0])
        utility.set_setting('language', match[0])
    if not 'Sorry, Netflix ' in content:
        match = re.compile('id="signout".+?authURL=(.+?)"',
                           re.DOTALL).findall(content)
        if match:
            utility.log('Setting authorization url: ' + match[0])
            utility.set_setting('authorization_url', match[0])
        if 'id="page-LOGIN"' in content:
            match = re.compile('name="authURL" value="(.+?)"',
                               re.DOTALL).findall(content)
            utility.log('Setting authorization url: ' + match[0])
            utility.set_setting('authorization_url', match[0])
            post_data = {
                'authURL': match[0],
                'email': utility.get_setting('username'),
                'password': utility.get_setting('password'),
                'RememberMe': 'on'
            }
            utility.progress_window(login_progress, 50,
                                    utility.get_string(30202))
            content = utility.decode(
                connect.load_site(utility.main_url + '/Login?locale=' +
                                  utility.get_setting('language'),
                                  post=post_data))
            if 'id="page-LOGIN"' in content:
                utility.notification(utility.get_string(30303))
                return False
            match = re.compile('"locale":"(.+?)"',
                               re.DOTALL | re.IGNORECASE).findall(content)
            if match and not utility.get_setting('language'):
                utility.log('Setting language: ' + match[0])
                utility.set_setting('language', match[0])
            match = re.compile('"country":"(.+?)"',
                               re.DOTALL | re.IGNORECASE).findall(content)
            if match:
                utility.log('Setting country code: ' + match[0])
                utility.set_setting('country_code', match[0])
            connect.save_session()
            utility.progress_window(login_progress, 75,
                                    utility.get_string(30203))
        if not (utility.get_setting('selected_profile') or
                (utility.get_setting('single_profile') == 'true')):
            profiles.choose()
        elif not (utility.get_setting('single_profile') == 'true') and (
                utility.get_setting('show_profiles') == 'true'):
            profiles.choose()
        elif not ((utility.get_setting('single_profile') == 'true') and
                  (utility.get_setting('show_profiles') == 'true')):
            profiles.load()
        else:
            profiles.get_my_list_change_authorisation()
        if not utility.get_setting('is_kid') == 'true':
            content = utility.decode(
                connect.load_site(utility.main_url + '/browse'))
            match = re.compile('"version":{"app":"(.+?)"').findall(content)
            netflix_application, netflix_version = match[0].split('-')
            utility.set_setting('netflix_application', netflix_application)
            utility.set_setting('netflix_version', netflix_version)
        if login_progress:
            if not utility.progress_window(login_progress, 100,
                                           utility.get_string(30204)):
                return False
            xbmc.sleep(500)
            login_progress.close()
        return True
    else:
        utility.notification(utility.get_string(30300))
        if login_progress:
            login_progress.close()
        return False
Пример #38
0
channel = BEC(alpha=0.7)
n = int((math.pow(2, 11) * 0.1))
x = np.random.binomial(1, 0.5, n)

I = channel.polarize(int(math.pow(2, 11)), 0.9999888)
l = range(int(math.pow(2, 11)))
Ineg = [-I[i] for i in range(len(I))]
polarized = [True for i in range(len(I))]
I1, l1 = zip(*sorted(zip(Ineg, l)))
inp = [0 for i in range(int(math.pow(2, 11)))]

for i in range(len(x)):
    inp[l1[i]] = x[i]
    polarized[i] = False

inp = np.random.binomial(1, 0.5, int(math.pow(2, 11)))

encoded = utility.encode(inp)

y = channel.passInput(encoded)

decoded = utility.decode(y)

c = 0
for i in range(len(inp)):
    if (not polarized[i]):
        if (decoded[i] == inp[i]):
            c += 1

print n, c
Пример #39
0
def login():
    login_progress = xbmcgui.DialogProgress()
    login_progress.create('Netflix', utility.get_string(30200) + '...')
    utility.progress_window(login_progress, 25, utility.get_string(30201))
    connect.session.cookies.clear()
    content = utility.decode(connect.load_site(utility.main_url + 'Login'))
    if not 'Sorry, Netflix ' in content:
        match = re.compile('name="authURL" value="(.+?)"',
                           re.DOTALL).findall(content)
        utility.log('Setting authorization url: ' + match[0])
        utility.set_setting('authorization_url', match[0])
        match = re.compile('locale: "(.+?)"', re.DOTALL).findall(content)
        utility.set_setting('language', match[0])
        post_data = {
            'authURL': utility.get_setting('authorization_url'),
            'email': utility.get_setting('username'),
            'password': utility.get_setting('password'),
            'RememberMe': 'on'
        }
        utility.progress_window(login_progress, 50, utility.get_string(30202))
        content = utility.decode(
            connect.load_site(utility.main_url + 'Login?locale=' +
                              utility.get_setting('language'),
                              post=post_data))
        if 'id="page-LOGIN"' in content:
            utility.notification(utility.get_string(30303))
            return False
        match = re.compile('"apiUrl":"(.+?)",').findall(content)
        utility.set_setting('api_url', match[0])
        post_data = utility.my_list % utility.get_setting('authorization_url')
        content = utility.decode(
            connect.load_site(utility.evaluator(), post=post_data))
        matches = json.loads(content)['value']
        match = matches['lolomos'].keys()
        utility.set_setting('root_list', match[0])
        match = matches['lists'].keys()
        utility.set_setting('my_list', match[1])
        match = matches['lists'][utility.get_setting(
            'my_list')]['trackIds']['trackId']
        utility.set_setting('track_id', unicode(match))
        connect.save_session()
        utility.progress_window(login_progress, 75, utility.get_string(30203))
        if not (utility.get_setting('selected_profile') or
                (utility.get_setting('single_profile') == 'true')):
            profiles.choose()
        elif not (utility.get_setting('single_profile') == 'true') and (
                utility.get_setting('show_profiles') == 'true'):
            profiles.choose()
        elif not ((utility.get_setting('single_profile')
                   and utility.get_setting('show_profiles')) == 'true'):
            profiles.load()
        #if not utility.get_setting('is_kid') == 'true':
        #match = re.compile('"version":{"app":"(.+?)"').findall(content)
        #utility.set_setting('lolomos', match[0])
        #3a5922fa-a4a9-41d8-a08c-9e84c2d32be4_ROOT
        if login_progress:
            if not utility.progress_window(login_progress, 100,
                                           utility.get_string(30204)):
                return False
            xbmc.sleep(500)
            login_progress.close()
        return True
    else:
        utility.notification(utility.get_string(30300))
        if login_progress:
            login_progress.close()
        return False
Пример #40
0
def raw(messages, names):
    fromDay = date.fromtimestamp(messages[0]["timestamp_ms"] // 1000)
    toDay = date.fromtimestamp(messages[-1]["timestamp_ms"] // 1000)
    people = {"total": 0}
    photos = {"total": 0}
    gifs = {"total": 0}
    stickers = {"total": 0}
    videos = {"total": 0}
    audios = {"total": 0}
    files = {"total": 0}
    reactions = {"total": 0, "types": {}, "gave": {}, "got": {}}
    emojis = {"total": 0, "types": {}, "sent": {}}
    days = daysList(messages)
    months = {}
    years = {}
    weekdays = {}
    hours = hoursList()

    for n in names:
        reactions["gave"][n] = {"total": 0}
        reactions["got"][n] = {"total": 0}
        emojis["sent"][n] = {"total": 0}

    for m in messages:
        name = m["sender_name"]
        day = date.fromtimestamp(m["timestamp_ms"] // 1000)
        days[str(day)] += 1
        month = f"{day.month}/{day.year}"
        months[month] = 1 + months.get(month, 0)
        year = f"{day.year}"
        years[year] = 1 + years.get(year, 0)
        weekday = date.fromtimestamp(m["timestamp_ms"] // 1000).isoweekday()
        weekdays[weekday] = 1 + weekdays.get(weekday, 0)
        hour = datetime.fromtimestamp(m["timestamp_ms"] // 1000).hour
        hours[hour] += 1
        people["total"] += 1
        if name in names:
            people[name] = 1 + people.get(name, 0)
        if "content" in m:
            if name in names:
                data = regex.findall(r'\X', m["content"])
                for c in data:
                    if any(char in emoji.UNICODE_EMOJI for char in c):
                        emojis["total"] += 1
                        emojis["types"][c] = 1 + emojis["types"].get(c, 0)
                        emojis["sent"][name]["total"] += 1
                        emojis["sent"][name][c] = 1 + emojis["sent"][name].get(
                            c, 0)
        elif "photos" in m:
            photos["total"] += 1
            if name in names:
                photos[name] = 1 + photos.get(name, 0)
        elif "gifs" in m:
            gifs["total"] += 1
            if name in names:
                gifs[name] = 1 + gifs.get(name, 0)
        elif "sticker" in m:
            stickers["total"] += 1
            if name in names:
                stickers[name] = 1 + stickers.get(name, 0)
        elif "videos" in m:
            videos["total"] += 1
            if name in names:
                videos[name] = 1 + videos.get(name, 0)
        elif "audio_files" in m:
            audios["total"] += 1
            if name in names:
                audios[name] = 1 + audios.get(name, 0)
        elif "files" in m:
            files["total"] += 1
            if name in names:
                files[name] = 1 + files.get(name, 0)
        if "reactions" in m:
            for r in m["reactions"]:
                if r["reaction"] == decode("\u00e2\u009d\u00a4"):
                    reaction = "❤️"
                else:
                    reaction = r["reaction"]
                reactions["total"] += 1
                reactions["types"][reaction] = 1 + reactions["types"].get(
                    reaction, 0)
                if name in names:
                    reactions["got"][name]["total"] += 1
                    reactions["got"][name][
                        reaction] = 1 + reactions["got"][name].get(
                            reaction, 0)
                    if r["actor"] in names:
                        reactions["gave"][r["actor"]]["total"] += 1
                        reactions["gave"][r["actor"]][
                            reaction] = 1 + reactions["gave"][r["actor"]].get(
                                reaction, 0)

    basicStats = (people, photos, gifs, stickers, videos, audios, files)
    times = (hours, days, weekdays, months, years)
    return basicStats, reactions, emojis, times, people, fromDay, toDay, names
Пример #41
0
    def find_matches(self, text, collection, mode='fuzzy', meta=None):
        """Find completion matches for the given text.

        Given the user's input text and a collection of available
        completions, find completions matching the last word of the
        text.

        `collection` can be either a list of strings or a list of Candidate
        namedtuples.
        `mode` can be either 'fuzzy', or 'strict'
            'fuzzy': fuzzy matching, ties broken by name prevalance
            `keyword`: start only matching, ties broken by keyword prevalance

        yields prompt_toolkit Completion instances for any matches found
        in the collection of available completions.

        """
        if not collection:
            return []
        prio_order = [
            'keyword', 'function', 'view', 'table', 'datatype', 'database',
            'schema', 'column', 'table alias', 'join', 'name join', 'fk join'
        ]
        type_priority = prio_order.index(meta) if meta in prio_order else -1
        text = last_word(text, include='most_punctuations').lower()
        text_len = len(text)

        if text and text[0] == '"':
            # text starts with double quote; user is manually escaping a name
            # Match on everything that follows the double-quote. Note that
            # text_len is calculated before removing the quote, so the
            # Completion.position value is correct
            text = text[1:]

        if mode == 'fuzzy':
            fuzzy = True
            priority_func = self.prioritizer.name_count
        else:
            fuzzy = False
            priority_func = self.prioritizer.keyword_count

        # Construct a `_match` function for either fuzzy or non-fuzzy matching
        # The match function returns a 2-tuple used for sorting the matches,
        # or None if the item doesn't match
        # Note: higher priority values mean more important, so use negative
        # signs to flip the direction of the tuple
        if fuzzy:
            regex = '.*?'.join(map(re.escape, text))
            pat = re.compile('(%s)' % regex)

            def _match(item):
                if item.lower()[:len(text) + 1] in (text, text + ' '):
                    # Exact match of first word in suggestion
                    # This is to get exact alias matches to the top
                    # E.g. for input `e`, 'Entries E' should be on top
                    # (before e.g. `EndUsers EU`)
                    return float('Infinity'), -1
                r = pat.search(self.unescape_name(item.lower()))
                if r:
                    return -len(r.group()), -r.start()
        else:
            match_end_limit = len(text)

            def _match(item):
                match_point = item.lower().find(text, 0, match_end_limit)
                if match_point >= 0:
                    # Use negative infinity to force keywords to sort after all
                    # fuzzy matches
                    return -float('Infinity'), -match_point

        matches = []
        for cand in collection:
            if isinstance(cand, _Candidate):
                item, prio, display_meta, synonyms, prio2, display = cand
                if display_meta is None:
                    display_meta = meta
                syn_matches = (_match(x) for x in synonyms)
                # Nones need to be removed to avoid max() crashing in Python 3
                syn_matches = [m for m in syn_matches if m]
                sort_key = max(syn_matches) if syn_matches else None
            else:
                item, display_meta, prio, prio2, display = cand, meta, 0, 0, cand
                sort_key = _match(cand)

            if sort_key:
                if display_meta and len(display_meta) > 50:
                    # Truncate meta-text to 50 characters, if necessary
                    display_meta = display_meta[:47] + u'...'

                # Lexical order of items in the collection, used for
                # tiebreaking items with the same match group length and start
                # position. Since we use *higher* priority to mean "more
                # important," we use -ord(c) to prioritize "aa" > "ab" and end
                # with 1 to prioritize shorter strings (ie "user" > "users").
                # We first do a case-insensitive sort and then a
                # case-sensitive one as a tie breaker.
                # We also use the unescape_name to make sure quoted names have
                # the same priority as unquoted names.
                lexical_priority = (
                    tuple(0 if c in (' _') else -ord(c)
                          for c in self.unescape_name(item.lower())) + (1, ) +
                    tuple(c for c in item))

                item = self.case(item)
                display = self.case(display)
                priority = (sort_key, type_priority, prio, priority_func(item),
                            prio2, lexical_priority)

                item = decode(item)
                display_meta = decode(display_meta)
                display = decode(display)

                matches.append(
                    Match(completion=Completion(text=item,
                                                start_position=-text_len,
                                                display_meta=display_meta,
                                                display=display),
                          priority=priority))
        return matches
Пример #42
0
def videos(url, video_type, run_as_widget=False):
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    content = utility.decode(connect.load_site(url))
    if not 'id="page-LOGIN"' in content:
        if utility.get_setting(
                'single_profile'
        ) == 'true' and 'id="page-ProfilesGate"' in content:
            profiles.force_choose()
        else:
            if '<div id="queue"' in content:
                content = content[content.find('<div id="queue"'):]
            content = utility.clean_content(content)
            match = None
            if not match:
                match = re.compile('"\$type":"leaf",.*?"id":([0-9]+)',
                                   re.DOTALL).findall(content)
            print '1: ' + str(match)
            if not match:
                match = re.compile('<a href="\/watch\/([0-9]+)',
                                   re.DOTALL).findall(content)
            print '2: ' + str(match)
            if not match:
                match = re.compile('<span id="dbs(.+?)_.+?alt=".+?"',
                                   re.DOTALL).findall(content)
            print '3: ' + str(match)
            if not match:
                match = re.compile('<span class="title.*?"><a id="b(.+?)_',
                                   re.DOTALL).findall(content)
            print '4: ' + str(match)
            if not match:
                match = re.compile('"boxart":".+?","titleId":(.+?),',
                                   re.DOTALL).findall(content)
            print '5: ' + str(match)
            if not match:
                match = re.compile('WiPlayer\?movieid=([0-9]+?)&',
                                   re.DOTALL).findall(content)
            print '6: ' + str(match)
            print len(match)
            i = 1
            for video_id in match:
                if int(video_id) > 10000000:
                    if not run_as_widget:
                        utility.progress_window(loading_progress,
                                                i * 100 / len(match), '...')
                    video(video_id, '', '', False, False, video_type, url)
                i += 1
            match1 = re.compile('&pn=(.+?)&', re.DOTALL).findall(url)
            match2 = re.compile('&from=(.+?)&', re.DOTALL).findall(url)
            match_api_root = re.compile('"API_ROOT":"(.+?)"',
                                        re.DOTALL).findall(content)
            match_api_base = re.compile('"API_BASE_URL":"(.+?)"',
                                        re.DOTALL).findall(content)
            match_identifier = re.compile('"BUILD_IDENTIFIER":"(.+?)"',
                                          re.DOTALL).findall(content)
            if 'agid=' in url and match_api_root and match_api_base and match_identifier:
                genre_id = url[url.find('agid=') + 5:]
                add.directory(
                    utility.get_string(30110),
                    match_api_root[0] + match_api_base[0] + '/' +
                    match_identifier[0] + '/wigenre?genreId=' + genre_id +
                    '&full=false&from=51&to=100&_retry=0', 'list_videos', '',
                    video_type)
            elif match1:
                current_page = match1[0]
                next_page = str(int(current_page) + 1)
                add.directory(
                    utility.get_string(30110),
                    url.replace('&pn=' + current_page + '&',
                                '&pn=' + next_page + '&'), 'list_videos', '',
                    video_type)
            elif match2:
                current_from = match2[0]
                next_from = str(int(current_from) + 50)
                current_to = str(int(current_from) + 49)
                next_to = str(int(current_from) + 99)
                add.directory(
                    utility.get_string(30110),
                    url.replace('&from=' + current_from + '&',
                                '&from=' + next_from + '&').replace(
                                    '&to=' + current_to + '&',
                                    '&to=' + next_to + '&'), 'list_videos', '',
                    video_type)
            if utility.get_setting(
                    'force_view') == 'true' and not run_as_widget:
                xbmc.executebuiltin('Container.SetViewMode(' +
                                    utility.get_setting('view_id_videos') +
                                    ')')
        xbmcplugin.endOfDirectory(plugin_handle)
    else:
        delete.cookies()
        utility.log('User is not logged in.', loglevel=xbmc.LOGERROR)
        utility.notification(utility.get_string(30303))
Пример #43
0
 def test_product(self):
     original = localized.goodbye()
     localized.translation(languages=['ko']).install()
     translated = decode(localized.goodbye())
     assert original != translated
Пример #44
0
        file = open(sys.path[0] + "\\" + FICHERO_CORREGIDO_ASCII, 'w+')
        file.write(corrected.bin)

        file.flush()
        os.fsync(file.fileno())
        file.close()

    if decode:
        #Decode
        #If the data is read from an text file containing "1" and "0",
        #it is transformed to a bit sequence, which is subsequently saved
        #in a temporal binary file, used as the stream passed to the decoder

        try:
            utility.generate_temp_binary_file(FICHERO_CODIFICADO_ASCII, FICHERO_TEMPORAL)
            decoded_without_correction = utility.decode("\\" + FICHERO_TEMPORAL, transformation_matrix, irreducible_polynomial)

            os.remove(sys.path[0] + "\\" + FICHERO_TEMPORAL)

            # Save the results
            file = open(sys.path[0] + "\\" + FICHERO_DECODIFICADO_SIN_CORRECCION, 'bw+')
            file.write(bytes.fromhex(decoded_without_correction.hex))
            file.close()
        except FileNotFoundError:
            print("No se ha encontrado el fichero codificado")
            continue

        try:
            utility.generate_temp_binary_file(FICHERO_CORREGIDO_ASCII, FICHERO_TEMPORAL)
            decoded = utility.decode("\\" + FICHERO_TEMPORAL, transformation_matrix, irreducible_polynomial)
Пример #45
0
def login():
    login_progress = xbmcgui.DialogProgress()
    login_progress.create('Netflix', utility.get_string(30200) + '...')
    utility.progress_window(login_progress, 25, utility.get_string(30201))
    connect.session.cookies.clear()
    content = utility.decode(connect.load_site(utility.main_url + '/Login'))
    match = re.compile('"locale":"(.+?)"', re.DOTALL | re.IGNORECASE).findall(content)
    if match and not utility.get_setting('language'):
        utility.log('Setting language: ' + match[0])
        utility.set_setting('language', match[0])
    if not 'Sorry, Netflix ' in content:
        match = re.compile('id="signout".+?authURL=(.+?)"', re.DOTALL).findall(content)
        if match:
            utility.log('Setting authorization url: ' + match[0])
            utility.set_setting('authorization_url', match[0])
        if 'id="page-LOGIN"' in content:
            match = re.compile('name="authURL" value="(.+?)"', re.DOTALL).findall(content)
            utility.log('Setting authorization url: ' + match[0])
            utility.set_setting('authorization_url', match[0])
            post_data = {'authURL': match[0], 'email': utility.get_setting('username'),
                         'password': utility.get_setting('password'), 'RememberMe': 'on'}
            utility.progress_window(login_progress, 50, utility.get_string(30202))
            content = utility.decode(connect.load_site(utility.main_url + '/Login?locale=' +
                                                       utility.get_setting('language'), post=post_data))
            if 'id="page-LOGIN"' in content:
                utility.notification(utility.get_string(30303))
                return False
            match = re.compile('"locale":"(.+?)"', re.DOTALL | re.IGNORECASE).findall(content)
            if match and not utility.get_setting('language'):
                utility.log('Setting language: ' + match[0])
                utility.set_setting('language', match[0])
            match = re.compile('"country":"(.+?)"', re.DOTALL | re.IGNORECASE).findall(content)
            if match:
                utility.log('Setting country code: ' + match[0])
                utility.set_setting('country_code', match[0])
            connect.save_session()
            utility.progress_window(login_progress, 75, utility.get_string(30203))
        if not (utility.get_setting('selected_profile') or (utility.get_setting('single_profile') == 'true')):
            profiles.choose()
        elif not (utility.get_setting('single_profile') == 'true') and (utility.get_setting('show_profiles') == 'true'):
            profiles.choose()
        elif not (
                    (utility.get_setting('single_profile') == 'true') and (
                            utility.get_setting('show_profiles') == 'true')):
            profiles.load()
        else:
            profiles.get_my_list_change_authorisation()
        if not utility.get_setting('is_kid') == 'true':
            content = utility.decode(connect.load_site(utility.main_url + '/browse'))
            match = re.compile('"version":{"app":"(.+?)"').findall(content)
            netflix_application, netflix_id = match[0].split('-')
            utility.set_setting('netflix_application', netflix_application)
            utility.set_setting('netflix_id', netflix_id)
        if login_progress:
            if not utility.progress_window(login_progress, 100, utility.get_string(30204)):
                return False
            xbmc.sleep(500)
            login_progress.close()
        return True
    else:
        utility.notification(utility.get_string(30300))
        if login_progress:
            login_progress.close()
        return False
Пример #46
0
def videos(url, video_type, run_as_widget=False):
    loading_progress = None
    if not run_as_widget:
        loading_progress = xbmcgui.DialogProgress()
        loading_progress.create('Netflix', utility.get_string(30205) + '...')
        utility.progress_window(loading_progress, 0, '...')
    xbmcplugin.setContent(plugin_handle, 'movies')
    if not xbmcvfs.exists(utility.session_file()):
        login.login()
    '''
    the next part is necessary during the changing phase. Otherwise data are not available.
    '''
    if 'recently-added' in url:
        postdata = utility.recently_added % utility.get_setting('authorization_url')
        content = utility.decode(connect.load_site(utility.evaluator(), post=postdata))
    else:
        content = utility.decode(connect.load_site(url))
    if not 'id="page-LOGIN"' in content or url == 'recently-added':
        if utility.get_setting('single_profile') == 'true' and 'id="page-ProfilesGate"' in content:
            profiles.force_choose()
        else:
            if '<div id="queue"' in content:
                content = content[content.find('<div id="queue"'):]
            if not 'recently-added' in url:
                content = utility.clean_content(content)
            match = None
            if not match: match = re.compile('"\$type":"leaf",.*?"id":([0-9]+)', re.DOTALL).findall(content)
            print '1: ' + str(match)
            if not match: match = re.compile('<a href="\/watch\/([0-9]+)', re.DOTALL).findall(content)
            print '2: ' + str(match)
            if not match: match = re.compile('<span id="dbs(.+?)_.+?alt=".+?"', re.DOTALL).findall(content)
            print '3: ' + str(match)
            if not match: match = re.compile('<span class="title.*?"><a id="b(.+?)_', re.DOTALL).findall(content)
            print '4: ' + str(match)
            if not match: match = re.compile('"boxart":".+?","titleId":(.+?),', re.DOTALL).findall(content)
            print '5: ' + str(match)
            if not match: match = re.compile('WiPlayer\?movieid=([0-9]+?)&', re.DOTALL).findall(content)
            print '6: ' + str(match)
            if 'recently-added' in url:
                matches = json.loads(content)['value']['videos']
                for video_id in matches:
                    match.append(unicode(video_id))
            print '7: ' + str(match)
            print len(match)
            i = 1
            for video_id in match:
                if int(video_id) > 10000000 or 'recently-added' in url:
                    if not run_as_widget:
                        utility.progress_window(loading_progress, i * 100 / len(match), '...')
                    video(video_id, '', '', False, False, video_type, url)
                i += 1
            match1 = re.compile('&pn=(.+?)&', re.DOTALL).findall(url)
            match2 = re.compile('&from=(.+?)&', re.DOTALL).findall(url)
            match_api_root = re.compile('"API_ROOT":"(.+?)"', re.DOTALL).findall(content)
            match_api_base = re.compile('"API_BASE_URL":"(.+?)"', re.DOTALL).findall(content)
            match_identifier = re.compile('"BUILD_IDENTIFIER":"(.+?)"', re.DOTALL).findall(content)
            if 'agid=' in url and match_api_root and match_api_base and match_identifier:
                genre_id = url[url.find('agid=') + 5:]
                add.directory(utility.get_string(30110), match_api_root[0] + match_api_base[0] + '/' + match_identifier[
                    0] + '/wigenre?genreId=' + genre_id + '&full=false&from=51&to=100&_retry=0', 'list_videos', '',
                              video_type)
            elif match1:
                current_page = match1[0]
                next_page = str(int(current_page) + 1)
                add.directory(utility.get_string(30110),
                              url.replace('&pn=' + current_page + '&', '&pn=' + next_page + '&'), 'list_videos', '',
                              video_type)
            elif match2:
                current_from = match2[0]
                next_from = str(int(current_from) + 50)
                current_to = str(int(current_from) + 49)
                next_to = str(int(current_from) + 99)
                add.directory(utility.get_string(30110),
                              url.replace('&from=' + current_from + '&', '&from=' + next_from + '&').replace(
                                  '&to=' + current_to + '&', '&to=' + next_to + '&'), 'list_videos', '', video_type)
            if utility.get_setting('force_view') == 'true' and not run_as_widget:
                xbmc.executebuiltin('Container.SetViewMode(' + utility.get_setting('view_id_videos') + ')')
        xbmcplugin.endOfDirectory(plugin_handle)
    else:
        delete.cookies()
        utility.log('User is not logged in.', loglevel=xbmc.LOGERROR)
        utility.notification(utility.get_string(30303))