def _new_term(self): if not self.args.query or len(self.args.query) < 1: slog.error('Provide 1 arguments at least please.') return query = self.get_term_query() print('query:', query) term = self.get_terms_from_wp(query, force=True) print(term) if term: slog.error('The term "%s" has been in wordpress.' % self.args.query[0]) return taxname = query[0] slug = self.args.query[0] name = self.args.query[1] if len(self.args.query) > 1 else slug term = WordPressTerm() term.slug = slug term.name = name term.taxonomy = taxname if len(self.args.query) > 2: term.description = self.args.query[2] termid = self.wpcall(NewTerm(term)) if not termid: return term = self.wpcall(GetTerm(taxname, termid)) if not term: return slog.info('The term %s(%s) has created.' % (name, termid)) self.conf.save_term(term, taxname) self.conf.save_to_file() slog.info('The term %s has saved.' % name)
def _new_term(self): if not self.args.query or len(self.args.query)<1: slog.error('Provide 1 arguments at least please.') return query = self.get_term_query() print('query:', query) term = self.get_terms_from_wp(query, force=True) print(term) if term: slog.error('The term "%s" has been in wordpress.'%self.args.query[0]) return taxname = query[0] slug = self.args.query[0] name = self.args.query[1] if len(self.args.query)>1 else slug term = WordPressTerm() term.slug = slug term.name = name term.taxonomy = taxname if len(self.args.query)>2: term.description = self.args.query[2] termid = self.wpcall(NewTerm(term)) if not termid: return term = self.wpcall(GetTerm(taxname, termid)) if not term: return slog.info('The term %s(%s) has created.'%(name, termid)) self.conf.save_term(term, taxname) self.conf.save_to_file() slog.info('The term %s has saved.'%name)
def _new_draft(self): name = None if self.args.query: name = self.args.query[0] try: dfile, dname = self.conf.get_new_draft(name) except BlogError as e: slog.critical(e) return dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') subdict = { 'TITLE':'', 'DATE':dt, 'MODIFIED':dt, 'AUTHOR':self.conf.site.user, 'NICENAME':'', 'CATEGORY':'technology', 'TAG':'', 'POSTTYPE':self.args.type, 'POSTSTATUS':'draft', } write_by_templ(self.conf.get_path('templates', 'article.md'), dfile, subdict, True) slog.info('The draft file "%s" has created.'%dfile)
def print_results(self, results): if isinstance(results, list): for result in results: self.print_result(result) elif isinstance(results, dict): for k,v in results.items(): slog.info('%s %s'%(k, str(v))) else: self.print_result(results)
def print_results(self, results): if isinstance(results, list): for result in results: self.print_result(result) elif isinstance(results, dict): for k, v in results.items(): slog.info('%s %s' % (k, str(v))) else: self.print_result(results)
def _update_a_draft(self): postid = self.get_postid() if not postid: slog.warning('Please provide a post id!') return afile, aname = self.conf.get_draft(postid) html, meta, txt, medias = self._get_and_update_article_content(afile) if not html: return if meta.poststatus == 'draft': slog.warning('The post status of draft "%s" is "draft", ' 'please modify it to "publish".' % postid) return # Update all taxonomy before create a new article. self.get_terms_from_wp(['category']) self.get_terms_from_wp(['post_tag']) if meta.posttype == 'page': post = WordPressPage() else: post = WordPressPost() post.content = html post.title = meta.title post.slug = meta.nicename post.date = meta.date post.user = meta.author post.date_modified = meta.modified post.post_status = meta.poststatus post.terms = self.get_terms_from_meta(meta.category, meta.tags) if not post.terms: slog.warning('Please provide some terms.') return postid = self.wpcall(NewPost(post)) if postid: write_by_templ(afile, afile, { 'POSTID': postid, 'SLUG': postid }, True) else: return newfile, newname = None, None if meta.posttype == 'page': newfile, newname = self.conf.get_article(post.nicename, meta.posttype) else: newfile, newname = self.conf.get_article(postid, meta.posttype) slog.info('Move "%s" to "%s".' % (afile, newfile)) shutil.move(afile, newfile)
def _update_term(self): q = self.args.query term = None query = self.get_term_query() typ = query[0] if q and len(q) > 1: term = self.get_terms_from_wp(query, force=True) if not term: slog.error('The term %s is not existend.'%str(q)) return term = self.wpcall(GetTerm(typ, term.id)) if term: term.slug = q[0] term.name = q[1] if len(q)>2: term.description = q[2] # post_get can not support parent. if term.taxonomy == 'post_tag': term.parent = None issucc = self.wpcall(EditTerm(term.id, term)) if issucc: self.conf.save_term(term, typ) self.conf.save_to_file() slog.info('The term %s(%s) has saved.'%(term.slug, term.id)) else: slog.info('The term %s(%s) saves unsuccessfully.'%(term.slug, term.id)) else: slog.info('Can not get term "%s".'%typ) else: term = self.get_terms_from_wp(query, force=True) if term: slog.info('Update terms done.') else: slog.warning('No terms.')
def _update_a_draft(self): postid = self.get_postid() if not postid: slog.warning('Please provide a post id!') return afile, aname = self.conf.get_draft(postid) html, meta, txt, medias = self._get_and_update_article_content(afile) if not html: return if meta.poststatus == 'draft': slog.warning('The post status of draft "%s" is "draft", ' 'please modify it to "publish".'%postid) return # Update all taxonomy before create a new article. self.get_terms_from_wp(['category']) self.get_terms_from_wp(['post_tag']) if meta.posttype == 'page': post = WordPressPage() else: post = WordPressPost() post.terms = self.get_terms_from_meta(meta.category, meta.tags) if not post.terms: slog.warning('Please provide some terms.') return post.content= html post.title = meta.title post.slug = meta.nicename post.date = meta.date post.user = meta.author post.date_modified = meta.modified post.post_status = meta.poststatus postid = self.wpcall(NewPost(post)) if postid: write_by_templ(afile, afile, {'POSTID':postid, 'SLUG':postid}, True) else: return newfile, newname = None, None if meta.posttype == 'page': newfile, newname = self.conf.get_article(meta.nicename, meta.posttype) else: newfile, newname = self.conf.get_article(postid, meta.posttype) slog.info('Move "%s" to "%s".'%(afile, newfile)) shutil.move(afile, newfile)
def cloneAGit(self, gitConf, includeUpdate=True): exists = os.path.exists(gitConf.path) if self.args.force and exists: slog.info('Removing git repostory "%s"' % gitConf.path) shutil.rmtree(gitConf.path) exists = False if exists: if includeUpdate: updateArgv = ['update', '--' + gitConf.name] if args.force: updateArgv.append('-f') updateArgs, parser = config.checkArgs(conf, updateArgv) update.build(conf, updateArgs, parser) else: git.clone(gitConf.git, gitConf.path)
def call(heroPath, sszPath, exportPath): parser = Parser(exportPath) # parse heros files = filter(herosFiles, get_files(heroPath, ["json"])) slog.info("parse: etc.json") parser.parseHero(files) # parse ssz files = filter(confFiles, get_files(sszPath, ["json"])) for path in files: slog.info("parse: %s", os.path.basename(path)) jsontxt = read_file(path) jsontxt = re.sub(r'\/\/.*$', '', jsontxt, flags=re.M) obj = json.loads(jsontxt) parser.parseConf(obj, os.path.basename(path).split('.')[0])
def cloneAGit(self, gitConf, includeUpdate=True): exists = os.path.exists(gitConf.path) if self.args.force and exists: slog.info('Removing git repostory "%s"'%gitConf.path) shutil.rmtree(gitConf.path) exists = False if exists: if includeUpdate: updateArgv = ['update', '--'+gitConf.name] if args.force: updateArgv.append('-f') updateArgs, parser = config.checkArgs(conf, updateArgv) update.build(conf, updateArgs, parser) else: git.clone(gitConf.git, gitConf.path)
def main(): add_log_handler(slog, handler=logging.StreamHandler(sys.stdout), debug=logging.DEBUG) gconf = wpcmd.base.Conf() workDir = os.path.abspath( os.path.join(os.path.split(os.path.abspath(__file__))[0], os.pardir)) confFile = os.path.join(workDir, "build.conf.py") if os.path.exists(confFile): gconf.readFromFile(confFile) else: gconf.init(workDir, confFile) slog.info('Please modify build.conf.py!') exit(1) gargs, subParser = wpcmd.base.check_args() if gargs: _build(gargs.sub_name, gconf, gargs, subParser)
def go(self): print(self.args) if self.args.type == 'post': self._show_post() elif self.args.type == 'page': self._show_page() elif self.args.type == 'draft': for adir, aname, afile in self.conf.get_mdfiles('draft'): slog.info(afile) elif self.args.type == 'option': self._show_options() elif self.args.type == 'tax': self._show_tax() elif self.args.type in ('term', 'category', 'tag'): self._show_term() elif self.args.type == 'medialib': self._show_medialib() elif self.args.type == 'mediaitem': self._show_mediaitem()
def main(): add_log_handler(slog, handler=logging.StreamHandler(sys.stdout), debug=logging.DEBUG) gconf = wpcmd.base.Conf() workDir = os.path.abspath( os.path.join(os.path.split( os.path.abspath(__file__))[0], os.pardir)) confFile = os.path.join(workDir, "build.conf.py") if os.path.exists(confFile): gconf.readFromFile(confFile) else: gconf.init(workDir, confFile) slog.info('Please modify build.conf.py!') exit(1) gargs, subParser = wpcmd.base.check_args() if gargs: _build(gargs.sub_name, gconf, gargs, subParser)
def _get_and_update_article_content(self, afile, istxt=False): html, meta, txt, medias = self._get_article_content(afile) if not html: return None, None, None, None attach = 0 if not meta.attachments: attach = 1 elif meta.attachments[0] == '$ATTACHMENTS': attach = 2 elif len(meta.attachments) > 0: attach = 3 if medias and attach > 0: txt, attachids = self._update_medias(medias, txt) idstxt = ','.join(attachids) if attach == 1: # Add attachments to the TOF. txt = 'Attachments: %s\n%s' % (idstxt, txt) slog.info('Fill attachments: %s.' % idstxt) elif attach == 2: txt = Template(txt).safe_substitute(ATTACHMENTS=idstxt) slog.info('Fill attachments: %s.' % idstxt) elif attach == 3: slog.info('Add new attachments: %s.' % idstxt) meta.attachments += attachids txt = re.sub(r'^Attachments: .*$', 'Attachments: ' + ','.join(meta.attachments), txt, 0, re.M) write_file(afile, txt) html, meta, txt, medias = self._get_article_content(txt, True) if medias: slog.error('Medias in the article is maybe wrong!') return None, None, None, None return html, meta, txt, medias
def _get_and_update_article_content(self, afile, istxt=False): html, meta, txt, medias = self._get_article_content(afile) if not html: return None, None, None, None attach = 0 if not meta.attachments: attach = 1 elif meta.attachments[0] == '$ATTACHMENTS': attach = 2 elif len(meta.attachments)>0: attach = 3 if medias and attach>0: txt,attachids = self._update_medias(medias, txt) idstxt = ','.join(attachids) if attach == 1: # Add attachments to the TOF. txt = 'Attachments: %s\n%s'%(idstxt, txt) slog.info('Fill attachments: %s.'%idstxt) elif attach == 2: txt = Template(txt).safe_substitute(ATTACHMENTS=idstxt) slog.info('Fill attachments: %s.'%idstxt) elif attach == 3: slog.info('Add new attachments: %s.'%idstxt) meta.attachments += attachids txt = re.sub(r'^Attachments: .*$', 'Attachments: '+ ','.join(meta.attachments), txt, 0, re.M) write_file(afile, txt) html, meta, txt, medias = self._get_article_content(txt, True) if medias: slog.error('Medias in the article is maybe wrong!') return None, None, None, None return html, meta, txt, medias
def _write_analytic(self): if args.name: match = re.match(r'^(\d*)-(\d*)$', args.name) a,b = None,None if match: if match.group(1): a = int(match.group(1)) if match.group(2): b = int(match.group(2)) dirlist = [] for f in list_dir(conf.get_path(args.dirname)): if not f.endswith('.md'): continue fname = int(f.split('.')[0]) if a != None: if fname < a: continue if b != None: if fname > b: continue dirlist.append(fname) abc = sorted(dirlist) slog.info('\n'.join([str(item) for item in sorted(dirlist)]))
def _update_medias(self, medias, txt): slog.info('Ready for upload some medias to WordPress.') attach_ids = [] urlre = re.compile(r'wp-content/.*/(\d{4}/\d{2}/).*') for path, name in medias: bits = None mediafile = self.conf.get_path(path) print(mediafile) with open(mediafile, 'rb') as m: bits = Binary(m.read()).data amedia = {} amedia['name'] = name amedia['type'] = mimetypes.guess_type(path)[0] amedia['bits'] = bits upd = self.wpcall(UploadFile(amedia)) txt = txt.replace(path, upd['url']) match = urlre.search(upd['url']) targetdir = self.conf.get_media(match.group(1)) if not os.path.exists(targetdir): os.makedirs(targetdir) attach_ids.append(upd['id']) shutil.move(mediafile, os.path.join(targetdir, name)) return txt, attach_ids
def _write_analytic(self): if args.name: match = re.match(r'^(\d*)-(\d*)$', args.name) a, b = None, None if match: if match.group(1): a = int(match.group(1)) if match.group(2): b = int(match.group(2)) dirlist = [] for f in list_dir(conf.get_path(args.dirname)): if not f.endswith('.md'): continue fname = int(f.split('.')[0]) if a != None: if fname < a: continue if b != None: if fname > b: continue dirlist.append(fname) abc = sorted(dirlist) slog.info('\n'.join([str(item) for item in sorted(dirlist)]))
def _new_draft(self): name = None if self.args.query: name = self.args.query[0] try: dfile, dname = self.conf.get_new_draft(name) except BlogError as e: slog.critical(e) return dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') subdict = { 'TITLE': '', 'DATE': dt, 'MODIFIED': dt, 'AUTHOR': self.conf.site.user, 'NICENAME': '', 'CATEGORY': 'technology', 'TAG': '', 'POSTTYPE': self.args.type, 'POSTSTATUS': 'draft', } write_by_templ(self.conf.get_path('templates', 'article.md'), dfile, subdict, True) slog.info('The draft file "%s" has created.' % dfile)
def print_result(self, result): if isinstance(result, WordPressTerm): slog.info( 'id=%s, group=%s, ' 'taxnomy_id=%s, name=%s, slug=%s, ' 'parent=%s, count=%d', result.id, result.group, result.taxonomy_id, result.name, result.slug, result.parent, result.count) elif isinstance(result, WordPressPost): slog.info( 'id=%s, date=%s, date_modified=%s, ' 'slug=%s, title=%s, post_status=%s, post_type=%s', result.id, str(result.date), str(result.date_modified), result.slug, result.title, result.post_status, result.post_type) elif isinstance(result, WordPressMedia): slog.info( 'id=%s, parent=%s, title=%s, ' 'description=%s, caption=%s, date_created=%s, link=%s, ' 'thumbnail=%s, metadata=%s', result.id, result.parent, result.title, result.description, result.caption, str(result.date_created), result.link, result.thumbnail, result.metadata) else: slog.info(result)
def _update_term(self): q = self.args.query term = None query = self.get_term_query() typ = query[0] if q and len(q) > 1: term = self.get_terms_from_wp(query, force=True) if not term: slog.error('The term %s is not existend.' % str(q)) return term = self.wpcall(GetTerm(typ, term.id)) if term: term.slug = q[0] term.name = q[1] if len(q) > 2: term.description = q[2] # post_get can not support parent. if term.taxonomy == 'post_tag': term.parent = None issucc = self.wpcall(EditTerm(term.id, term)) if issucc: self.conf.save_term(term, typ) self.conf.save_to_file() slog.info('The term %s(%s) has saved.' % (term.slug, term.id)) else: slog.info('The term %s(%s) saves unsuccessfully.' % (term.slug, term.id)) else: slog.info('Can not get term "%s".' % typ) else: term = self.get_terms_from_wp(query, force=True) if term: slog.info('Update terms done.') else: slog.warning('No terms.')
def print_result(self, result): if isinstance(result, WordPressTerm): slog.info('id=%s, group=%s, ' 'taxnomy_id=%s, name=%s, slug=%s, ' 'parent=%s, count=%d', result.id, result.group, result.taxonomy_id, result.name, result.slug, result.parent, result.count) elif isinstance(result, WordPressPost): slog.info('id=%s, date=%s, date_modified=%s, ' 'slug=%s, title=%s, post_status=%s, post_type=%s', result.id, str(result.date), str(result.date_modified), result.slug, result.title, result.post_status, result.post_type) elif isinstance(result, WordPressMedia): slog.info('id=%s, parent=%s, title=%s, ' 'description=%s, caption=%s, date_created=%s, link=%s, ' 'thumbnail=%s, metadata=%s', result.id, result.parent, result.title, result.description, result.caption, str(result.date_created), result.link, result.thumbnail, result.metadata) else: slog.info(result)
def _update_an_article(self, postid): afile, aname = self.conf.get_article(postid, self.args.type) html, meta, txt, medias = self._get_and_update_article_content(afile) if not html: return resultclass = WordPressPost if self.args.type == 'page': postid = meta.postid resultclass = WordPressPage post = self.wpcall(GetPost(postid, result_class=resultclass)) if not post: slog.warning('No post "%s"!'%postid) return slog.info('Old article:') self.print_results(post) post.title = meta.title post.user = meta.author post.slug = meta.nicename post.date = meta.date post.content = html post.post_status = meta.poststatus if meta.modified: post.date_modified = meta.modified terms = self.get_terms_from_meta(meta.category, meta.tags) if terms: post.terms = terms elif self.args.type == 'post': slog.warning('Please provide some terms.') return succ = self.wpcall(EditPost(postid, post)) if succ == None: return if succ: slog.info('Update %s successfully!'%postid) else: slog.info('Update %s fail!'%postid)
def _update_an_article(self, postid): afile, aname = self.conf.get_article(postid, self.args.type) html, meta, txt, medias = self._get_and_update_article_content(afile) if not html: return resultclass = WordPressPost if self.args.type == 'page': postid = meta.postid resultclass = WordPressPage post = self.wpcall(GetPost(postid, result_class=resultclass)) if not post: slog.warning('No post "%s"!' % postid) return slog.info('Old article:') self.print_results(post) post.title = meta.title post.user = meta.author post.slug = meta.nicename post.date = meta.date post.content = html post.post_status = meta.poststatus if meta.modified: post.date_modified = meta.modified terms = self.get_terms_from_meta(meta.category, meta.tags) if terms: post.terms = terms elif self.args.type == 'post': slog.warning('Please provide some terms.') return succ = self.wpcall(EditPost(postid, post)) if succ == None: return if succ: slog.info('Update %s successfully!' % postid) else: slog.info('Update %s fail!' % postid)