示例#1
0
    def install(self, filename):
        issrc = False
        if filename.find('src') > 0:
            issrc = True

        f = zipfile.ZipFile(filename, 'r')
        for info in f.infolist():
            if info.file_size == 0:
                continue
            filepath = info.filename
            if not issrc and filepath.find('/.hg/') > 0:
                continue
            if filepath.endswith('EasyAccout.conf') or filepath.endswith('EasyAccout.db'):
                continue
            pos = filepath.find('/')
            newpath = os.path.join(self.home, filepath[pos+1:].replace('/', os.sep))
            newdir = os.path.dirname(newpath)

            if not os.path.isdir(newdir):
                os.mkdirs(newdir)

            newf = open(newpath, 'wb')
            newf.write(f.read(filepath))
            newf.close()

            logfile.info('install:', info.filename, 'to:', newpath)
        f.close()
示例#2
0
    def OnFileSaveAs(self, event):
        dlg = wx.FileDialog(self,
                            message=_("Account save as..."),
                            defaultDir=os.getcwd(),
                            defaultFile="",
                            wildcard=_("YouMoney Database (*.db)|*.db"),
                            style=wx.FD_SAVE)
        dlg.SetFilterIndex(2)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            logfile.info("save file:", path)
            if not path.endswith('.db'):
                path += ".db"

            if os.path.isfile(path):
                wx.MessageBox(_('File exist'), _('Can not save account file'),
                              wx.OK | wx.ICON_INFORMATION)
                return
            try:
                shutil.copyfile(self.conf['lastdb'], path)
            except Exception as e:
                wx.MessageBox(
                    _('Save account failture:') + str(e),
                    _('Can not save account file'),
                    wx.OK | wx.ICON_INFORMATION)
                return

        dlg.Destroy()
示例#3
0
    def install(self, filename):
        issrc = False
        if filename.find('src') > 0:
            issrc = True

        f = zipfile.ZipFile(filename, 'r')
        for info in f.infolist():
            if info.file_size == 0:
                continue
            filepath = info.filename
            if not issrc and filepath.find('/.hg/') > 0:
                continue
            if filepath.endswith('youmoney.conf') or filepath.endswith(
                    'youmoney.db'):
                continue
            pos = filepath.find('/')
            newpath = os.path.join(self.home,
                                   filepath[pos + 1:].replace('/', os.sep))
            newdir = os.path.dirname(newpath)

            if not os.path.isdir(newdir):
                os.makedirs(newdir)

            newf = open(newpath, 'wb')
            newf.write(f.read(filepath))
            newf.close()

            logfile.info('install:', info.filename, 'to:', newpath)
        f.close()
示例#4
0
    def OnFileNew(self, event):
        dlg = wx.FileDialog(self,
                            message=_("New account file save..."),
                            defaultDir=os.getcwd(),
                            defaultFile="",
                            wildcard=_("YouMoney Database (*.db)|*.db"),
                            style=wx.FD_SAVE)
        dlg.SetFilterIndex(2)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            logfile.info("save file:", path)
            if not path.endswith('.db'):
                path += ".db"

            if os.path.isfile(path):
                wx.MessageBox(_('File exist'), _('Can not save account file'),
                              wx.OK | wx.ICON_INFORMATION)
                return

            self.db.close()
            self.initdb(path)
            self.reload()
            self.conf['lastdb'] = path
            self.conf.dump()

            self.conf.iscreate = True
            self.initcate()

            self.SetStatusText(_('Database file: ') + self.conf['lastdb'], 0)

        dlg.Destroy()
示例#5
0
    def openinfo(self):
        socket.setdefaulttimeout(30)
        updatefile = ['', '']
        num = 0
        for url in updatefile:
            self.callback.Update(50 * num, _('Download update.txt') + '...')
            logfile.info('get:', url)
            try:
                op = urllib2.urlopen(url)
                lines = op.readlines()
            except:
                logfile.info(traceback.format_exc())
                num += 1
                continue
            #logfile.info(lines)

            for line in lines:
                line = line.strip()
                if not line:
                    continue
                if line.startswith('#'):
                    continue

                parts = line.split('\t')
                self.info[parts[0]] = parts[1]

            return

        raise IOError, 'get update.txt error!'
        self.callback.Update(100)
示例#6
0
    def openinfo(self):
        socket.setdefaulttimeout(30)
        updatefile = [
            'http://www.pythonid.com/youmoney/update.txt',
            'http://youmoney.googlecode.com/files/update.txt'
        ]  # TODO: to be  updated
        num = 0
        for url in updatefile:
            self.callback.Update(50 * num, _('Download update.txt') + '...')
            logfile.info('get:', url)
            try:
                op = urllib.request.urlopen(url)
                lines = op.readlines()
            except:
                logfile.info(traceback.format_exc())
                num += 1
                continue
            # logfile.info(lines)

            for line in lines:
                line = line.strip()
                if not line:
                    continue
                if line.startswith('#'):
                    continue

                parts = line.split('\t')
                self.info[parts[0]] = parts[1]

            return

        raise IOError('get update.txt error!')
示例#7
0
    def load(self):
        self.list.ClearAll()
        self.init()

        sql = "select * from recycle order by id"
        logfile.info(sql)
        rets = self.parent.parent.db.query(sql)
        if rets:
            for row in rets:
                try:
                    cate = self.parent.parent.category.catemap(row['type'], row['category'])
                    typestr = storage.catetypes[row['type']]
                except:
                    sql = "delete from recycle where id=" + str(row['id'])
                    self.parent.parent.db.execute(sql)
                    continue
                item = self.list.InsertItem(0, typestr)
                # self.list.SetStringItem(item, 0, storage.catetypes[row['type']])
                self.list.SetItem(item, 1, cate)
                self.list.SetItem(item, 2, str(row['num']))
                self.list.SetItem(item, 3, storage.payways[row['payway']])
                self.list.SetItem(item, 4, storage.cycles[row['addtime']])
                self.list.SetItem(item, 5, row['explain'])

                self.list.SetItemData(item, row['id'])
示例#8
0
    def openinfo(self):
        socket.setdefaulttimeout(30)
        updatefile = ['', 
                      '']
        num = 0
        for url in updatefile:
            self.callback.Update(50 * num, _('Download update.txt') + '...')
            logfile.info('get:', url)
            try:
                op = urllib2.urlopen(url)
                lines = op.readlines()
            except:
                logfile.info(traceback.format_exc())
                num += 1
                continue
            #logfile.info(lines)

            for line in lines:
                line = line.strip()
                if not line:
                    continue
                if line.startswith('#'):
                    continue
                
                parts = line.split('\t')
                self.info[parts[0]] = parts[1]
             
            return
        
        raise IOError, 'get update.txt error!'
        self.callback.Update(100)
示例#9
0
    def OnFileImportData(self, event):
        dlg = dialogs.ImportDataDialog(self)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            if not path:
                dlg.Destroy()
                return

            exp = export.DataImport(self.db, 'gbk')
            try:
                idlg = wx.ProgressDialog(_('Importing...'),
                                         _('Waiting for importing.'),
                                         maximum=100,
                                         parent=self,
                                         style=wx.PD_APP_MODAL
                                         | wx.PD_ELAPSED_TIME
                                         | wx.PD_REMAINING_TIME)
                exp.itemdata(path, idlg)
                idlg.Destroy()
            except Exception as e:
                logfile.info(traceback.format_exc())
                wx.MessageBox(str(e), _('Import Error:'),
                              wx.OK | wx.ICON_INFORMATION)
            else:
                wx.MessageBox(_('Import complete!'), _('Information'),
                              wx.OK | wx.ICON_INFORMATION)
            self.reload()

        dlg.Destroy()
示例#10
0
def check(frame):
    try:
        up = Update()
        ver = up.update()
        if ver:
            evt = event.UpdateNotifyEvent(version=ver)
            wx.PostEvent(frame, evt)
    except Exception as e:
        logfile.info(e)
示例#11
0
def main():
    home = os.path.dirname(os.path.abspath(sys.argv[0]))
    filename = os.path.join(home, "update.log")
    logfile.install(filename)

    try:
        up = Update()
        up.update()
    except Exception as e:
        logfile.info(e)
示例#12
0
    def rollback(self):
        backhome = os.path.join(self.home, 'tmp', 'backup')

        for root,dirs,files in os.walk(backhome):
            for fname in files:
                fpath = os.path.join(root, fname)
                dstpath = self.home + fpath[len(backhome):]
                try:
                    shutil.copyfile(fpath, dstpath)
                except:
                    logfile.info(traceback.format_exc())
                logfile.info('rollback file:', fpath, dstpath)
示例#13
0
    def rollback(self):
        backhome = os.path.join(self.home, 'tmp', 'backup')

        for root, dirs, files in os.walk(backhome):
            for fname in files:
                fpath = os.path.join(root, fname)
                dstpath = self.home + fpath[len(backhome):]
                try:
                    shutil.copyfile(fpath, dstpath)
                except:
                    logfile.info(traceback.format_exc())
                logfile.info('rollback file:', fpath, dstpath)
示例#14
0
    def query(self):
        url = self.user_url % ('query', self.conf['user'],
                               self.conf['password'])

        resp = urllib.request.urlopen(url)
        data = resp.read()
        logfile.info('query resp:', data)
        x = json.loads(data)

        if 'error' in x:
            return 0, x

        if self.conf['sync_way'] == 'user' and self.conf['id'] != x['id']:
            logfile.info('sync_way: user, local id:', self.conf['id'],
                         'remote id:', x['id'])
            self.conf['id'] = x['id']
            self.conf.dump()
            # logfile.info(self.get_conf())
            self.status = self.ADD
            return self.status, x

        # if self.conf['sync_way'] == 'user' and not x['haveconf']:
        #    self.upload_conf()

        # return x is last version information
        if x['ver'] == 0 and 'error' not in x:
            self.status = self.ADD
            return self.status, x

        # get local sync_ver
        if len(self.conf['sync_ver']) > 0:
            localver = int(self.conf['sync_ver'])
        else:  # not have local sync_ver
            logfile.info('not found local sync_ver, remote:', x['ver'])
            if x['ver'] > 0:  # remove have sync_ver, update
                self.status = self.UPDATE
                return self.status, x
            else:  # remote and local both not have sync_ver, ADD
                self.status = self.ADD
                return self.status, x

        if x['ver'] == localver:  # the same version
            logfile.info('check md5, local db: ', self.md5val, 'remote:',
                         x['md5'])
            if x['md5'] == self.md5val:  # the same md5, not update
                self.status = self.NOUPDATE
            else:  # modified, commit
                self.status = self.COMMIT

        elif x['ver'] > localver:  # remote version is newer than local
            # if x['modify']:
            # if self.conf['sync_md5'] != self.md5val: # local modified
            if x['modify']:  # user modified on old data, conflict
                self.status = self.CONFLICT
            else:  # update
                self.status = self.UPDATE
        else:
            self.status = self.ERROR

        return self.status, x
示例#15
0
    def backup(self):
        backdir = os.path.join(self.home, 'tmp', 'backup')
        try:
            if os.path.isdir(backdir):
                shutil.rmtree(backdir)
        except:
            os.rename(backdir, backdir + '.autobak.' + str(time.time()))
        os.makedirs(backdir)

        allfiles = []

        for topdir in os.listdir(self.home):
            if topdir in ['.hg', 'tmp'] or topdir.endswith(('.swp', '.log')):
                continue

            if topdir.find('.backup.') > 0:
                try:
                    os.remove(topdir)
                except:
                    continue
            toppath = os.path.join(self.home, topdir)
            if os.path.isdir(toppath):
                for root, dirs, files in os.walk(toppath):
                    for fname in files:
                        fpath = os.path.join(root, fname)
                        if fpath.endswith('.swp'):
                            continue
                        newpath = os.path.join(
                            self.home, 'tmp', 'backup',
                            fpath[len(self.home):].lstrip(os.sep))
                        newdir = os.path.dirname(newpath)
                        if not os.path.isdir(newdir):
                            os.makedirs(newdir)
                        shutil.copyfile(fpath, newpath)
                        allfiles.append(fpath)
                        logfile.info('copy:', fpath, newpath)
            else:
                newpath = os.path.join(self.home, 'tmp', 'backup',
                                       toppath[len(self.home):].lstrip(os.sep))
                newdir = os.path.dirname(newpath)
                if not os.path.isdir(newdir):
                    os.makedirs(newdir)
                shutil.copyfile(toppath, newpath)
                allfiles.append(toppath)
                logfile.info('copy:', toppath, newpath)

        for fname in allfiles:
            if fname.endswith('youmoney.conf') or fname.endswith(
                    'youmoney.db'):
                newfile = fname + '.%d%02d%02d.%02d%02d%02d.bak' % time.localtime(
                )[:6]
                shutil.copyfile(fname, newfile)
                continue
            logfile.info('remove file:', fname)
            try:
                os.remove(fname)
            except:
                newname = fname + '.backup.' + str(time.time())
                logfile.info('rename:', newname)
                os.rename(fname, newname)
示例#16
0
    def OnCloseWindow(self, event):
        # if self.conf['sync_way'] == 'user':
        # sync.synchronization(self)
        task.taskq.put(None)
        logfile.info('task thread end')
        vi = sys.version_info
        if vi[0] == 2 and vi[1] >= 6:
            task.server.shutdown()
        else:
            task.server.server_close()
        logfile.info('server thread end')

        self.Destroy()
        sys.exit()
示例#17
0
 def initcate(self):
     sql = "select count(*) from category"
     count = self.db.query_one(sql)
     #       print 'count:', count, 'iscreate:', config.cf.iscreate, 'lang:', config.cf['lang']
     if count == 0 and config.cf.iscreate and config.cf['lang'] == 'zh_CN':
         path = os.path.join(self.rundir, 'data', 'category.csv')
         if not os.path.isfile(path):
             return
         exp = export.DataImport(self.db, 'gbk')
         try:
             exp.category(path)
         except:
             logfile.info(traceback.format_exc())
         self.reload()
示例#18
0
    def OnDelete(self, event):
        dlg = wx.MessageDialog(self, _('Is really delete? Delete can not be restored!'), _('Notice:'),
                               wx.OK | wx.CANCEL | wx.ICON_INFORMATION)
        if dlg.ShowModal() != wx.ID_OK:
            dlg.Destroy()
            return
        dlg.Destroy()

        if self.currentItem is None:
            return
        id = self.list.GetItemData(self.currentItem)
        sql = "delete from recycle where id=" + str(id)
        logfile.info('del:', sql)
        self.parent.parent.db.execute(sql)
        self.parent.parent.reload()
示例#19
0
    def OnChooseType(self, event):
        val = self.type.GetValue()
        self.default_type = val
        self.category.Clear()

        logfile.info('Choose type:', val)

        if val == _('Surplus'):
            self.category.Append(_('All Categories'))
            self.category.SetValue(_('All Categories'))
        else:
            for x in self.data[val]:
                self.category.Append(x)

            self.category.SetValue(self.data[val][0])
示例#20
0
    def run(self):
        while True:
            try:
                task = taskq.get()
            except:
                continue
            if task is None:
                break
            try:
                func = getattr(self, 'do_' + task['type'])
            except:
                logfile.info('unkown type')
                continue

            func(task)
示例#21
0
    def OnInit(self):
        max = 1000
        dlg = wx.ProgressDialog(_("YouMoney Updater"),
                                _("Updating") + "...",
                                maximum=max,
                                parent=None,
                                style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL
                                | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME)

        up = Updater(dlg)
        filepath = None
        errorinfo = ''
        try:
            dlg.Update(0, _('Updating') + '...')
            filepath = up.download()
            dlg.Update(950, _('Close YouMoney') + '...')
            if filepath:
                try:
                    up.close_youmoney()
                    dlg.Update(950, _('Backup old data') + '...')
                    up.backup()
                    up.install(filepath)
                except Exception as e:
                    logfile.info(traceback.format_exc())
                    up.rollback()
                    errorinfo = _('Update failed!') + ' ' + str(e)
                else:
                    os.remove(filepath)
        except:
            logfile.info(traceback.format_exc())

        if errorinfo:
            dlg.Update(1000, errorinfo)
        else:
            if filepath:
                dlg.Update(1000, _('Update complete!'))
            else:
                going, skip = dlg.Update(999)
                if going:
                    if up.error_info:
                        dlg.Update(1000, up.error_info)
                    else:
                        dlg.Update(1000, _('Update failed!'))
                else:
                    dlg.Update(1000, _('Update cancled!'))
        dlg.Destroy()

        return True
示例#22
0
    def download(self):
        status, reason, headers = self.getheader(0)
        self.filesize = int(headers.getheader('Content-Length'))
        self.callback.Update(150, _('Package size') + ': ' + str(self.filesize))
        logfile.info('local size:', self.localsize, 'http size:', self.filesize)
        
        if self.filesize == self.localsize:
            return

        if self.localsize > self.filesize:
            self.localsize = 0
            os.remove(self.local)
            
        status, reason, headers = self.getheader(self.localsize)
        self.callback.Update(200, _('Download package') + ' ... 0%')
        self.getdata(self.filesize - self.localsize)
示例#23
0
    def download(self):
        status, reason, headers = self.getheader(0)
        self.filesize = int(headers.getheader('Content-Length'))
        self.callback.Update(150, _('Package size') + ': ' + str(self.filesize))
        logfile.info('local size:', self.localsize, 'http size:', self.filesize)
        
        if self.filesize == self.localsize:
            return

        if self.localsize > self.filesize:
            self.localsize = 0
            os.remove(self.local)
            
        status, reason, headers = self.getheader(self.localsize)
        self.callback.Update(200, _('Download package') + ' ... 0%')
        self.getdata(self.filesize - self.localsize)
示例#24
0
    def get_conf(self):
        if self.conf['sync_way'] != 'user':
            return None

        url = self.user_url % ('getconf', self.conf['user'],
                               self.conf['password'])

        resp = urllib.request.urlopen(url)
        s = resp.read()

        data = json.loads(s)
        if 'error' not in data:
            logfile.info('get conf:', data['data'])
            self.conf.load_data(data['data'])

        return data
示例#25
0
    def OnInit(self):
        max = 1000
        dlg = wx.ProgressDialog(_("EasyAccout Updater"), _("Updating") + "...",
                               maximum = max,parent=None,
                               style = wx.PD_CAN_ABORT| wx.PD_APP_MODAL
                                | wx.PD_ELAPSED_TIME| wx.PD_REMAINING_TIME)

        up = Updater(dlg)
        filepath = None
        errorinfo = ''
        try:
            dlg.Update(0, _('Updating') + '...')
            filepath = up.download()
            dlg.Update(950, _('Close EasyAccout') + '...')
            if filepath:
                try:
                    up.close_youmoney()
                    dlg.Update(950, _('Backup old data') + '...')
                    up.backup()
                    up.install(filepath)
                except Exception, e:
                    logfile.info(traceback.format_exc())
                    up.rollback()
                    errorinfo = _('Update failed!') + ' ' + str(e)
                else:
                    os.remove(filepath)
        except:
            logfile.info(traceback.format_exc())

        if errorinfo:
            dlg.Update(1000, errorinfo)
        else:
            if filepath:
                dlg.Update(1000, _('Update complete!'))
            else:
                going, skip = dlg.Update(999)
                if going:
                    if up.error_info:
                        dlg.Update(1000, up.error_info)
                    else:
                        dlg.Update(1000, _('Update failed!'))
                else:
                    dlg.Update(1000, _('Update cancled!'))
        dlg.Destroy()
         
        return True
示例#26
0
    def backup(self):
        backdir = os.path.join(self.home, 'tmp', 'backup') 
        try:
            if os.path.isdir(backdir):
                 shutil.rmtree(backdir)
        except:
            os.rename(backdir, backdir + '.autobak.' + str(time.time()))
        os.makedirs(backdir)
        
        allfiles = []
        
        for topdir in os.listdir(self.home):
            if topdir in ['.hg', 'tmp'] or topdir.endswith(('.swp', '.log')):
                continue

            if topdir.find('.backup.') > 0:
                try:
                    os.remove(topdir)
                except:
                    continue
            toppath = os.path.join(self.home, topdir)
            if os.path.isdir(toppath):
                for root,dirs,files in os.walk(toppath):
                    for fname in files:
                        fpath = os.path.join(root, fname)
                        if fpath.endswith('.swp'):
                            continue
                        newpath = os.path.join(self.home, 'tmp', 'backup', fpath[len(self.home):].lstrip(os.sep))
                        newdir = os.path.dirname(newpath)
                        if not os.path.isdir(newdir):
                            os.makedirs(newdir)
                        shutil.copyfile(fpath, newpath)
                        allfiles.append(fpath)
                        logfile.info('copy:', fpath, newpath)
            else:
                newpath = os.path.join(self.home, 'tmp', 'backup', toppath[len(self.home):].lstrip(os.sep))
                newdir = os.path.dirname(newpath)
                if not os.path.isdir(newdir):
                    os.makedirs(newdir)
                shutil.copyfile(toppath, newpath)
                allfiles.append(toppath)
                logfile.info('copy:', toppath, newpath)
 
        for fname in allfiles:
            if fname.endswith('EasyAccout.conf') or fname.endswith('EasyAccout.db'):
                newfile = fname + '.%d%02d%02d.%02d%02d%02d.bak' % time.localtime()[:6]
                shutil.copyfile(fname, newfile)
                continue
            logfile.info('remove file:', fname)
            try:
                os.remove(fname)
            except:
                newname = fname + '.backup.' + str(time.time())
                logfile.info('rename:', newname)
                os.rename(fname, newname)
示例#27
0
def main():
    if sys.platform.startswith('win32'):
        filename = os.path.join(home, "youmoney.log")
        vername = os.path.join(home, "version.dat")
        reportfile = os.path.join(home, "youmoney.report.txt")
    else:
        filename = os.path.join(os.environ['HOME'], ".youmoney",
                                "youmoney.log")
        vername = os.path.join(os.environ['HOME'], ".youmoney", "verion.dat")
        reportfile = os.path.join(os.environ['HOME'], "youmoney.report.txt")

    logfile.install(filename)
    #logfile.install('stdout')

    f = open(vername, 'w')
    f.write(version.VERSION)
    f.close()

    th = task.Task()
    th.start()

    try:
        app = YouMoney()
        app.MainLoop()
    except:
        s = traceback.format_exc()
        f = open(reportfile, 'a+')
        f.write(s)
        f.close()

        try:
            data = urllib.urlencode({
                'user': str(ui.storage.name),
                'sys': ui.update.system_version(),
                'version': str(version.VERSION),
                'info': s
            })
            resp = urllib2.urlopen(
                'http://%s/report' % (ui.config.cf['server']), data)
            logfile.info('report result:', resp.read())
        except:
            pass
        else:
            os.remove(reportfile)
        raise
示例#28
0
 def OnFileExportCate(self, event):
     dlg = wx.FileDialog(self,
                         message=_("Export Category"),
                         defaultDir=os.getcwd(),
                         defaultFile="",
                         wildcard=_("csv file (*.csv)|*.csv"),
                         style=wx.FD_SAVE)
     dlg.SetFilterIndex(2)
     if dlg.ShowModal() == wx.ID_OK:
         path = dlg.GetPath()
         exp = export.DataExport(self.db, 'gbk')
         try:
             exp.category(path)
         except Exception as e:
             logfile.info(traceback.format_exc())
             wx.MessageBox(str(e), _('Export Error:'),
                           wx.OK | wx.ICON_INFORMATION)
     dlg.Destroy()
示例#29
0
 def OnFileImportCate(self, event):
     dlg = dialogs.ImportCateDialog(self)
     if dlg.ShowModal() == wx.ID_OK:
         path = dlg.GetPath()
         if not path:
             dlg.Destroy()
             return
         exp = export.DataImport(self.db, 'gbk')
         try:
             exp.category(path)
         except Exception as e:
             logfile.info(traceback.format_exc())
             wx.MessageBox(str(e), _('Import Error:'),
                           wx.OK | wx.ICON_INFORMATION)
         else:
             wx.MessageBox(_('Import complete!'), _('Information'),
                           wx.OK | wx.ICON_INFORMATION)
         self.reload()
     dlg.Destroy()
示例#30
0
    def updateone(self, fileurl):
        socket.setdefaulttimeout(30)
        fs = urllib.request.urlopen(fileurl)
        lines = fs.readlines()
        fs.close()

        info = {}
        for line in lines:
            if line.startswith('#'):
                continue
            parts = line.strip().split('\t')
            if len(parts) != 2:
                continue
            info[parts[0]] = parts[1]

        if not self.version_diff(info['version']):
            logfile.info('not need update:', info['version'])
            return None
        logfile.info('found new version: ', info['version'])
        return info['version']
示例#31
0
def main():
    if sys.platform.startswith('win32'):
        filename = os.path.join(home, "youmoney.log")
        vername  = os.path.join(home, "version.dat")
        reportfile  = os.path.join(home, "youmoney.report.txt")
    else:
        filename = os.path.join(os.environ['HOME'], ".youmoney", "youmoney.log")
        vername  = os.path.join(os.environ['HOME'], ".youmoney", "verion.dat")
        reportfile  = os.path.join(os.environ['HOME'], "youmoney.report.txt")

    logfile.install(filename)
    #logfile.install('stdout')
        
    f = open(vername, 'w')
    f.write(version.VERSION)
    f.close()
    
    th = task.Task()
    th.start()
 
    try:
        app = YouMoney()
        app.MainLoop()
    except:
        s = traceback.format_exc()
        f = open(reportfile, 'a+')
        f.write(s)
        f.close()

        try:
            data = urllib.urlencode({'user':str(ui.storage.name), 
                                 'sys':ui.update.system_version(), 
                                 'version':str(version.VERSION), 'info':s})
            resp = urllib2.urlopen('http://%s/report' % (ui.config.cf['server']), data)  
            logfile.info('report result:', resp.read())
        except:
            pass
        else:
            os.remove(reportfile)
        raise
示例#32
0
    def getdata(self, length):
        logfile.info('length:', length)
        f = open(self.local, 'a+b')
        num = 0
        bufsize = 8192
        try:
            while True:
                leave = length - num
                if leave < bufsize:
                    bufsize = leave
                data = self.h.file.read(bufsize)
                if not data:
                    break
                num += len(data)
                f.write(data)
                logfile.info('download size:', num)
                rate = float(self.filesize - length + num) / self.filesize
                going, skip = self.callback.Update(
                    200 + rate * 700,
                    _('Download package') + '... %.2d%%' % (rate * 100))
                if not going:
                    f.close()
                    return
        except Exception as e:
            logfile.info(traceback.format_exc())
            f.close()
            raise

        f.close()
示例#33
0
 def getdata(self, length):
     logfile.info('length:', length)
     f = open(self.local, 'a+b')
     num = 0 
     bufsize = 8192
     try:     
         while True:
             leave = length - num
             if leave < bufsize:
                 bufsize = leave
             data = self.h.file.read(bufsize)
             if not data:
                 break
             num += len(data)
             f.write(data)
             logfile.info('download size:', num)
             rate = float(self.filesize - length + num) / self.filesize
             going, skip = self.callback.Update(200 + rate * 700, _('Download package') + '... %.2d%%' % (rate * 100))
             if not going:
                 f.close()
                 return
     except Exception, e:
         logfile.info(traceback.format_exc()) 
         f.close()
         raise
示例#34
0
    def OnFileChange(self, event):
        dlg = wx.FileDialog(self,
                            message=_("Change account path..."),
                            defaultDir=os.getcwd(),
                            defaultFile="",
                            wildcard=_("YouMoney Database (*.db)|*.db"),
                            style=wx.FD_SAVE)
        dlg.SetFilterIndex(2)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            logfile.info("save file:", path)
            if not path.endswith('.db'):
                path += ".db"

            self.conf.dump()
            oldfile = self.conf['lastdb']
            if os.path.isfile(path):
                wx.MessageBox(_('File exist'), _('Can not save account file'),
                              wx.OK | wx.ICON_INFORMATION)
                return
            try:
                shutil.copyfile(self.conf['lastdb'], path)
            except Exception as e:
                wx.MessageBox(
                    _('Change account path failture:') + str(e),
                    _('Can not save account file'),
                    wx.OK | wx.ICON_INFORMATION)
                return
            self.db.close()
            if os.path.isfile(oldfile):
                os.remove(oldfile)
            self.initdb(path)
            # self.db = storage.DBStorage(path)
            self.reload()
            self.conf['lastdb'] = path
            self.conf.dump()

            self.SetStatusText(_('Database file: ') + self.conf['lastdb'], 0)

        dlg.Destroy()
示例#35
0
    def user_add(self):
        isok = False
        dlg = UserPassDialog(self, self.conf, 'add')
        while True:
            ret = dlg.ShowModal()
            if ret != wx.ID_OK:
                return
            vals = dlg.values()
            if vals['password1'] != vals['password2']:
                dlg.set_warn(_('Different password.'))
                continue
            url = 'http://%s/sync?action=useradd&ident=%s&user=%s&pass=%s' % (self.conf['server'], self.conf['id'], urllib.request.quote(vals['username']), urllib.request.quote(vals['password1'])) #Fixme: to be fixed
            try:
                resp = urllib.request.urlopen(url)
                s = resp.read()
            except Exception as e:
                wx.MessageBox(str(e), _('Error'), wx.OK | wx.ICON_INFORMATION)
                continue
            
            val = json.loads(s)
            errstr = val.get('error')
            if errstr:
                logfile.info(errstr)
                dlg.set_warn(self.errors[val['status']])
                continue
             
            wx.MessageBox(_('User and password are successfully added!'), _('Success'), wx.OK | wx.ICON_INFORMATION)
            self.conf['user'] = vals['username']
            self.conf['password'] = vals['password1']
            self.conf.dump()

            self.username.SetValue(vals['username'])
            self.password.SetValue(vals['password1'])

            isok = True
            break

        dlg.Destroy()
        return isok
示例#36
0
    def __init__(self, parent, readydata):
        if readydata['mode'] == 'insert':
            title = _('Add income item')
        else:
            title = _('Edit income item')

        MySizedDialog.__init__(self, None, -1, title, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        self.parent = parent
        self.data = readydata

        panel = self.GetContentsPane()
        panel.SetSizerType("form")
         
        wx.StaticText(panel, -1, _('Date:'))
        # self.date = wx.DatePickerCtrl(panel, size=(120, -1), style=wx.DP_DROPDOWN|
        #            wx.DP_SHOWCENTURY|wx.DP_ALLOWNONE)
        logfile.info('year:', readydata['year'], ' month:', readydata['month'])

        tm = wx.DateTime()
        tm.Set(readydata['day'], readydata['month']-1, readydata['year'])
        self.date = adv.GenericDatePickerCtrl(panel, dt=tm, size=(120, -1), style=adv.DP_DROPDOWN | adv.DP_SHOWCENTURY | adv.DP_ALLOWNONE)

        wx.StaticText(panel, -1, _('Category:'))
        items = readydata['cates']
        self.cate = wx.ComboBox(panel, -1, readydata['cate'], (90, 50), (160, -1), items, wx.CB_DROPDOWN | wx.CB_READONLY)

        wx.StaticText(panel, -1, _('Money:'))
        self.num = wx.TextCtrl(panel, -1, str(readydata['num']), size=(125, -1))

        wx.StaticText(panel, -1, _('Explain:'))
        self.explain = wx.TextCtrl(panel, -1, readydata['explain'], size=(220, 100), style=wx.TE_MULTILINE)

        wx.StaticText(panel, -1, '')
        self.reuse = wx.CheckBox(panel, -1, _("Not close dialog, continue."))

        self.SetButtonSizer(self.CreateStdDialogButtonSizer(wx.OK | wx.CANCEL))
        self.SetMinSize(wx.Size(300, 250))

        self.Fit()
示例#37
0
    def OnFileOpen(self, event):
        dlg = wx.FileDialog(self,
                            message=_("Choose account file:"),
                            defaultDir=os.getcwd(),
                            defaultFile="",
                            wildcard=_("YouMoney Database (*.db)|*.db"),
                            style=wx.FD_OPEN | wx.FD_CHANGE_DIR)

        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            logfile.info("open file:", path)

            self.db.close()
            self.initdb(path)
            # self.db = storage.DBStorage(path)
            self.reload()
            self.conf['lastdb'] = path
            self.conf.dump()

            self.SetStatusText(_('Database file: ') + self.conf['lastdb'], 0)

        dlg.Destroy()
示例#38
0
    def cateedit_dialog(self, ready):
        cates = copy.deepcopy(self.category.catelist_parent())
        cates[_('Income')].insert(0, _('No Higher Category'))
        cates[_('Payout')].insert(0, _('No Higher Category'))
        ready['cates'] = cates
        if not ready['upcate']:
            ready['upcate'] = _('No Higher Category')

        dlg = dialogs.CategoryDialog(self, ready)
        dlg.CenterOnScreen()
        if dlg.ShowModal() == wx.ID_OK:
            item = dlg.values()
            logfile.info('cateedit:', item)
            type = catetypes[item['catetype']]
            parent = 0
            if item['catetype'] == _('Income'):
                if item['upcate'] != _('No Higher Category'):
                    parent = self.category.income_catemap[item['upcate']]
            elif item['catetype'] == _('Payout'):
                if item['upcate'] != _('No Higher Category'):
                    parent = self.category.payout_catemap[item['upcate']]

            if item['mode'] == 'insert':
                # sql = "insert into category (name,parent,type) values ('%s',%d,%d)" % (item['cate'], parent, type)
                sql = "insert into category (name,parent,type) values (?,?,?)"
                logfile.info('insert category:', sql)
                try:
                    # self.db.execute(sql, (item['cate'], parent, type, ))
                    self.db.execute_param(sql, (
                        item['cate'],
                        parent,
                        type,
                    ))
                except Exception as e:
                    wx.MessageBox(
                        _('Add category failture:') + str(e),
                        _('Add category information'),
                        wx.OK | wx.ICON_INFORMATION)
                else:
                    self.reload()
            elif item['mode'] == 'update':
                # sql = "update category set name='%s',parent=%d,type=%d where id=%d" % (item['cate'], parent, type, item['id'])
                sql = "update category set name=?,parent=?,type=? where id=?"
                logfile.info('update category:', sql)
                try:
                    self.db.execute_param(sql, (
                        item['cate'],
                        parent,
                        type,
                        item['id'],
                    ))
                except Exception as e:
                    wx.MessageBox(
                        _('Change category failure:') + str(e),
                        _('Change category information'),
                        wx.OK | wx.ICON_INFORMATION)
                else:
                    self.reload()
示例#39
0
    def close_youmoney(self):
        maxc = 30
        issend = False
        socket.setdefaulttimeout(30)
        while  maxc > 0:
            logfile.info('try connect to EasyAccout...')
            self.callback.Update(950)
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.setblocking(0)
                ret = sock.connect_ex(('127.0.0.1', 9596))
                #logfile.info('connect: ', ret) 

                if ret in [EINPROGRESS, EALREADY, EWOULDBLOCK]:
                    checkmax = 4
                    while checkmax > 0:
                        logfile.info('checkmax:', checkmax)
                        self.callback.Update(950)
                        r = [sock]
                        try:
                            r, w, e = select.select(r, [], [], 0.5)
                        except select.error, err:
                            logfile.info('select error:', err[0], err[1])
                            if err[0] == EINTR:
                                continue
                            raise IOError, 'connect error' 
                        logfile.info(r, w, e)
                        if sock in r:
                            break
                        else:
                            checkmax -= 1
                    else:
                        raise IOError, 'connect error' 
                else:
                    raise IOError, 'connect error'
                sock.setblocking(1)
示例#40
0
                 if err[0] == EINTR:
                     continue
                 raise IOError, 'connect error' 
             logfile.info(r, w, e)
             if sock in r:
                 break
             else:
                 checkmax -= 1
         else:
             raise IOError, 'connect error' 
     else:
         raise IOError, 'connect error'
     sock.setblocking(1)
 except:
     sock.close()
     logfile.info(traceback.format_exc())
     return True
 self.callback.Update(950)
 logfile.info('connect ok!') 
 if not issend:
     sockfile = sock.makefile()
     line = sockfile.readline()
     logfile.info('read:', line.strip()) 
     if not line.startswith('EasyAccout'):
         sock.close()
         return False
     else:
         sockfile.write('update\r\n')
         sockfile.flush()
         line = sockfile.readline()
         logfile.info('read:', line.strip())
示例#41
0
    def download(self):
        verstr = self.info['version']
        if int(version.VERSION.replace('.','')) >= int(verstr.replace('.', '')):
            logfile.info('not need update:', version.VERSION, verstr)
            self.error_info = _('Not need update:') + verstr
            return

        if sys.platform == 'darwin' and not self.home.startswith(os.environ['HOME']):
            logfile.info('auto update not support binary on Mac OS X.')
            self.error_info = _('Mac OS X binary version dose not support the automatic update.')
            return

        prefix = ''
        noinstallfile = prefix + '' % (verstr)
        srcfile = prefix + '' % (verstr)

        srcmainfile = os.path.join(self.home, 'EasyAccout.py')
        fileurl = srcfile
        if os.path.isfile(srcmainfile):
            if sys.platform.startswith('linux') and self.home.startswith('/usr/share'):
                logfile.info('Linux rpm and deb install not support auto update')
                self.err_info = _('Linux rpm and deb install does not support the automaitc update.')
                return
            fileurl = srcfile
        else:     
            if sys.platform == 'win32':
                exe = os.path.join(self.home, 'youmoney.exe')
                if os.path.isfile(exe):
                    fileurl = noinstallfile
                else:
                    fileurl = srcfile
            elif sys.platform == 'darwin':
                logfile.info('Mac OS X not support binary auto update.')
                self.error_info = _('Mac OS X binary version dose not support the automatic update.')
                return
            elif sys.platform.startswith('linux'):
                fileurl = srcfile
        
        filepath = os.path.join(self.tmpdir, os.path.basename(fileurl))
        self.path = filepath
        logfile.info('try download %s' % fileurl)
        logfile.info('save:', filepath)
        
        count = 9
        while count > 0: 
            try:
                dw = Downloader(fileurl, filepath, self.callback)
                dw.download()
            except:
                logfile.info(traceback.format_exc())
                count -= 1
                continue 
            break
        
        self.callback.Update(900, _('Validate package') + '...')
        size = os.path.getsize(filepath)
        if dw.filesize > size:
            self.error_info = _('Package size is too small. Try update again.')
            return

        md5str = sumfile(filepath)
        name = os.path.basename(fileurl)
        logfile.info('file md5:', md5str, self.info[name])
        if md5str == self.info[name]:
            logfile.info('file md5 check ok!')
            return filepath
        elif size >= dw.filesize:
            logfile.info('file md5 check failed. remove')
            os.remove(filepath)
            self.error_info = _('Package md5 is error! Try update again.')
            return