def set(self, id, data, **kwargs):
        """
        Saves data to storage
        # id   - string,   unique string to identify data
        # data - any type, data to cache (string, int, list, dict)
        # persistent - boolean, if true it saves the data persistent    (optional)
        """

        if kwargs.get('persistent', False):
            pointer = self.md5(id)
            try:
                raw = pickle.dumps(data)
                mc.GetApp().GetLocalConfig().SetValue(
                    pointer, binascii.hexlify(bz2.compress(raw)))
                mc.GetApp().GetLocalConfig().SetValue(pointer + "_timestamp",
                                                      str(time.time()))
                return True
            except:
                print traceback.format_exc()

        else:
            pointer = os.path.join(self.path, self.md5(id))
            try:
                fp = open(pointer, "wb")
                pickle.dump(data, fp)
                fp.close()
                return True
            except:
                print traceback.format_exc()

        return False
Esempio n. 2
0
def onclick():
    state = mc.GetApp().GetLocalConfig().GetValue("logotweak.state")

    if state == "green":
        #red
        os.system(
            'printf "\xAA\x06\x35\x30\x30\x33\x30\x30\x35\x33" > /dev/ttyS1')
        os.system(
            'printf "\xAA\x06\x35\x30\x30\x31\x36\x34\x42\x35" > /dev/ttyS1')
        mc.GetApp().GetLocalConfig().SetValue("logotweak.state", "red")
        mc.ShowDialogNotification("Boxee Box Logo: Red")
    elif state == "red":
        #off
        os.system(
            'printf "\xAA\x06\x35\x30\x30\x33\x30\x30\x35\x33" > /dev/ttyS1')
        mc.GetApp().GetLocalConfig().SetValue("logotweak.state", "off")
        mc.ShowDialogNotification("Boxee Box Logo: Off")
    elif state == "off":
        #green
        os.system(
            'printf "\xAA\x06\x35\x30\x30\x33\x30\x30\x35\x33" > /dev/ttyS1')
        os.system(
            'printf "\xAA\x06\x35\x30\x30\x32\x36\x34\x42\x36" > /dev/ttyS1')
        mc.GetApp().GetLocalConfig().SetValue("logotweak.state", "green")
        mc.ShowDialogNotification("Boxee Box Logo: Green")
Esempio n. 3
0
def updateArchiveSpoiler():
    try:
        mc.ShowDialogWait()
        if isLoggedIn():
            response = callService('showhide')
            if ((response == 'T') and mc.GetApp().GetLocalConfig().SetValue(
                    'hide_scores', 'true')):
                pass
        else:
            mc.GetApp().GetLocalConfig().Reset('hide_scores')
        mc.HideDialogWait()
    except Exception, e:
        mc.GetApp().GetLocalConfig().Reset('hide_scores')
        return raiseError(log='updatearchivespoiler', error=e)
Esempio n. 4
0
def authenticate():
    try:
        content = mc.Http().Get(
            'http://app.boxee.tv/api/get_application_data?id=mlb')
        if content:
            return status_error
        else:
            auth_dom = parseString(content)
            email = auth_dom.getElementsByTagName('email')[0].firstChild.data
            account = auth_dom.getElementsByTagName(
                'rand_account')[0].firstChild.data
            post_data = request({
                'func': '_login',
                'email': email,
                'pass': account
            })
            if ((not post_data) or (post_data['data'] == '0')):
                Exception('post request return false')
            cf = mc.GetApp().GetLocalConfig()
            response = getJson(data=post_data['data'])
            response = response.get('identity')
            code = str(response.get('code'))
            if ((code != '1') and info('authenticate.code', code)):
                cf.Reset('fprt')
                cf.Reset('ipid')
                cf.Reset('username')
                cf.Reset('password')
                info('login', 'stored/entered credentials invalid')
                return status_invalid
            mc.HideDialogWait()
    except Exception, e:
        updateArchiveSpoiler()
        return status_invalid
Esempio n. 5
0
def callService(func, values={}, authenticated=True, content=False):
    try:
        info('callservice',
             ('calling the boxee_mlb service w/%s, authentication/%s' %
              (func, str(authenticated).lower())))
        params = {}
        http_service = mc.Http()
        url_base = 'http://dir.boxee.tv/apps/mlb/mlb.php?func=%s&%s'
        if authenticated:
            app = mc.GetApp()
            cf = app.GetLocalConfig()
            params['nsfp'] = cf.GetValue('fprt')
            params['nsid'] = cf.GetValue('ipid')
        if values:
            for i in values:
                params[i] = values[i]

        url_base = underscore((url_base % (func, urllib.urlencode(params))))
        query_result = http_service.Get(url_base)
        if (content == 'json'):
            query_result = re.sub('//.*?\n|/\\*.*?\\*/', '', query_result,
                                  re.S)
            query_result = json.loads(query_result)
        return query_result
    except Exception, e:
        return raiseError(log='callservice', error=e)
Esempio n. 6
0
class User(object):
    isAuthenticated = False
    config = mc.GetApp().GetLocalConfig()

    def __init__(self):
        try:
            self.userName = self.config.GetValue("username")
            self.userPassword = self.config.GetValue("password")
        except:
            self.userName = ''
            self.userPassword = ''
        if (len(self.userName) > 0 and len(self.userPassword) > 0):
            self.authenticate(self.userName, self.userPassword)

    def authenticate(self, user, password):
        if (api.doLogin(user, password)):
            self.config.SetValue('username', user)
            self.config.SetValue('password', password)
            self.isAuthenticated = True

    def logout(self):
        self.config.Reset('username')
        self.config.Reset('password')
        self.config.Reset('user-token')
        self.config.Reset('auth-token')
        self.isAuthenticated = False
    def RestoreFromDefaults(self):
        stringRep = mc.GetApp().GetLocalConfig().GetValue("history-items")
        if len(stringRep) > 0:
            #mc.LogInfo("string representation of items: %s" % stringRep)
            listLoaded = pickle.loads(stringRep)
            list = []
            for item in listLoaded:
                type = mc.ListItem.MEDIA_VIDEO_FEATURE_FILM
                playItem = mc.ListItem(type)
                playItem.SetThumbnail(item["image"])
                playItem.SetTitle(item["title"])
                playItem.SetDescription(item["description"])
                playItem.SetLabel(item["title"])
                playItem.SetPath(item["path"])
                if item.has_key("timeToResume"):
                    playItem.SetProperty("timeToResume", item["timeToResume"])
                if item.has_key("lastViewedEpisodeIndex"):
                    playItem.SetProperty("lastViewedEpisodeIndex",
                                         item["lastViewedEpisodeIndex"])
                if item.has_key('folder'):
                    playItem.SetProperty('folder', item['folder'])
                list.append(playItem)

            return list

        else:
            return []
Esempio n. 8
0
 def GetStoredPlaylistNamesByPlayingTimes(self):
     stringRep = mc.GetApp().GetLocalConfig().GetValue(
         "playlistnames-by-times")
     storedItems = dict()
     if len(stringRep) > 0: storedItems = pickle.loads(stringRep)
     if None == storedItems: storedItems = dict()
     return storedItems
Esempio n. 9
0
    def __init__(
        self,
        uacode=False,
    ):
        self.uacode = uacode
        self.debug = False
        self.version = "1.0"
        self.domain = 'boxee.bartsidee.nl'
        self.application = mc.GetApp().GetId()

        if 'linux' in sys.platform:
            self.os = 'Linux'
        elif 'win32' in sys.platform:
            self.os = 'Windows'
        elif 'darwin' in sys.platform:
            self.os = 'Macintosh'

        try:
            self.platform = mc.GetPlatform()
        except:
            self.platform = 'Boxee'
        try:
            self.deviceid = mc.GetDeviceId()
        except:
            self.deviceid = 'None'
        try:
            self.boxeeid = mc.GetUniqueId()
        except:
            self.boxeeid = 'None'
Esempio n. 10
0
def SetListView(view, passive=False):
    ListView = mc.GetApp().GetLocalConfig().GetValue("listview")
    if ListView == "list":
        view = "list"
    elif ListView == "thumbnails":
        view = "thumbnails"

    if view == "default":
        oldview = 212
        newview = 112
    if view == "list":
        oldview = 212
        newview = 112
    elif view == "thumbnails":
        oldview = 112
        newview = 212
    else:  #list
        oldview = 212
        newview = 112

    if passive == False:
        mc.GetWindow(14000).GetControl(oldview).SetVisible(False)  #Hide List
        mc.GetWindow(14000).GetControl(newview).SetVisible(True)  #Show List

    return newview
Esempio n. 11
0
def MenuRightSelectItem(itemNumber):
    if itemNumber == 0:  #add item to favorites
        stackitem = mc.GetWindow(14000).GetList(555).GetItem(0)
        URL = stackitem.GetProperty("URL")
        if URL.find(favorites_URL) != -1:
            mc.ShowDialogOk("Error", "Cannot Add From Favorite List.")
            return
        ModifyFavoriteList('add')
        mc.GetWindow(14000).GetList(GetListView()).SetFocus()
    elif itemNumber == 1:  #remove items from favorites
        stackitem = mc.GetWindow(14000).GetList(555).GetItem(0)
        URL = stackitem.GetProperty("URL")
        if URL.find(favorites_URL) == -1:
            mc.ShowDialogOk("Error", "Please Select Favorite List First.")
            return
        ModifyFavoriteList('remove')

        userkey = mc.GetApp().GetLocalConfig().GetValue("userkey")
        arguments = "?user="******"&request=get&type=.plx"
        ParsePlaylist(URL=favorites_URL + arguments)

        mc.GetWindow(14000).GetList(GetListView()).SetFocus()
    elif itemNumber == 2:  #about Navi-X
        mc.GetWindow(14000).PushState()
        OpenTextFile(URL='readme.txt')
Esempio n. 12
0
def start():
    os.system("/etc/init.d/telnetd start")
    mc.GetApp().GetLocalConfig().SetValue("telnettweak.status", "1")
    ilist = mc.GetActiveWindow().GetList(101)
    item = ilist.GetItem(ilist.GetFocusedItem())
    item.SetLabel("Disable Telnet")
    mc.ShowDialogNotification("Telnet: Started")
Esempio n. 13
0
def PushDir():
	app = mc.GetApp()
	params = mc.Parameters()
	params["noreload"] = "1"
	app.ActivateWindow(targetwindow, params)
	list = mc.GetWindow(targetwindow).GetList(targetcontrol)
	list.SetItems(dir)
	mc.HideDialogWait()
Esempio n. 14
0
def stop():
    os.system(
        "/bin/kill `ps ax | grep -v grep | grep telnetd | awk '{print $1}'`")
    mc.GetApp().GetLocalConfig().SetValue("telnettweak.status", "0")
    ilist = mc.GetActiveWindow().GetList(101)
    item = ilist.GetItem(ilist.GetFocusedItem())
    item.SetLabel("Enable Telnet")
    mc.ShowDialogNotification("Telnet: Stopped")
 def construct(self):
     """sets cache dir in temp folder"""
     id = mc.GetApp().GetId()
     prefix = "cache_"
     tmp = mc.GetTempDir()
     path = os.path.join(tmp, prefix + id)
     if not os.path.exists(path):
         os.makedirs(path)
     return path
Esempio n. 16
0
 def read_user_id(self):
     #        try:
     #            f=open(RootDir + 'user_id.dat', 'r')
     #            self.user_id = f.read()
     #            f.close()
     #        except IOError:
     #            return
     config = mc.GetApp().GetLocalConfig()
     self.user_id = config.GetValue("userid")
Esempio n. 17
0
def getCredentials():
    try:
        cf = mc.GetApp().GetLocalConfig()
        if (cf.GetValue('username') and cf.GetValue('password')):
            return {
                'user': cf.GetValue('username'),
                'pass': cf.GetValue('password')
            }
    except Exception, e:
        return raiseError(log='getCredentials', error=e)
    def get(self, id, **kwargs):
        """
        Gets data from storage
        # id         - string, unique string to identify data
        # age        - int,    if set checks if data is not older then age in seconds (optional)
        # persistent - boolean, if true it saves the data persistent                  (optional)
        """
        if kwargs.get('age'):
            age = kwargs['age']
        else:
            age = 0

        if kwargs.get('persistent', False):
            pointer = self.md5(id)
            expire = time.time() - age

            try:
                raw = bz2.decompress(
                    binascii.unhexlify(
                        mc.GetApp().GetLocalConfig().GetValue(pointer)))
                timestamp = float(
                    mc.GetApp().GetLocalConfig().GetValue(pointer +
                                                          "_timestamp"))
                if timestamp >= expire or age == 0:
                    return pickle.loads(raw)
            except:
                print traceback.format_exc()
        else:
            pointer = os.path.join(self.path, self.md5(id))
            expire = time.time() - age

            if os.path.isfile(pointer):
                timestamp = os.path.getmtime(pointer)
                if timestamp >= expire or age == 0:
                    try:
                        fp = open(pointer)
                        data = pickle.load(fp)
                        fp.close()
                        return data
                    except:
                        print traceback.format_exc()

        return False
Esempio n. 19
0
def prevMonth():
    try:
        cf = mc.GetApp().GetLocalConfig()
        if cf.GetValue('calendar'):
            active = 0
        else:
            active = int(cf.GetValue('calendar'))
        setMonth((active - 1))
    except Exception, e:
        return raiseError(log='prevmonth', error=e)
Esempio n. 20
0
def ModifyFavoriteList(command='none'):
    list = mc.GetWindow(14000).GetList(GetListView())
    itemNumber = list.GetFocusedItem()

    if itemNumber < 0:
        return

    if command == 'add':
        listitem = list.GetItem(itemNumber)
        mediaitem = CMediaItem()
        mediaitem.type = listitem.GetProperty("media_type")
        mediaitem.name = listitem.GetLabel()
        mediaitem.thumb = listitem.GetProperty("thumb")
        mediaitem.URL = listitem.GetProperty("url")
        mediaitem.processor = listitem.GetProperty("processor")

        postdata = "type=" + mediaitem.type + "\n"
        postdata = postdata + "name=" + mediaitem.name + "\n"
        postdata = postdata + "thumb=" + mediaitem.thumb + "\n"
        postdata = postdata + "URL=" + mediaitem.URL + "\n"
        postdata = postdata + "processor=" + mediaitem.processor + "\n"

        try:
            userkey = mc.GetApp().GetLocalConfig().GetValue("userkey")
            arguments = "?user="******"&request=add"
            req = urllib2.Request(favorites_URL + arguments, postdata)
            f = urllib2.urlopen(req)
            data = f.read()
            f.close()
        except IOError:
            pass
    elif command == 'remove':
        try:
            userkey = mc.GetApp().GetLocalConfig().GetValue("userkey")
            arguments = "?user="******"&request=remove&index=" + str(
                itemNumber)
            req = urllib2.Request(favorites_URL + arguments)
            f = urllib2.urlopen(req)
            data = f.read()
            f.close()
        except IOError:
            pass
Esempio n. 21
0
def logout():
    try:
        cf = mc.GetApp().GetLocalConfig()
        cf.Reset('fprt')
        cf.Reset('ipid')
        cf.Reset('username')
        cf.Reset('password')
        cf.Reset('hide_scores')
        return True
    except Exception, e:
        return raiseError(log='logout', error=e)
Esempio n. 22
0
    def save(self):
        data = {}
        for key in self._settings:
            data[key] = vars(self)[key]

        if self.embedded:
            import mc
            mc.GetApp().GetLocalConfig().SetValue(
                'settings', binascii.hexlify(marshal.dumps(data)))
        else:
            json_dumps(data,
                       os.path.join(self.dataDir, 'settings', 'settings.json'))
Esempio n. 23
0
def MenuLeftSelectItem(itemNumber):
    if itemNumber == 0:
        SelectItem(iURL=home_URL)
        mc.GetWindow(14000).GetList(GetListView()).SetFocus()
    elif itemNumber == 1:
        userkey = mc.GetApp().GetLocalConfig().GetValue("userkey")
        arguments = "?user="******"&request=get&type=.plx"
        SelectItem(iURL=favorites_URL + arguments)
    elif itemNumber == 2:
        ListView = mc.GetApp().GetLocalConfig().GetValue("listview")
        if ListView == "default":
            mc.GetApp().GetLocalConfig().SetValue("listview", "thumbnails")
        elif ListView == "thumbnails":
            mc.GetApp().GetLocalConfig().SetValue("listview", "list")
        else:
            mc.GetApp().GetLocalConfig().SetValue("listview", "default")
        Init()
        ParsePlaylist(reload=False)
        mc.GetWindow(14000).GetList(122).SetFocus()
        mc.GetWindow(14000).GetList(122).SetFocusedItem(itemNumber)
    elif itemNumber == 3:
        if nxserver.is_user_logged_in() == True:
            response = mc.ShowDialogConfirm("Message", "Sign out?", "No",
                                            "Yes")
            if response:
                nxserver.logout()
                mc.ShowDialogOk("Sign out", "Sign out Successful.")
                Init()
        else:
            result = nxserver.login()
            if result == 0:
                mc.ShowDialogOk("Sign in", "Sign in Successful.")
                Init()
            elif result == -1:
                mc.ShowDialogOk("Sign in", "Sign in Failed.")
        mc.GetWindow(14000).GetList(GetListView()).SetFocus()
    elif itemNumber == 4:
        mc.CloseWindow()
    pass
Esempio n. 24
0
def doLogin(user, password):
    params = urllib.urlencode({'login': user, 'password': password})
    url = "%s/%s?%s&%s" % (baseUrl, loginPath, apiKey, apiVersion)
    fd = urllib.urlopen(url, params)
    response = simplejson.loads(fd.read())
    config = mc.GetApp().GetLocalConfig()
    if (response['status'] != '200 OK'):
        config.Reset('auth-token')
        config.Reset('user-token')
        return False
    else:
        config.SetValue("auth-token", str(response['auth_token']))
        config.SetValue('user-token', str(response['user_token']))
        return True
Esempio n. 25
0
 def open(self):
     """Open an existing database and load its content into memory"""
     # guess protocol
     data = bz2.decompress(
         binascii.unhexlify(mc.GetApp().GetLocalConfig().GetValue(
             self.name)))
     try:
         self.fields, self.next_id, self.records, self.indices = cPickle.loads(
             data)
         for f in self.indices.keys():
             setattr(self, '_' + f, Index(self, f))
         self.mode = "open"
         return True, self
     except:
         return False, self
Esempio n. 26
0
def playList(mlbList):
    try:
        cf = mc.GetApp().GetLocalConfig()
        list = mc.GetActiveWindow().GetList(mlbList)
        item = list.GetItem(list.GetFocusedItem())
        if (isLoggedIn() or mc.ShowDialogNotification(
                'You must first log in before you can watch this game.',
                'mlb-icon.png')):
            pass
    except Exception, e:
        error('playlist', e)
        mc.ShowDialogNotification(
            'Sorry, we are currently unable to play this game.',
            'mlb-icon.png')
        return False
    def empty(self, **kwargs):
        """
        removes all data from cache
        # persistent - boolean, if true empties all persistent data (optional)
        """
        for root, dirs, files in os.walk(self.path, topdown=False):
            for name in files:
                filename = os.path.join(root, name)
                os.chmod(filename, stat.S_IWUSR)
                os.remove(filename)
            for name in dirs:
                os.rmdir(os.path.join(root, name))

        if kwargs.get('persistent', False):
            mc.GetApp().GetLocalConfig().ResetAll()
    def StoreToDefaults(self):
        listToStore = []
        for item in self.historyItems:
            theDict = {"path": item.GetPath(), "title": item.GetLabel()}
            theDict["description"] = item.GetDescription()
            theDict["image"] = item.GetThumbnail()
            if item.GetProperty("timeToResume"):
                theDict["timeToResume"] = str(item.GetProperty("timeToResume"))
            if item.GetProperty("lastViewedEpisodeIndex"):
                theDict["lastViewedEpisodeIndex"] = str(
                    item.GetProperty("lastViewedEpisodeIndex"))
            listToStore.append(theDict)

        stringRep = pickle.dumps(listToStore)
        if stringRep != None:
            mc.GetApp().GetLocalConfig().SetValue("history-items", stringRep)
Esempio n. 29
0
def setMonth(active, setList=True):
    try:
        window = mc.GetActiveWindow()
        cf = mc.GetApp().GetLocalConfig()
        cf.SetValue('calendar', str(active))
        if setList:
            month = getMonth(active, False)
            if (active == 0):
                url = month.strftime('rss://dir.boxee.tv/apps/mlb/feed/%Y/%m')
            else:
                url = 'rss://dir.boxee.tv/apps/mlb/feed/calendar'
            mc.GetActiveWindow().GetList(121).SetContentURL(url)
        window.GetLabel(102).SetLabel(
            (('[UPPERCASE]' + getMonth(active, True)) + '[/UPPERCASE]'))
        window.GetLabel(103).SetLabel((('[UPPERCASE]' + getMonth(
            (active + 1), True)) + '[/UPPERCASE]'))
        window.GetLabel(101).SetLabel((('[UPPERCASE]' + getMonth(
            (active - 1), True)) + '[/UPPERCASE]'))
    except Exception, e:
        return raiseError(log='nextmonth', error=e)
Esempio n. 30
0
def promptQuality():
    try:
        cf = mc.GetApp().GetLocalConfig()
        q_ask = bool(cf.GetValue('ask_quality'))
        q_high = bool(cf.GetValue('high_quality'))
        q_default = bool(cf.GetValue('default_quality'))
        if ((not q_ask) and ((not q_high) and (not q_default))):
            q_ask = True
            cf.SetValue('ask_quality', '1')
        if q_ask:
            q_message = 'Please select your video quality (manage this and other options in the settings tab):'
            quality = mc.ShowDialogConfirm('MLB.TV', q_message, 'Normal',
                                           'High')
            quality = int(quality)
        elif q_high:
            quality = 1
        else:
            quality = 0
        return str(quality)
    except Exception, e:
        return raiseError(log='promptquality', error=e)