Пример #1
0
def trim_filename(path):
    assert type(path) in (str, unicode)
    if len(path) > PIE_CONFIG.getint('Format', 'filesystem_length_limit') - 5:
        dirn = os.path.dirname(path)
        basen, ext = os.path.splitext(os.path.basename(path))
        basen = basen[:PIE_CONFIG.getint('Format', 'filesystem_length_limit') - len(ext) - len(dirn) - 5] # -5 to account for addition chars from auto_increment_fn
        return os.path.join(dirn, basen.strip() + ext)
    else:
        return path
Пример #2
0
def trim_filename(path):
    assert type(path) in (str, unicode)
    if len(path) > PIE_CONFIG.getint('Format', 'filesystem_length_limit') - 5:
        dirn = os.path.dirname(path)
        basen, ext = os.path.splitext(os.path.basename(path))
        basen = basen[:PIE_CONFIG.getint(
            'Format', 'filesystem_length_limit') - len(ext) - len(
                dirn
            ) - 5]  # -5 to account for addition chars from auto_increment_fn
        return os.path.join(dirn, basen.strip() + ext)
    else:
        return path
Пример #3
0
def suggest_path_store_with_bibdata(obj):
    assert obj.has_aspect('cached')
    assert obj.has_aspect('bibdata')
    root = LIBRARYDIR
    auth = obj.Author(favour_corporate=False)
    if obj.BibData_Journal:
        subd = obj.BibData_Journal
    # elif obj.
    #     obj.
    else: subd = u''
    print 'suggest_path_store_with_bibdata: ____'
    ext = os.path.splitext(obj.FileData_FullPath)[1]
    # try to fix odd file extensions (phtml, php etc)
    if not ext in FEXTENSIONS[obj.FileData_FileType]:
        if len(FEXTENSIONS[obj.FileData_FileType]) == 1:
            # only guess if there's only one possible extension
            ext = FEXTENSIONS[obj.FileData_FileType][0]
    fn_prop = "%s - %s%s" % (
        obj.ReferDate().strftime("%Y%m%d"),
        translate_non_alphanumerics(obj.Title()),
        ext)
    proposal = os.path.join(
        root, auth.strip(), subd.strip(), 
        fn_prop[:PIE_CONFIG.getint('Format', 'filesystem_length_limit')].strip()
        )
    proposal = trim_filename(proposal)
    proposal = auto_increment_fn(proposal)
    print 'SUGGESTING:', proposal
    if os.path.exists(proposal):
        raise IOError, 'File already exists. TODO - auto-fix'
    return proposal, ('librarydir',
                      [i for i in (auth, subd) if i],
                      os.path.basename(proposal))
Пример #4
0
def clean_backups():
    if len(os.listdir(BACKUPDIR)) < 2:
        return  # always have at least one backup
    if len(os.listdir(BACKUPDIR)) > 25:  # more than 25 backups is a bit silly
        files = [os.path.join(BACKUPDIR, i) for i in os.listdir(BACKUPDIR)]
        files.sort()
        for f in files[:len(files) - 25]:
            try:
                os.remove(f)
                print 'deleting old backup %s' % f
            except:
                continue
    for fn in os.listdir(BACKUPDIR):
        fn = os.path.join(BACKUPDIR, fn)
        if os.path.isfile(fn):
            # print fn.split('.')
            try:
                fdate = datetime.datetime.strptime(
                    fn.split('.')[-1], '%Y%m%d-%H%M')
                deldays = datetime.timedelta(days=PIE_CONFIG.getint(
                    'Internal', 'delete_backups_after_days'))
                today = datetime.datetime.today()
                if today - fdate > deldays:
                    os.remove(fn)
                    print 'deleting old backup %s' % fn
                else:
                    print 'Leave %s' % fn
            except:
                traceback.print_exc()
                continue
Пример #5
0
def suggest_path_store_with_bibdata(obj):
    assert obj.has_aspect('cached')
    assert obj.has_aspect('bibdata')
    root = LIBRARYDIR
    auth = obj.Author(favour_corporate=False)
    if obj.BibData_Journal:
        subd = obj.BibData_Journal
    # elif obj.
    #     obj.
    else:
        subd = u''
    print 'suggest_path_store_with_bibdata: ____'
    ext = os.path.splitext(obj.FileData_FullPath)[1]
    # try to fix odd file extensions (phtml, php etc)
    if not ext in FEXTENSIONS[obj.FileData_FileType]:
        if len(FEXTENSIONS[obj.FileData_FileType]) == 1:
            # only guess if there's only one possible extension
            ext = FEXTENSIONS[obj.FileData_FileType][0]
    fn_prop = "%s - %s%s" % (obj.ReferDate().strftime("%Y%m%d"),
                             translate_non_alphanumerics(obj.Title()), ext)
    proposal = os.path.join(
        root, auth.strip(), subd.strip(),
        fn_prop[:PIE_CONFIG.getint('Format', 'filesystem_length_limit')].strip(
        ))
    proposal = trim_filename(proposal)
    proposal = auto_increment_fn(proposal)
    print 'SUGGESTING:', proposal
    if os.path.exists(proposal):
        raise IOError, 'File already exists. TODO - auto-fix'
    return proposal, ('librarydir', [i for i in (auth, subd)
                                     if i], os.path.basename(proposal))
Пример #6
0
def clean_backups():
    if len(os.listdir(BACKUPDIR)) < 2: return # always have at least one backup
    if len(os.listdir(BACKUPDIR)) > 25: # more than 25 backups is a bit silly
        files = [os.path.join(BACKUPDIR, i) for i in os.listdir(BACKUPDIR)]
        files.sort()
        for f in files[:len(files)-25]: 
            try:
                os.remove(f)
                print 'deleting old backup %s' % f
            except:
                continue
    for fn in os.listdir(BACKUPDIR):
        fn = os.path.join(BACKUPDIR, fn)
        if os.path.isfile(fn):
            # print fn.split('.')
            try:
                fdate = datetime.datetime.strptime(
                    fn.split('.')[-1], '%Y%m%d-%H%M')
                deldays = datetime.timedelta(days=PIE_CONFIG.getint(
                        'Internal', 'delete_backups_after_days'))
                today = datetime.datetime.today()
                if today - fdate > deldays:
                    os.remove(fn)
                    print 'deleting old backup %s' % fn
                else:
                    print 'Leave %s' % fn
            except:
                traceback.print_exc()
                continue
Пример #7
0
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)

        self.defbibtexchoice = wx.Choice(self,
                                         -1,
                                         choices=self.bibtexchoices.keys())
        self.defbibtexchoice.SetStringSelection(
            PIE_CONFIG.get('Format', 'default_bibtex_entry_type'))
        tta = wx.ToolTip(
            _('Web pages and downloads will use this type by default'))
        self.defbibtexchoice.SetToolTip(tta)
        self.howpublishedtext = wx.TextCtrl(self,
                                            -1,
                                            validator=pieBibtexValidator(True))
        ttb = wx.ToolTip(
            _('Web pages and downloads will use this text in the "howpublished" field by default'
              ))
        self.howpublishedtext.SetValue(
            PIE_CONFIG.get('Format', 'default_howpublished_text'))
        self.urlchoice = wx.Choice(self, -1, choices=self.uchz.keys())
        ttc = wx.ToolTip(
            _("When referencing urls, should pieberry use the full URL, the page that referred to the full URL (where possible) or just the domain name of the site?"
              ))
        self.urlchoice.SetToolTip(ttc)
        self.urlchoice.SetStringSelection(self.uchz_rv[PIE_CONFIG.get(
            'Format', 'url_level_represent')])
        self.plaintextfmtchoice = wx.Choice(self,
                                            -1,
                                            choices=self.ptxtfchz.keys())
        self.plaintextfmtchoice.SetStringSelection(
            self.ptxtfchz_rv[PIE_CONFIG.get('Format',
                                            'plaintext_citation_format')])
        self.protectcaps_cb = wx.CheckBox(
            self, -1,
            _('Prevent reformatting of capital letters in citations'))
        self.protectcaps_cb.SetValue(
            PIE_CONFIG.getboolean('Format', 'protect_all_caps_in_citations'))

        self.writepdf_cb = wx.CheckBox(self, -1,
                                       _('Write file metadata when possible'))
        ttd = wx.ToolTip(
            _('''
Pieberry will try to update metadata fields of pdf, office-xml and open
document files to reflect the known bibliographic data to a limited extent
(generally just the title and author). It doesn\'t always, however, work 
(but should fail safe)'''))
        self.writepdf_cb.SetToolTip(ttd)
        self.writepdf_cb.SetValue(
            PIE_CONFIG.getboolean('Format', 'write_file_metadata'))
        self.fnlen_spinner = wx.SpinCtrl(self, -1, min=40, max=255)
        self.fnlen_spinner.SetValue(
            PIE_CONFIG.getint('Format', 'filesystem_length_limit'))
        self._do_layout()
        self._do_bindings()
Пример #8
0
 def _set_columndata(self, idx, obj, msgtype=None):
     '''Set relevant data to the column at row: idx'''
     # print 'BibListCtrl._set_columndata'
     if not msgtype:
         msgtype = obj.get_icon_code('bibwindow')
     self.SetItemImage(idx, MessageType[msgtype])
     # self.SetItemText(idx, '')
     if obj.notes: self.SetStringItem(idx, 1, u'\u270D') # writing pen
     else: self.SetStringItem(idx, 1, '')
     self.SetStringItem(idx, 2, obj.Author())
     self.SetStringItem(idx, 3, fmtdate(obj.ReferDate()))
     self.SetStringItem(idx, 4, obj.Title(atom_title_hack=ATH))
     if obj.StatData_FollowUpFlag:
         td = datetime.datetime.today() - obj.StatData_FollowUpDate
         if td.days < PIE_CONFIG.getint('Internal', 'flagged_purpleafter'):
             self.SetItemTextColour(idx, 'blue')
         elif td.days > PIE_CONFIG.getint('Internal', 'flagged_redafter'):
             self.SetItemTextColour(idx, 'red')
         else:
             self.SetItemTextColour(idx, 'purple')
     else: self.SetItemTextColour(idx, wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))
Пример #9
0
 def _set_columndata(self, idx, obj, msgtype=None):
     '''Set relevant data to the column at row: idx'''
     # print 'BibListCtrl._set_columndata'
     if not msgtype:
         msgtype = obj.get_icon_code('bibwindow')
     self.SetItemImage(idx, MessageType[msgtype])
     # self.SetItemText(idx, '')
     if obj.notes: self.SetStringItem(idx, 1, u'\u270D')  # writing pen
     else: self.SetStringItem(idx, 1, '')
     self.SetStringItem(idx, 2, obj.Author())
     self.SetStringItem(idx, 3, fmtdate(obj.ReferDate()))
     self.SetStringItem(idx, 4, obj.Title(atom_title_hack=ATH))
     if obj.StatData_FollowUpFlag:
         td = datetime.datetime.today() - obj.StatData_FollowUpDate
         if td.days < PIE_CONFIG.getint('Internal', 'flagged_purpleafter'):
             self.SetItemTextColour(idx, 'blue')
         elif td.days > PIE_CONFIG.getint('Internal', 'flagged_redafter'):
             self.SetItemTextColour(idx, 'red')
         else:
             self.SetItemTextColour(idx, 'purple')
     else:
         self.SetItemTextColour(
             idx, wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))
Пример #10
0
    def __init__(self, *args, **kw):
        
        wx.Panel.__init__(self, *args, **kw)
        sizer = wx.BoxSizer(wx.VERTICAL)

        self.toolbar = wx.ToolBar(self, -1)

        self.MakeToolBar()
        
        self.titlelabel = wx.StaticText(self, -1, 'The title')
        self.authorlabel = wx.StaticText(self, -1, 'The Author')
        self.datelabel = wx.StaticText(self, -1, 'Date')
        self.tagedit = PieTagWidget(self, -1, mode="lhorizontal")
        self.tagedit.setTagList(get_all_tags().keys())
        self.tagedit.Bind(EVT_PIE_TAG_ADDED, self.OnTagAdded)
        self.tagedit.Bind(EVT_PIE_TAG_CLICKED, self.OnTagClicked)
        self.rtc = rt.RichTextCtrl(
            self, style=wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER|wx.WANTS_CHARS)

        rtcfont = wx.Font(12, wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
        self.rtc.SetFont(rtcfont)

        sizer.Add(self.titlelabel, 0, wx.EXPAND|wx.ALL, 5)

        font = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)
        self.titlelabel.SetFont(font)

        sizer.Add(self.authorlabel, 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
        sizer.Add(self.datelabel, 0, wx.EXPAND|wx.ALL, 5)
        sizer.Add(self.tagedit)
        sizer.Add(self.toolbar, 0, wx.EXPAND)
        sizer.Add(self.rtc, 1, wx.ALL|wx.EXPAND, 0)

        self.savebt = wx.Button(self, -1, _('Save'))
        self.donebt = wx.Button(self, -1, _('Save and Close'))
        lsizer = wx.BoxSizer(wx.HORIZONTAL)
        lsizer.Add((20,20), 1)
        lsizer.Add(self.savebt, 0, wx.ALL, 3)
        lsizer.Add(self.donebt, 0, wx.ALL, 3)
        
        sizer.Add(lsizer, 0, wx.EXPAND)

        self.SetSizer(sizer)
        self.Layout()
        self._do_bindings()

        self.savetimer = PeriodicSaveTimer(self)
        self.savetimer.Start(PIE_CONFIG.getint('Internal', 'minutes_between_save_notes') * 60 * 1000)
        wx.CallAfter(self.rtc.SetFocus)
Пример #11
0
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        
        self.defbibtexchoice = wx.Choice(self, -1, 
                                         choices=self.bibtexchoices.keys())
        self.defbibtexchoice.SetStringSelection(
            PIE_CONFIG.get('Format', 'default_bibtex_entry_type'))
        tta = wx.ToolTip(_('Web pages and downloads will use this type by default'))
        self.defbibtexchoice.SetToolTip(tta)
        self.howpublishedtext = wx.TextCtrl(self, -1, 
                                            validator=pieBibtexValidator(True))
        ttb = wx.ToolTip(_('Web pages and downloads will use this text in the "howpublished" field by default'))     
        self.howpublishedtext.SetValue(
            PIE_CONFIG.get('Format', 'default_howpublished_text'))
        self.urlchoice = wx.Choice(self, -1, choices = self.uchz.keys())
        ttc = wx.ToolTip(_("When referencing urls, should pieberry use the full URL, the page that referred to the full URL (where possible) or just the domain name of the site?"))
        self.urlchoice.SetToolTip(ttc)
        self.urlchoice.SetStringSelection(
            self.uchz_rv[PIE_CONFIG.get('Format', 'url_level_represent')])
        self.plaintextfmtchoice = wx.Choice(self, -1, 
                                       choices=self.ptxtfchz.keys())
        self.plaintextfmtchoice.SetStringSelection(
            self.ptxtfchz_rv[PIE_CONFIG.get('Format', 'plaintext_citation_format')])
        self.protectcaps_cb = wx.CheckBox(self, -1, 
                                          _('Prevent reformatting of capital letters in citations'))
        self.protectcaps_cb.SetValue(
            PIE_CONFIG.getboolean('Format', 'protect_all_caps_in_citations'))

        self.writepdf_cb = wx.CheckBox(self, -1, 
                                       _('Write file metadata when possible'))
        ttd = wx.ToolTip(_('''
Pieberry will try to update metadata fields of pdf, office-xml and open
document files to reflect the known bibliographic data to a limited extent
(generally just the title and author). It doesn\'t always, however, work 
(but should fail safe)'''))
        self.writepdf_cb.SetToolTip(ttd)
        self.writepdf_cb.SetValue(
            PIE_CONFIG.getboolean('Format', 'write_file_metadata'))
        self.fnlen_spinner = wx.SpinCtrl(self, -1, min=40, max=255)
        self.fnlen_spinner.SetValue(
            PIE_CONFIG.getint('Format', 'filesystem_length_limit'))
        self._do_layout()
        self._do_bindings()