def testDailyAlarm(self):
     from time import strftime
     self.topics = [Topic('onDailyAlarm', 'E1')]
     hour, minute = strftime('%H:%M').split(':')
     xsettings = [{
         'hour': int(hour),
         'minute': int(minute) + 1,
         'key': 'E1'
     }]
     settings = Settings()
     flexmock(settings, getEventsByType=xsettings)
     self.publisher = SchedulePublisher(self.dispatcher, settings)
     self.publisher.intervalAlarms = []
     self.publisher.sleep = time.sleep
     self.publisher.sleepinterval = 1
     self.subscriber.addTopic(self.topics[0])
     self.dispatcher.addSubscriber(self.subscriber)
     self.dispatcher.start()
     self.publisher.start()
     self.subscriber.waitForMessage(count=1, timeout=65)
     self.publisher.abort()
     self.dispatcher.abort()
     messages = self.subscriber.retrieveMessages()
     msgtopics = [msg.topic for msg in messages]
     time.sleep(1)
     for topic in self.topics:
         assert topic in msgtopics
Exemple #2
0
def start():
    global log
    settings = Settings()
    settings.getSettings()
    kl = KodiLogger()
    if settings.general['elevate_loglevel'] is True:
        kl.setLogLevel(xbmc.LOGINFO)
    else:
        kl.setLogLevel(xbmc.LOGDEBUG)
    log = kl.log
    log(msg=_('Settings read'))
    Cache.dispatcher = PubSub_Threaded.Dispatcher(
        interval=settings.general['TaskFreq'], sleepfxn=xbmc.sleep)
    log(msg=_('Dispatcher initialized'))

    subscriberfactory = SubscriberFactory(settings, kl)
    subscribers = subscriberfactory.createSubscribers()
    for subscriber in subscribers:
        Cache.dispatcher.addSubscriber(subscriber)
    publisherfactory = PublisherFactory(settings, subscriberfactory.topics,
                                        Cache.dispatcher, kl, debug)
    publisherfactory.createPublishers()
    Cache.publishers = publisherfactory.ipublishers

    Cache.dispatcher.start()
    log(msg=_('Dispatcher started'))

    for p in Cache.publishers:
        try:
            p.start()
        except threading.ThreadError:
            raise
    log(msg=_('Publisher(s) started'))
 def __init__(self):
     super(MediathekViewPlugin, self).__init__()
     self.settings = Settings()
     self.notifier = Notifier()
     self.database = Store(self.get_new_logger('Store'), self.notifier,
                           self.settings)
     self.unicodePath = unicode(self.path, 'utf-8')
	def __init__( self, plugin, sortmethods = None ):
		self.plugin			= plugin
		self.handle			= plugin.addon_handle
		self.settings		= Settings()
		self.sortmethods	= sortmethods if sortmethods is not None else [ xbmcplugin.SORT_METHOD_TITLE, xbmcplugin.SORT_METHOD_DATE, xbmcplugin.SORT_METHOD_DURATION, xbmcplugin.SORT_METHOD_SIZE ]
		self.showshows		= False
		self.showchannels	= False
Exemple #5
0
 def __init__(self):
     super(MediathekViewService, self).__init__()
     self.set_topic('Service')
     self.settings = Settings()
     self.notifier = Notifier()
     self.monitor = MediathekViewMonitor(self, 'instanceid')
     self.updater = MediathekViewUpdater(self.get_new_logger(
         'Updater'), self.notifier, self.settings, self.monitor)
 def __init__(self):
     super(MediathekViewService, self).__init__()
     self.setTopic('Service')
     self.settings = Settings()
     self.notifier = Notifier()
     self.monitor = MediathekViewMonitor(self)
     self.updater = MediathekViewUpdater(self.getNewLogger('Updater'),
                                         self.notifier, self.settings,
                                         self.monitor)
def test(key):
    global log
    log = KodiLogger.log
    import resources.lib.tests.direct_test as direct_test
    from resources.lib.events import Events
    import traceback
    log(msg=_('Running Test for Event: %s') % key)
    events = Events().AllEvents
    settings = Settings()
    settings.getSettings()
    if settings.general['elevate_loglevel'] is True:
        KodiLogger.setLogLevel(xbmc.LOGNOTICE)
    else:
        KodiLogger.setLogLevel(xbmc.LOGDEBUG)
    log(msg=_('Settings for test read'))
    evtsettings = settings.events[key]
    topic = settings.topicFromSettingsEvent(key)
    task_key = settings.events[key]['task']
    tasksettings = settings.tasks[task_key]
    testlogger = direct_test.TestLogger()
    log(msg=_('Creating subscriber for test'))
    subscriberfactory = SubscriberFactory(settings, testlogger)
    subscriber = subscriberfactory.createSubscriber(key)
    if subscriber is not None:
        log(msg=_('Test subscriber created successfully'))
        try:
            kwargs = events[evtsettings['type']]['expArgs']
        except KeyError:
            kwargs = {}
        testRH = direct_test.TestHandler(
            direct_test.testMsg(subscriber.taskmanagers[0], tasksettings,
                                kwargs))
        subscriber.taskmanagers[0].returnHandler = testRH.testReturnHandler
        # Run test
        log(msg=_('Running test'))
        nMessage = PubSub_Threaded.Message(topic=topic, **kwargs)
        try:
            subscriber.notify(nMessage)
        except Exception:
            msg = _('Unspecified error during testing')
            e = sys.exc_info()[0]
            if hasattr(e, 'message'):
                msg = str(e.message)
            msg = msg + '\n' + traceback.format_exc()
            log(msg=msg)
            msgList = msg.split('\n')
            import resources.lib.dialogtb as dialogtb
            dialogtb.show_textbox('Error', msgList)
    else:
        log(msg=_('Test subscriber creation failed due to errors'))
        msgList = testlogger.retrieveLogAsList()
        import resources.lib.dialogtb as dialogtb
        dialogtb.show_textbox('Error', msgList)

    xbmc.sleep(2000)
 def testStereoModeChange(self):
     self.topics = [Topic('onStereoModeChange')]
     self.subscriber.addTopic(self.topics[0])
     self.dispatcher.addSubscriber(self.subscriber)
     settings = Settings()
     flexmock(settings, general={'LoopFreq': 100})
     self.publisher = LoopPublisher(self.dispatcher, settings)
     self.dispatcher.start()
     self.publisher.start()
     self.subscriber.waitForMessage(count=1, timeout=5)
     self.publisher.abort()
     self.dispatcher.abort()
     messages = self.subscriber.retrieveMessages()
     msgtopics = [msg.topic for msg in messages]
     for topic in self.topics:
         assert topic in msgtopics
 def testProfileChange(self):
     self.topics = [Topic('onProfileChange')]
     self.subscriber.addTopic(self.topics[0])
     self.dispatcher.addSubscriber(self.subscriber)
     settings = Settings()
     flexmock(settings, general={'LoopFreq': 100})
     self.publisher = LoopPublisher(self.dispatcher, settings)
     self.dispatcher.start()
     self.publisher.start()
     time.sleep(5)
     self.publisher.abort()
     self.dispatcher.abort()
     messages = self.subscriber.retrieveMessages()
     msgtopics = [msg.topic for msg in messages]
     for topic in self.topics:
         assert topic in msgtopics
 def testOnWindowClose(self):
     self.topics = [Topic('onWindowClose', 'E1')]
     self.subscriber.addTopic(self.topics[0])
     self.dispatcher.addSubscriber(self.subscriber)
     settings = Settings()
     flexmock(settings, general={'LoopFreq': 100})
     flexmock(settings, getClosewindowids={10001: 'E1'})
     self.publisher = LoopPublisher(self.dispatcher, settings)
     self.dispatcher.start()
     self.publisher.start()
     time.sleep(5)
     self.publisher.abort()
     self.dispatcher.abort()
     messages = self.subscriber.retrieveMessages()
     msgtopics = [msg.topic for msg in messages]
     for topic in self.topics:
         assert topic in msgtopics
 def testOnWindowOpen(self):
     self.topics = [Topic('onWindowOpen', 'E1')]
     self.subscriber.addTopic(self.topics[0])
     self.dispatcher.addSubscriber(self.subscriber)
     settings = Settings()
     flexmock(settings, general={'LoopFreq': 100})
     flexmock(settings, getOpenwindowids={10001: 'E1'})
     self.publisher = LoopPublisher(self.dispatcher, settings)
     self.dispatcher.start()
     self.publisher.start()
     self.subscriber.waitForMessage(count=1, timeout=5)
     self.publisher.abort()
     self.dispatcher.abort()
     messages = self.subscriber.retrieveMessages()
     msgtopics = [msg.topic for msg in messages]
     for topic in self.topics:
         assert topic in msgtopics
 def testLoopIdle(self):
     self.topics = [Topic('onIdle', 'E1'), Topic('onIdle', 'E2')]
     for topic in self.topics:
         self.subscriber.addTopic(topic)
     self.dispatcher.addSubscriber(self.subscriber)
     idleSettings = {'E1': 3, 'E2': 5}
     settings = Settings()
     flexmock(settings, getIdleTimes=idleSettings)
     flexmock(settings, general={'LoopFreq': 100})
     self.publisher = LoopPublisher(self.dispatcher, settings)
     self.dispatcher.start()
     self.publisher.start()
     time.sleep(7)
     self.publisher.abort()
     self.dispatcher.abort()
     messages = self.subscriber.retrieveMessages()
     msgtopics = [msg.topic for msg in messages]
     for topic in self.topics:
         assert topic in msgtopics
 def setup(self):
     self.folder = translatepath('special://addon/resources/lib/tests')
     setPathRW(self.folder)
     watchdogSettings = [{
         'folder': self.folder,
         'patterns': '*',
         'ignore_patterns': '',
         'ignore_directories': True,
         'recursive': False,
         'key': 'E1'
     }]
     self.dispatcher = Dispatcher()
     self.subscriber = testSubscriber()
     self.topic = Topic('onFileSystemChange', 'E1')
     self.subscriber.addTopic(self.topic)
     self.dispatcher.addSubscriber(self.subscriber)
     settings = Settings()
     flexmock(settings, getWatchdogSettings=watchdogSettings)
     self.publisher = WatchdogPublisher(self.dispatcher, settings)
     self.dispatcher.start()
 def setup(self):
     self.folder = translatepath('special://addon/resources/lib/tests')
     watchdogStartupSettings = [{
         'ws_folder': self.folder,
         'ws_patterns': '*',
         'ws_ignore_patterns': '',
         'ws_ignore_directories': True,
         'ws_recursive': False,
         'key': 'E1'
     }]
     self.saveduserpickle = WatchdogStartup.getPickle()
     self.dispatcher = Dispatcher()
     self.subscriber = testSubscriber()
     self.topic = Topic('onStartupFileChanges', 'E1')
     self.subscriber.addTopic(self.topic)
     self.dispatcher.addSubscriber(self.subscriber)
     settings = Settings()
     flexmock(settings, getWatchdogStartupSettings=watchdogStartupSettings)
     self.publisher = WatchdogStartup(self.dispatcher, settings)
     self.dispatcher.start()
Exemple #15
0
    def __init__(self, plugin, sortmethods=None):
        Film.__init__(self)
        self.plugin = plugin
        self.handle = plugin.addon_handle
        self.settings = Settings()
        # define sortmethod for films
        # all av. sort method and put the default sortmethod on first place to be used by UI
        allSortMethods = [
            xbmcplugin.SORT_METHOD_TITLE, xbmcplugin.SORT_METHOD_DATE,
            xbmcplugin.SORT_METHOD_DATEADDED, xbmcplugin.SORT_METHOD_SIZE,
            xbmcplugin.SORT_METHOD_DURATION
        ]
        if sortmethods is not None:
            self.sortmethods = sortmethods
        else:
            method = allSortMethods[0]
            allSortMethods[0] = allSortMethods[self.settings.filmSortMethod]
            allSortMethods[self.settings.filmSortMethod] = method
            self.sortmethods = allSortMethods

        self.showshows = False
        self.showchannels = False
 def testIntervalAlarm(self):
     self.topics = [Topic('onIntervalAlarm', 'E1')]
     xsettings = [{'hours': 0, 'minutes': 0, 'seconds': 10, 'key': 'E1'}]
     settings = Settings()
     self.dispatcher = Dispatcher()
     self.subscriber = MockSubscriber()
     flexmock(settings, getEventsByType=xsettings)
     self.publisher = SchedulePublisher(self.dispatcher, settings)
     self.publisher.dailyAlarms = []
     self.publisher.sleep = time.sleep
     self.publisher.sleepinterval = 1
     self.subscriber.testq = Queue.Queue()
     self.subscriber.addTopic(self.topics[0])
     self.dispatcher.addSubscriber(self.subscriber)
     self.dispatcher.start()
     self.publisher.start()
     self.subscriber.waitForMessage(count=1, timeout=20)
     self.publisher.abort()
     self.dispatcher.abort()
     messages = self.subscriber.retrieveMessages()
     msgtopics = [msg.topic for msg in messages]
     for topic in self.topics:
         assert topic in msgtopics
 def testLogRegex(self):
     self.topics = [Topic('onLogRegex', 'E1')]
     xsettings = [{
         'matchIf': 'kodi_callbacks',
         'rejectIf': '',
         'eventId': 'E1'
     }]
     settings = Settings()
     flexmock(settings, getLogRegexes=xsettings)
     flexmock(settings, general={'LogFreq': 100})
     self.publisher = LogPublisher(self.dispatcher, settings)
     try:
         os.remove(testLog.fn)
     except OSError:
         pass
     finally:
         with open(testLog.fn, 'w') as f:
             f.writelines('')
     self.subscriber.addTopic(self.topics[0])
     self.dispatcher.addSubscriber(self.subscriber)
     self.dispatcher.start()
     self.publisher.start()
     t = threading.Thread(target=testLog.logSimulate)
     t.start()
     t.join()
     self.publisher.abort()
     self.dispatcher.abort()
     time.sleep(2)
     try:
         os.remove(testLog.fn)
     except OSError:
         pass
     messages = self.subscriber.retrieveMessages()
     msgtopics = [msg.topic for msg in messages]
     for topic in self.topics:
         assert topic in msgtopics
 def __init__(self):
     super(MediathekView, self).__init__()
     self.settings = Settings()
     self.notifier = Notifier()
     self.database = Store(self.getNewLogger('Store'), self.notifier,
                           self.settings)
Exemple #19
0
 def __init__(self):
     self.proxy = ProxyTCPD()
     self.s = Settings()
     self.s.log('Proxy Bound to 127.0.0.1:{}'.format(self.proxy.port))
     self.proxy_thread = threading.Thread(target=self.proxy.serve_forever)
     self.s.setSetting('proxy', '127.0.0.1:{}'.format(self.proxy.port))
Exemple #20
0
class Plugin(object):
    PLUGIN_ID = xbmcaddon.Addon().getAddonInfo("id")
    PLUGIN_URL = "plugin://{}".format(PLUGIN_ID)
    settings = Settings()

    def __init__(self):
        self._rules = {}
        self.path = urlsplit(sys.argv[0]).path or "/"
        self.handle = int(sys.argv[1])
        self.kwargs = dict(parse_qsl(sys.argv[2].lstrip("?")))
        self.auth = Auth(self)
        self.logger = Logger(self)
        self.routing = Routing(self)
        self.search_history = SearchHistory(self)
        self.main_menu_items = self._main_menu_items()

    def client(self, endpoint):
        return KinoPubClient(self, endpoint)

    def list_item(
        self,
        name,
        label2="",
        iconImage="",
        thumbnailImage="",
        path="",
        poster=None,
        fanart=None,
        video_info=None,
        properties=None,
        addContextMenuItems=False,
        subtitles=None,
    ):
        return ExtendedListItem(
            name,
            label2=label2,
            iconImage=iconImage,
            thumbnailImage=thumbnailImage,
            path=path,
            poster=poster,
            fanart=fanart,
            video_info=video_info,
            properties=properties,
            addContextMenuItems=addContextMenuItems,
            subtitles=subtitles,
            plugin=self,
        )

    def run(self):
        self.routing.dispatch(self.path)

    def _main_menu_items(self):
        return [
            MainMenuItem(
                "Профиль",
                self.routing.build_url("profile"),
                self.routing.build_icon_path("profile"),
                False,
                True,
            ),
            MainMenuItem(
                "Поиск",
                self.routing.build_url("search", "all"),
                self.routing.build_icon_path("search"),
                True,
                self.settings.show_search,
            ),
            MainMenuItem(
                "Закладки",
                self.routing.build_url("bookmarks"),
                self.routing.build_icon_path("bookmarks"),
                True,
                True,
            ),
            MainMenuItem(
                "Я смотрю",
                self.routing.build_url("watching"),
                self.routing.build_icon_path("watching"),
                True,
                True,
            ),
            MainMenuItem(
                "Недосмотренные",
                self.routing.build_url("watching_movies"),
                self.routing.build_icon_path("watching_movies"),
                True,
                True,
            ),
            MainMenuItem(
                "Последние",
                self.routing.build_url("items", "all", "fresh"),
                self.routing.build_icon_path("fresh"),
                True,
                self.settings.show_last,
            ),
            MainMenuItem(
                "Популярные",
                self.routing.build_url("items", "all", "popular"),
                self.routing.build_icon_path("popular"),
                True,
                self.settings.show_popular,
            ),
            MainMenuItem(
                "Горячие",
                self.routing.build_url("items", "all", "hot"),
                self.routing.build_icon_path("hot"),
                True,
                self.settings.show_hot,
            ),
            MainMenuItem(
                self.sorting_title,
                self.routing.build_url("items", "all", "sort"),
                self.routing.build_icon_path("sort"),
                True,
                self.settings.show_sort,
            ),
            MainMenuItem(
                "ТВ",
                self.routing.build_url("tv"),
                self.routing.build_icon_path("tv"),
                True,
                self.settings.show_tv,
            ),
            MainMenuItem(
                "Подборки",
                self.routing.build_url("collections"),
                self.routing.build_icon_path("collections"),
                True,
                self.settings.show_collections,
            ),
            MainMenuItem(
                "Фильмы",
                self.routing.build_url("items", "movies"),
                self.routing.build_icon_path("movies"),
                True,
                self.settings.show_movies,
            ),
            MainMenuItem(
                "Сериалы",
                self.routing.build_url("items", "serials"),
                self.routing.build_icon_path("serials"),
                True,
                self.settings.show_serials,
            ),
            MainMenuItem(
                "ТВ шоу",
                self.routing.build_url("items", "tvshow"),
                self.routing.build_icon_path("tvshows"),
                True,
                self.settings.show_tvshows,
            ),
            MainMenuItem(
                "3D",
                self.routing.build_url("items", "3d"),
                self.routing.build_icon_path("3d"),
                True,
                self.settings.show_3d,
            ),
            MainMenuItem(
                "Концерты",
                self.routing.build_url("items", "concerts"),
                self.routing.build_icon_path("concerts"),
                True,
                self.settings.show_concerts,
            ),
            MainMenuItem(
                "Документальные фильмы",
                self.routing.build_url("items", "documovies"),
                self.routing.build_icon_path("documovies"),
                True,
                self.settings.show_documovies,
            ),
            MainMenuItem(
                "Документальные сериалы",
                self.routing.build_url("items", "docuserials"),
                self.routing.build_icon_path("docuserials"),
                True,
                self.settings.show_docuserials,
            ),
        ]

    @property
    def sorting_title(self):
        return "По {} {}".format(self.settings.sort_by,
                                 self.settings.sort_direction)

    @property
    def sorting_params(self):
        sorting = {
            "дате обновления": "updated",
            "дате добавления": "created",
            "году": "year",
            "названию": "title",
            "рейтингу": "rating",
            "Кинопоиску": "kinopoisk_rating",
            "IMDB": "imdb_rating",
            "просмотрам": "views",
            "зрителям": "watchers",
        }
        direction = {"по убыванию": "-", "по возрастанию": ""}
        return {
            "sort":
            "{}{}".format(sorting[self.settings.sort_by],
                          direction[self.settings.sort_direction])
        }
def service():
    # アドオン
    addon = xbmcaddon.Addon()
    # 設定ファイルを初期化
    settings = Settings()
    # 設定
    executable_path = addon.getSetting('executable_path')
    extension_path = addon.getSetting('extension_path')
    email = addon.getSetting('email')
    password = addon.getSetting('password')
    talk = addon.getSetting('talk')
    if executable_path and extension_path and email and password:
        # キーを初期化
        secret = Secret(renew=True)
        # LINEにログイン
        line = Line(executable_path, extension_path)
        if line.open(email, password):
            # トークを選択
            if line.select(talk):
                # 着信を監視
                hash = ''
                messages = []
                monitor = Monitor(line)
                while not monitor.abortRequested():
                    # 停止を待機
                    if monitor.waitForAbort(monitor.interval): break
                    # キーをチェック
                    if not secret.check(): break
                    # 表示されているメッセージを取得
                    messages = line.watch()
                    if messages:
                        # 差分の有無をチェック
                        hash1 = hashlib.md5(str(messages)).hexdigest()
                        # 差分があれば通知
                        if hash != hash1:
                            status = Cache('json').write_json(messages)
                            if status is not None:
                                # アドオン設定
                                cec = xbmcaddon.Addon().getSetting('cec')
                                # 既存データがある場合は画面を切り替えて通知する
                                if status > 0:
                                    # 画面切り替え
                                    if cec == 'true':
                                        xbmc.executebuiltin(
                                            'CECActivateSource')
                                    # 通知
                                    m = messages[-1]
                                    if m['ttl']:
                                        notify('%s > %s' %
                                               (m['ttl'], m['msg']))
                                    else:
                                        notify(m['msg'])
                                # 既存データの有無にかかわらず差分がある場合はとりあえず表示する
                                folderpath = 'plugin://%s/' % addon.getAddonInfo(
                                    'id')
                                if xbmc.getInfoLabel('Container.FolderPath'
                                                     ).find(folderpath) == 0:
                                    xbmc.executebuiltin(
                                        'Container.Update(%s,replace)' %
                                        folderpath)
                                elif cec == 'true':
                                    xbmc.executebuiltin(
                                        'RunAddon(%s)' %
                                        addon.getAddonInfo('id'))
                        # ハッシュを記録
                        hash = hash1
                    else:
                        # メッセージが取得できない
                        break
        # LINEを終了
        line.close()
        # キーをクリア
        secret.clear()
                from resources.lib.utils.updateaddon import UpdateAddon

                ua = UpdateAddon(addonid)
                ua.installFromZip(zipfn, updateonly=False, dryrun=dryrun)

        elif sys.argv[1] == 'lselector':
            from resources.lib.utils.selector import selectordialog

            try:
                result = selectordialog(sys.argv[2:])
            except (SyntaxError, TypeError) as e:
                xbmc.log(msg='Error: %s' % str(e), level=xbmc.LOGERROR)

        elif sys.argv[1] == 'logsettings':
            KodiLogger.setLogLevel(KodiLogger.LOGNOTICE)
            settings = Settings()
            settings.getSettings()
            settings.logSettings()
            dialog = xbmcgui.Dialog()
            msg = _('Settings written to log')
            dialog.ok(_('Kodi Callbacks'), msg)

        elif branch != 'master' and sys.argv[1] == 'checkupdate':
            try:
                from resources.lib.utils.githubtools import processargs
            except ImportError:
                pass
            else:
                processargs(sys.argv)

        else:
Exemple #23
0
class Plugin(object):
    PLUGIN_ID = xbmcaddon.Addon().getAddonInfo("id")
    PLUGIN_URL = "plugin://{}".format(PLUGIN_ID)
    settings = Settings()

    def __init__(self):
        self._rules = {}
        self.path = urlsplit(sys.argv[0]).path or "/"
        self.handle = int(sys.argv[1])
        self.kwargs = dict(parse_qsl(sys.argv[2].lstrip("?")))
        self.auth = Auth(self)
        self.logger = Logger(self)
        self.routing = Routing(self)
        self.main_menu_items = self._main_menu_items()

    def client(self, endpoint):
        return KinoPubClient(self, endpoint)

    def list_item(
        self,
        name,
        label2="",
        iconImage="",
        thumbnailImage="",
        path="",
        poster=None,
        video_info=None,
        properties=None,
        addContextMenuItems=False,
        subtitles=None,
    ):
        return ExtendedListItem(
            name,
            label2=label2,
            iconImage=iconImage,
            thumbnailImage=thumbnailImage,
            path=path,
            poster=poster,
            video_info=video_info,
            properties=properties,
            addContextMenuItems=addContextMenuItems,
            subtitles=subtitles,
            plugin=self,
        )

    def run(self):
        self.routing.dispatch(self.path)

    def _main_menu_items(self):
        return [
            MainMenuItem(
                "Профиль",
                self.routing.build_url("profile"),
                self.routing.build_icon_path("profile"),
                False,
                True,
            ),
            MainMenuItem(
                "Поиск",
                self.routing.build_url("search", "all"),
                self.routing.build_icon_path("search"),
                False,
                self.settings.show_search,
            ),
            MainMenuItem(
                "Закладки",
                self.routing.build_url("bookmarks"),
                self.routing.build_icon_path("bookmarks"),
                True,
                True,
            ),
            MainMenuItem(
                "Я смотрю",
                self.routing.build_url("watching"),
                self.routing.build_icon_path("watching"),
                True,
                True,
            ),
            MainMenuItem(
                "Недосмотренные",
                self.routing.build_url("watching_movies"),
                self.routing.build_icon_path("watching_movies"),
                True,
                True,
            ),
            MainMenuItem(
                "Последние",
                self.routing.build_url("items", "all", "fresh"),
                self.routing.build_icon_path("fresh"),
                True,
                self.settings.show_last,
            ),
            MainMenuItem(
                "Популярные",
                self.routing.build_url("items", "all", "popular"),
                self.routing.build_icon_path("popular"),
                True,
                self.settings.show_popular,
            ),
            MainMenuItem(
                "Горячие",
                self.routing.build_url("items", "all", "hot"),
                self.routing.build_icon_path("hot"),
                True,
                self.settings.show_hot,
            ),
            MainMenuItem(
                "ТВ",
                self.routing.build_url("tv"),
                self.routing.build_icon_path("tv"),
                True,
                self.settings.show_tv,
            ),
            MainMenuItem(
                "Подборки",
                self.routing.build_url("collections"),
                self.routing.build_icon_path("collections"),
                True,
                self.settings.show_collections,
            ),
            MainMenuItem(
                "Фильмы",
                self.routing.build_url("items", "movies"),
                self.routing.build_icon_path("movies"),
                True,
                self.settings.show_movies,
            ),
            MainMenuItem(
                "Сериалы",
                self.routing.build_url("items", "serials"),
                self.routing.build_icon_path("serials"),
                True,
                self.settings.show_serials,
            ),
            MainMenuItem(
                "ТВ шоу",
                self.routing.build_url("items", "tv_shows"),
                self.routing.build_icon_path("tvshows"),
                True,
                self.settings.show_tvshows,
            ),
            MainMenuItem(
                "3D",
                self.routing.build_url("items", "3d"),
                self.routing.build_icon_path("3d"),
                True,
                self.settings.show_3d,
            ),
            MainMenuItem(
                "Концерты",
                self.routing.build_url("items", "concerts"),
                self.routing.build_icon_path("concerts"),
                True,
                self.settings.show_concerts,
            ),
            MainMenuItem(
                "Документальные фильмы",
                self.routing.build_url("items", "documovies"),
                self.routing.build_icon_path("documovies"),
                True,
                self.settings.show_documovies,
            ),
            MainMenuItem(
                "Документальные сериалы",
                self.routing.build_url("items", "docuserials"),
                self.routing.build_icon_path("docuserials"),
                True,
                self.settings.show_docuserials,
            ),
        ]
Exemple #24
0
class Plugin(object):
    PLUGIN_ID = xbmcaddon.Addon().getAddonInfo("id")
    PLUGIN_URL = f"plugin://{PLUGIN_ID}"
    settings = Settings()

    def __init__(self):
        self._rules = {}
        self.path = urlsplit(sys.argv[0]).path or "/"
        self.handle = int(sys.argv[1])
        self.kwargs = dict(parse_qsl(sys.argv[2].lstrip("?")))
        self.auth = Auth(self)
        self.logger = Logger(self)
        self.routing = Routing(self)
        self.search_history = SearchHistory(self)
        self.main_menu_items = self._main_menu_items()
        self.items = ItemsCollection(self)

    def client(self, endpoint):
        return KinoPubClient(self, endpoint)

    def list_item(
        self,
        name,
        label2="",
        iconImage="",
        thumbnailImage="",
        path="",
        poster=None,
        fanart=None,
        video_info=None,
        properties=None,
        addContextMenuItems=False,
        subtitles=None,
    ):
        return ExtendedListItem(
            name,
            label2=label2,
            iconImage=iconImage,
            thumbnailImage=thumbnailImage,
            path=path,
            poster=poster,
            fanart=fanart,
            video_info=video_info,
            properties=properties,
            addContextMenuItems=addContextMenuItems,
            subtitles=subtitles,
            plugin=self,
        )

    def run(self):
        self.routing.dispatch(self.path)

    def _main_menu_items(self):
        return [
            MainMenuItem(
                "Профиль",
                self.routing.build_url("profile/"),
                self.routing.build_icon_path("profile"),
                False,
                True,
            ),
            MainMenuItem(
                "Поиск",
                self.routing.build_url("search", "all/"),
                self.routing.build_icon_path("search"),
                True,
                self.settings.show_search,
            ),
            MainMenuItem(
                "Закладки",
                self.routing.build_url("bookmarks/"),
                self.routing.build_icon_path("bookmarks"),
                True,
                True,
            ),
            MainMenuItem(
                "Я смотрю",
                self.routing.build_url("watching/"),
                self.routing.build_icon_path("watching"),
                True,
                True,
            ),
            MainMenuItem(
                "Недосмотренные",
                self.routing.build_url("watching_movies/"),
                self.routing.build_icon_path("watching_movies"),
                True,
                True,
            ),
            MainMenuItem(
                "Последние",
                self.routing.build_url("items", "all", "fresh/"),
                self.routing.build_icon_path("fresh"),
                True,
                self.settings.show_last,
            ),
            MainMenuItem(
                "Популярные",
                self.routing.build_url("items", "all", "popular/"),
                self.routing.build_icon_path("popular"),
                True,
                self.settings.show_popular,
            ),
            MainMenuItem(
                "Горячие",
                self.routing.build_url("items", "all", "hot/"),
                self.routing.build_icon_path("hot"),
                True,
                self.settings.show_hot,
            ),
            MainMenuItem(
                self.sorting_title,
                self.routing.build_url("items", "all", "sort/"),
                self.routing.build_icon_path("sort"),
                True,
                self.settings.show_sort,
            ),
            MainMenuItem(
                "ТВ",
                self.routing.build_url("tv/"),
                self.routing.build_icon_path("tv"),
                True,
                self.settings.show_tv,
            ),
            MainMenuItem(
                "Подборки",
                self.routing.build_url("collections/"),
                self.routing.build_icon_path("collections"),
                True,
                self.settings.show_collections,
            ),
            MainMenuItem(
                "Фильмы",
                self.routing.build_url("items", "movies/"),
                self.routing.build_icon_path("movies"),
                True,
                self.settings.show_movies,
            ),
            MainMenuItem(
                "Сериалы",
                self.routing.build_url("items", "serials/"),
                self.routing.build_icon_path("serials"),
                True,
                self.settings.show_serials,
            ),
            MainMenuItem(
                "ТВ шоу",
                self.routing.build_url("items", "tvshow/"),
                self.routing.build_icon_path("tvshows"),
                True,
                self.settings.show_tvshows,
            ),
            MainMenuItem(
                "3D",
                self.routing.build_url("items", "3d/"),
                self.routing.build_icon_path("3d"),
                True,
                self.settings.show_3d,
            ),
            MainMenuItem(
                "Концерты",
                self.routing.build_url("items", "concerts/"),
                self.routing.build_icon_path("concerts"),
                True,
                self.settings.show_concerts,
            ),
            MainMenuItem(
                "Документальные фильмы",
                self.routing.build_url("items", "documovies/"),
                self.routing.build_icon_path("documovies"),
                True,
                self.settings.show_documovies,
            ),
            MainMenuItem(
                "Документальные сериалы",
                self.routing.build_url("items", "docuserials/"),
                self.routing.build_icon_path("docuserials"),
                True,
                self.settings.show_docuserials,
            ),
        ]

    @property
    def sorting_title(self):
        return f"По {self.settings.sort_by} {self.settings.sort_direction}"

    @property
    def sorting_params(self):
        sorting = {
            "дате обновления": "updated",
            "дате добавления": "created",
            "году": "year",
            "названию": "title",
            "рейтингу": "rating",
            "Кинопоиску": "kinopoisk_rating",
            "IMDB": "imdb_rating",
            "просмотрам": "views",
            "зрителям": "watchers",
        }
        direction = {"по убыванию": "-", "по возрастанию": ""}
        return {
            "sort": f"{sorting[self.settings.sort_by]}{direction[self.settings.sort_direction]}"
        }

    def clear_window_property(self):
        xbmcgui.Window(10000).clearProperty("video.kino.pub-playback_data")

    def set_window_property(self, value):
        self.clear_window_property()
        pickled = codecs.encode(pickle.dumps(value), "base64").decode("utf-8")
        xbmcgui.Window(10000).setProperty("video.kino.pub-playback_data", pickled)

    def get_window_property(self, item_id):
        try:
            data = xbmcgui.Window(10000).getProperty("video.kino.pub-playback_data").encode("utf-8")
            items = pickle.loads(codecs.decode(data, "base64"))
        except EOFError:
            items = {}
        item = items.get(int(item_id), {})
        if item:
            item._plugin = self
        return item