示例#1
0
class AutoSwitch(threading.Thread):
    def __init__(self, config):
        super(AutoSwitch, self).__init__(name='AutoSwitch')
        self.logger = Log()
        self.config = config

    def get_interval(self):
        return int(self.config.get('interval')) * 60 * 60

    def change(self):
        rootdir = os.path.expanduser('~/.local/share/bingwallpaper/')
        while True:
            for parent, dirnames, filenames in os.walk(rootdir):
                random.shuffle(filenames)
                for filename in filenames:
                    begin = time.time()
                    end = begin
                    while self.get_interval() > (end - begin):
                        time.sleep(3600)
                        end = time.time()

                    os.system(
                        "gsettings set org.gnome.desktop.background picture-uri file://"
                        + os.path.join(parent, filename).replace(' ', '\ '))
                    self.logger.log("正在设置壁纸,壁纸来自:" +
                                    os.path.join(parent, filename))

    def run(self):
        self.change()
示例#2
0
    def __init__(self):
        self.logger = Log()
        dir = os.path.expanduser('~/.config/bingwallpaper/')
        if not os.path.exists(dir):
            try:
                self.logger.log('mkdir ' + dir)
                os.makedirs(dir)
            except:
                self.logger.log('\tError create dir' + dir)
        path = dir + "pic.db"

        exist = os.path.exists(path)

        self.conn = sqlite3.connect(path)

        if not exist:
            self.create_table()
示例#3
0
    def __init__(self, conf, app):
        super(MyWindow, self).__init__()

        self.app = app

        self.logger = Log()

        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)
        self.setWindowTitle("BingWallPaper setting")
        self.resize(300, 200)
        self.setFixedSize(300, 200)
        self.setWindowOpacity(0.95)
        self.center()

        self.conf = conf
        self.set_label()
        self._set_systray()

        self.aboutWindow = AboutWindow()
示例#4
0
 def __init__(self):
     super(BingImg, self).__init__(name='BingImg')
     self.logger = Log()
示例#5
0
class BingImg(threading.Thread):
    def __init__(self):
        super(BingImg, self).__init__(name='BingImg')
        self.logger = Log()

    def run(self):
        self.down_img()

    def download(self, url, model):
        pattern = re.compile(r'[^/]*$')
        match = pattern.search(url)
        if match:
            file = match.group()
        else:
            return

        dir = os.path.expanduser('~/.local/share/bingwallpaper/')
        if not os.path.exists(dir):
            try:
                os.makedirs(dir)
                os.path.exists(dir)
            except:
                self.logger.error('Error create dir' + dir)

        dest = dir + file
        try:
            urllib.request.urlretrieve(url, dest)
            self.logger.info('Save image ' + url + ' to dir ' + dest)

            model.save(time.strftime('%Y-%m-%d'), url, file)
            os.system(
                "gsettings set org.gnome.desktop.background picture-uri file://"
                + dest.replace(' ', '\ '))
        except:
            self.logger.error('Error retrieving the Url:' + url +
                              ', to dest:' + dest)

    def parse_img_url(self):
        url = 'https://www.bing.com/'
        data = urllib.request.urlopen(url)

        content = data.read()
        # print content
        pattern = re.compile(r";g_img=\{url:\s*['\"]([^'\"]*?)['\"]")
        # print pattern.pattern
        match = pattern.search(content)
        if match:
            img = match.group(1).replace('\\', '')
            if not img.startswith('http://') and not img.startswith(
                    'https://'):
                img = url + img
            self.logger.info('img url: ' + img)
            return img
        else:
            self.logger.error('Get img url failed!')
            return None

    def parse_img_url_from_json(self):
        url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'
        data = urllib.request.urlopen(url).read().decode('utf-8')
        ret = json.loads(data)
        imgUrl = ret['images'][0]['url']

        return imgUrl if imgUrl.startswith(
            'http') else 'https://cn.bing.com' + imgUrl

    def down_img(self):
        while True:
            model = Model()
            item = model.getOneByDay(time.strftime('%Y-%m-%d'))
            if not item:
                url = self.parse_img_url_from_json()
                # url = self.parse_img_url()
                if url:
                    self.download(url, model)

            model.close()
            del model
            time.sleep(60 * 60 * 8)
示例#6
0
 def __init__(self, config):
     super(AutoSwitch, self).__init__(name='AutoSwitch')
     self.logger = Log()
     self.config = config
示例#7
0
class Model:
    def __init__(self):
        self.logger = Log()
        dir = os.path.expanduser('~/.config/bingwallpaper/')
        if not os.path.exists(dir):
            try:
                self.logger.log('mkdir ' + dir)
                os.makedirs(dir)
            except:
                self.logger.log('\tError create dir' + dir)
        path = dir + "pic.db"

        exist = os.path.exists(path)

        self.conn = sqlite3.connect(path)

        if not exist:
            self.create_table()

    def getOneByDay(self, day):
        sql = 'SELECT * FROM pic WHERE day = ?'
        d = (day, )
        self.logger.log('execute sql: [{}], params:[{}]'.format(sql, d))
        cursor = self.conn.cursor()
        cursor.execute(sql, d)
        r = cursor.fetchall()
        cursor.close()
        if len(r) > 0:
            self.logger.log(r[0])
            return r[0]
        else:
            return None

    def save(self, day, url, file):
        cursor = self.conn.cursor()
        sql = '''INSERT INTO pic (day, url, file) VALUES (?, ?, ?)'''
        data = (day, url, file)
        self.logger.log('execute sql:[{}], params:[{}]'.format(sql, data))
        cursor.execute(sql, data)
        self.conn.commit()
        cursor.close()

    def create_table(self):
        cursor = self.conn.cursor()

        sql = '''CREATE TABLE `pic` (
        `day` varchar(10) NOT NULL,
        `url` varchar(255) NOT NULL,
        `file` varchar(255) NOT NULL,
        `time` TimeStamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`day`)
        );'''

        cursor.execute(sql)

        sql = '''CREATE TABLE `config` (
            `key` TEXT NOT NULL,
            `value` INTEGER NOT NULL,
            `desc` TEXT NOT NULL,
            PRIMARY KEY (`key`)
            );'''

        cursor.execute(sql)

        sql = '''INSERT INTO `config` (`key`, `value`, `desc`) VALUES
            ("autorun", 1, "auto run"),
            ("interval", 24, "interval time, unit: hour");
            '''
        cursor.execute(sql)

        self.conn.commit()
        cursor.close()

    def close(self):
        if self.conn:
            try:
                self.conn.close()
            finally:
                self.conn.close()

    def load_conf(self):
        sql = 'SELECT * FROM config'
        self.logger.log('execute sql: [{}]'.format(sql))

        self.conn.row_factory = sqlite3.Row

        cursor = self.conn.cursor()
        cursor.execute(sql)
        r = cursor.fetchall()
        cursor.close()
        if len(r) > 0:
            return r
        else:
            return None

    def update_conf(self, key, value):
        cursor = self.conn.cursor()

        sql = '''UPDATE `config` SET `value`= ? WHERE `key`= ?'''
        data = (value, key)
        self.logger.log('execute sql:[{}], params:[{}]'.format(sql, data))

        cursor.execute(sql, data)
        self.conn.commit()
        cursor.close()
示例#8
0
class MyWindow(QtWidgets.QWidget):
    def __init__(self, conf, app):
        super(MyWindow, self).__init__()

        self.app = app

        self.logger = Log()

        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)
        self.setWindowTitle("BingWallPaper setting")
        self.resize(300, 200)
        self.setFixedSize(300, 200)
        self.setWindowOpacity(0.95)
        self.center()

        self.conf = conf
        self.set_label()
        self._set_systray()

        self.aboutWindow = AboutWindow()

    def set_label(self):
        vbox = QtWidgets.QVBoxLayout()

        time_label = QtWidgets.QLabel(_('Interval(hour):'))
        time_label.setAlignment(QtCore.Qt.AlignCenter)

        select = QtWidgets.QComboBox(self)
        select.addItem("1", 1)
        select.addItem("2", 2)
        select.addItems(
            ["3", "4", "6", "8", "10", "24"])
        select.setCurrentIndex(self.conf.get('interval') - 1)

        # self.connect(select, QtCore.pyqtSignal('activated(QString)'), self.on_select)
        select.activated[str].connect(self.on_select)

        autorun_label = QtWidgets.QLabel(_('Auto startup:'))
        autorun_label.setAlignment(QtCore.Qt.AlignCenter)
        self.check = QtWidgets.QCheckBox('')
        self.check.setChecked(self.conf.get('autorun') == 1)
        # self.connect(self.check, QtCore.pyqtSignal('stateChanged(int)'), self.on_check)
        self.check.stateChanged.connect(self.on_check)

        grid_layout = QtWidgets.QGridLayout()

        grid_layout.addWidget(time_label, 0, 0)
        grid_layout.addWidget(select, 0, 1)

        grid_layout.addWidget(autorun_label, 1, 0)
        grid_layout.addWidget(self.check, 1, 1)

        vbox.addLayout(grid_layout)

        self.setLayout(vbox)

        # label.setAlignment(QtCore.Qt.AlignCenter)
        # self.setCentralWidget(label)

    def _set_systray(self):
        menu = QtWidgets.QMenu(self)  # 生成一个系统托盘处的菜单.就一个Quit

        browserAction = QtWidgets.QAction("&" + _("Browser"), self)
        # self.connect(browserAction, QtCore.pyqtSignal("triggered()"), self.open)
        browserAction.triggered.connect(self.open)
        menu.addAction(browserAction)

        settingAction = QtWidgets.QAction("&"+_("setting"), self)
        # self.connect(settingAction, QtCore.pyqtSignal("triggered()"), self.show)
        settingAction.triggered.connect(self.show)
        menu.addAction(settingAction)

        aboutAction = QtWidgets.QAction("&"+_("about"), self)
        # self.connect(aboutAction, QtCore.pyqtSignal("triggered()"), self.about)
        aboutAction.triggered.connect(self.about)
        menu.addAction(aboutAction)

        quitAction = QtWidgets.QAction("&"+_("Quit"), self)
        # self.connect(quitAction, QtCore.pyqtSignal("triggered()"), self.app.quit)
        quitAction.triggered.connect(self.app.quit)
        menu.addAction(quitAction)

        self.icon = QtWidgets.QSystemTrayIcon(QtGui.QIcon('../resource/index.png'), self)  # 加载系统托盘处的图标
        self.icon.setToolTip(u"A Alert Coming...")
        self.icon.setContextMenu(menu)
        # self.connect(self.icon, QtCore.pyqtSignal('activated(QSystemTrayIcon::ActivationReason)'), self.__icon_activated)
        self.icon.activated.connect(self.__icon_activated)
        self.icon.show()

    def on_check(self, check):
        self.logger.info('autorun: ' + str(check))
        if self.check.isChecked():
            self.conf.update('autorun', 1)
            os.system("cp /usr/share/applications/BingWallPaper.desktop " + os.path.expanduser('~') + "/.config/autostart/")
        else:
            self.conf.update('autorun', 0)
            os.system("rm -f " + os.path.expanduser('~') + "/.config/autostart/BingWallPaper.desktop")

    def on_select(self, text):
        self.logger.info('interval: ' + text)
        self.conf.update('interval', str(text))

    def closeEvent(self, event):
        self.hide()
        event.ignore()

    def __icon_activated(self, reason):
        if reason == QtWidgets.QSystemTrayIcon.DoubleClick:
            self.show()

    def center(self):
        qr = self.frameGeometry()  # 返回代表窗口框架结构的矩形
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()  # 返回屏幕(可显示区域)的中心点
        qr.moveCenter(cp)  # 将与窗口同大的矩形移动到屏幕中央
        self.move(qr.topLeft())  # 将主窗口移动到已定位的矩形处,QWidget的移动以左上角为基准点

    def about(self):
        # if not hasattr(self.__class__, 'aboutWindow'):
        #     self.aboutWindow = AboutWindow(self)
        self.aboutWindow.show()

    def open(self):
        QDesktopServices.openUrl(QUrl('file:///' + os.path.expanduser('~') + '/.local/share/bingwallpaper'))