def download_repo(self, commit_url, repo_file): repo_zip_url = commit_url.replace('commit', 'archive') + '.zip' try: print('Downloading {0}...'.format(repo_zip_url)) if not os.path.isfile(repo_file): download_file(repo_zip_url, repo_file) finally: print('finished.')
def main(date_today, tag, version): global download_dir repo = 'https://git.door43.org/Door43/en-tq' download_dir = tempfile.mkdtemp(prefix='tempTQ_') download_url = join_url_parts(repo, 'archive', '{0}.zip'.format(tag)) downloaded_file = os.path.join(download_dir, 'tQ.zip') # download the repository try: print('Downloading {0}...'.format(download_url), end=' ') download_file(download_url, downloaded_file) finally: print('finished.') try: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, download_dir) finally: print('finished.') # examine the repository source_root = os.path.join(download_dir, 'en-tq', 'content') books = [x for x in os.listdir(source_root) if os.path.isdir(os.path.join(source_root, x))] for book in books: print('Processing {}.'.format(book)) book_dir = os.path.join(source_root, book) api_path = os.path.join(api_v2, book, 'en') # noinspection PyUnresolvedReferences book_questions = [] # type: list[dict] for entry in os.listdir(book_dir): file_name = os.path.join(book_dir, entry) # we are only processing files if not os.path.isfile(file_name): continue # we are only processing markdown files if entry[-3:] != '.md': continue book_questions.append(get_cq(file_name)) # Check to see if there are published questions in this book pub_check = [x['cq'] for x in book_questions if len(x['cq']) > 0] if len(pub_check) == 0: print('No published questions for {0}'.format(book)) continue book_questions.sort(key=lambda y: y['id']) book_questions.append({'date_modified': date_today, 'version': version}) write_file('{0}/questions.json'.format(api_path), book_questions, indent=2) print() print('Updating the catalogs...', end=' ') update_catalog() print('finished.')
def main(date_today, tag, version): """ :param str|unicode date_today: :param str|unicode tag: :param str|unicode version: :return: """ global download_dir, tw_aliases repo = 'https://git.door43.org/Door43/en-tw' download_dir = tempfile.mkdtemp(prefix='tempTW_') download_url = join_url_parts(repo, 'archive', '{0}.zip'.format(tag)) downloaded_file = os.path.join(download_dir, 'tW.zip') # download the repository try: print('Downloading {0}...'.format(download_url), end=' ') download_file(download_url, downloaded_file) finally: print('finished.') try: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, download_dir) finally: print('finished.') # examine the repository tw_list = [] for root, dirs, files in os.walk( os.path.join(download_dir, 'en-tw', 'content')): for f in files: file_name = os.path.join(root, f) tw = get_tw(file_name) if tw: tw_list.append(tw) for i in tw_list: # type: dict if i['id'] in tw_aliases: i['aliases'] = [x for x in tw_aliases[i['id']] if x != i['term']] tw_list.sort(key=lambda y: len(y['term']), reverse=True) tw_list.append({'date_modified': date_today, 'version': version}) api_path = os.path.join(api_v2, 'bible', 'en') write_file('{0}/terms.json'.format(api_path), tw_list, indent=2) print() print('Updating the catalogs...', end=' ') update_catalog() print('finished.')
def download_repo(commit_url, repo_dir): repo_zip_url = commit_url.replace('commit', 'archive') + '.zip' repo_zip_file = os.path.join(tempfile.gettempdir(), repo_zip_url.rpartition('/')[2]) try: print('Downloading {0}...'.format(repo_zip_url)) if not os.path.isfile(repo_zip_file): download_file(repo_zip_url, repo_zip_file) finally: print('finished.') try: print('Unzipping {0}...'.format(repo_zip_file)) unzip(repo_zip_file, repo_dir) finally: print('finished.')
def download_source_file(source_url, destination_folder): """ Downloads the specified source file and unzips it if necessary. :param str source_url: The URL of the file to download :param str destination_folder: The directory where the downloaded file should be unzipped :return: None """ AppSettings.logger.debug( f"download_source_file( {source_url}, {destination_folder} )") source_filepath = os.path.join(destination_folder, source_url.rpartition(os.path.sep)[2]) AppSettings.logger.debug(f"source_filepath: {source_filepath}") try: AppSettings.logger.info(f"Downloading {source_url} …") # if the file already exists, remove it, we want a fresh copy if os.path.isfile(source_filepath): os.remove(source_filepath) download_file(source_url, source_filepath) finally: AppSettings.logger.debug("Downloading finished.") if source_url.lower().endswith('.zip'): try: AppSettings.logger.debug(f"Unzipping {source_filepath} …") # TODO: This is unsafe if the zipfile comes from an untrusted source unzip(source_filepath, destination_folder) finally: AppSettings.logger.debug("Unzipping finished.") # clean up the downloaded zip file if os.path.isfile(source_filepath): os.remove(source_filepath) str_filelist = str(os.listdir(destination_folder)) str_filelist_adjusted = str_filelist if len(str_filelist)<1500 \ else f'{str_filelist[:1000]} …… {str_filelist[-500:]}' AppSettings.logger.debug( f"Destination folder '{destination_folder}' now has: {str_filelist_adjusted}" )
def main(git_repo, tag, domain): global download_dir, out_template # clean up the git repo url if git_repo[-4:] == '.git': git_repo = git_repo[:-4] if git_repo[-1:] == '/': git_repo = git_repo[:-1] # initialize some variables today = ''.join(str(datetime.date.today()).rsplit('-')[0:3]) # str(datetime.date.today()) download_dir = '/tmp/{0}'.format(git_repo.rpartition('/')[2]) make_dir(download_dir) downloaded_file = '{0}/{1}.zip'.format(download_dir, git_repo.rpartition('/')[2]) file_to_download = join_url_parts(git_repo, 'archive/' + tag + '.zip') manifest = None metadata_obj = None content_dir = '' usfm_file = None # download the repository try: print('Downloading {0}...'.format(file_to_download), end=' ') if not os.path.isfile(downloaded_file): download_file(file_to_download, downloaded_file) finally: print('finished.') try: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, download_dir) finally: print('finished.') # examine the repository for root, dirs, files in os.walk(download_dir): if 'manifest.json' in files: # read the manifest try: print('Reading the manifest...', end=' ') manifest = load_json_object(os.path.join(root, 'manifest.json')) content_dir = root # look for the usfm file for the whole book found_usfm = glob(os.path.join(content_dir, '*.usfm')) if len(found_usfm) == 1: usfm_file = os.path.join(content_dir, found_usfm[0]) finally: print('finished.') if 'meta.json' in files: # read the metadata try: print('Reading the metadata...', end=' ') metadata_obj = BibleMetaData(os.path.join(root, 'meta.json')) finally: print('finished.') # if we have everything, exit the loop if manifest and metadata_obj: break # check for valid repository structure if not manifest: print_error('Did not find manifest.json in {}'.format(git_repo)) sys.exit(1) if not metadata_obj: print_error('Did not find meta.json in {}'.format(git_repo)) sys.exit(1) # get the versification data print('Getting versification info...', end=' ') vrs = Bible.get_versification(metadata_obj.versification) # type: list<Book> # get the book object for this repository book = next((b for b in vrs if b.book_id.lower() == manifest['project']['id']), None) # type: Book if not book: print_error('Book versification data was not found for "{}"'.format(manifest['project']['id'])) sys.exit(1) print('finished') if usfm_file: read_unified_file(book, usfm_file) else: read_chunked_files(book, content_dir, metadata_obj) # do basic checks print('Running USFM checks...', end=' ') book.verify_chapters_and_verses(True) if book.validation_errors: print_error('These USFM errors must be corrected before publishing can continue.') sys.exit(1) else: print('finished.') # insert paragraph markers print('Inserting paragraph markers...', end=' ') Bible.insert_paragraph_markers(book) print('finished.') # get chunks for this book print('Chunking the text...', end=' ') Bible.chunk_book(metadata_obj.versification, book) book.apply_chunks() print('finished.') # save the output out_dir = out_template.format(domain, metadata_obj.slug) # produces something like '01-GEN.usfm' book_file_name = '{0}-{1}.usfm'.format(str(book.number).zfill(2), book.book_id) print('Writing ' + book_file_name + '...', end=' ') write_file('{0}/{1}'.format(out_dir, book_file_name), book.usfm) print('finished.') # look for an existing status.json file print('Updating the status for {0}...'.format(metadata_obj.lang), end=' ') status_file = '{0}/status.json'.format(out_dir) if os.path.isfile(status_file): status = BibleStatus(status_file) else: status = BibleStatus() status.update_from_meta_data(metadata_obj) # add this book to the list of "books_published" status.add_book_published(book) # update the "date_modified" status.date_modified = today print('finished.') # save the status.json file print('Writing status.json...', end=' ') status_json = json.dumps(status, sort_keys=True, indent=2, cls=BibleEncoder) write_file(status_file, status_json) print('finished') # let the API know it is there print('Publishing to the API...') with api_publish(out_dir) as api: api.run() print('Finished publishing to the API.') # update the catalog print() print('Updating the catalogs...', end=' ') update_catalog() print('finished.') print_notice('Check {0} and do a git push'.format(out_dir))
def main(git_repo, tag): global download_dir # clean up the git repo url if git_repo[-4:] == '.git': git_repo = git_repo[:-4] if git_repo[-1:] == '/': git_repo = git_repo[:-1] # initialize some variables download_dir = '/tmp/{0}'.format(git_repo.rpartition('/')[2]) make_dir(download_dir) downloaded_file = '{0}/{1}.zip'.format(download_dir, git_repo.rpartition('/')[2]) file_to_download = join_url_parts(git_repo, 'archive/' + tag + '.zip') metadata_obj = None content_dir = None toc_obj = None # download the repository try: print('Downloading {0}...'.format(file_to_download), end=' ') if not os.path.isfile(downloaded_file): download_file(file_to_download, downloaded_file) finally: print('finished.') try: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, download_dir) finally: print('finished.') # examine the repository for root, dirs, files in os.walk(download_dir): if 'meta.yaml' in files: # read the metadata try: print('Reading the metadata...', end=' ') metadata_obj = TAMetaData(os.path.join(root, 'meta.yaml')) finally: print('finished.') if 'toc.yaml' in files: # read the table of contents try: print('Reading the toc...', end=' ') toc_obj = TATableOfContents(os.path.join(root, 'toc.yaml')) finally: print('finished.') if 'content' in dirs: content_dir = os.path.join(root, 'content') # if we have everything, exit the loop if content_dir and metadata_obj and toc_obj: break # check for valid repository structure if not metadata_obj: print_error('Did not find meta.yaml in {}'.format(git_repo)) sys.exit(1) if not content_dir: print_error('Did not find the content directory in {}'.format(git_repo)) sys.exit(1) if not toc_obj: print_error('Did not find toc.yaml in {}'.format(git_repo)) sys.exit(1) # check for missing pages check_missing_pages(toc_obj, content_dir) # generate the pages print('Generating the manual...', end=' ') manual = TAManual(metadata_obj, toc_obj) manual.load_pages(content_dir) print('finished.') file_name = os.path.join(get_output_dir(), '{0}_{1}.json'.format(manual.meta.manual, manual.meta.volume)) print('saving to {0} ...'.format(file_name), end=' ') content = json.dumps(manual, sort_keys=True, indent=2, cls=TAEncoder) write_file(file_name, content) print('finished.')
zipDir = inDir # + repoName zipFile = inDir + repoName + ".tar.gz" myLog( "info", " zipDir: " + zipDir ) myLog( "info", " zipFile: " + zipFile ) orgUmask = os.umask( 0 ) #try: # get repo referenced in notification if True: myLog( "info", "src: " + url + " dst: " + zipFile ) try: if not os.path.exists( zipDir ): os.makedirs( zipDir ) if not os.path.exists( inDir ): os.makedirs( inDir ) download_file( url, zipFile ) try: res = subprocess.check_output( [ "tar", "-xzf", zipFile, "-C", inDir ], shell=False ) except( OSError, e ): myLog( "error", "cannot tar: " + zipFile + " Error: " + e.strerror ) print( "506" ) sys.exit( 6 ) except( OSError, e ): myLog( "error", "Cannot make working directory: " + zipDir + \ " Error: " + e.strerror ) print( "507" ) sys.exit( 7 ) #except:
def import_obs(lang_data, git_repo, door43_url, no_pdf): global download_dir, root, api_dir lang_code = lang_data['lc'] # pre-flight checklist link_source = '/var/www/vhosts/api.unfoldingword.org/httpdocs/obs/jpg/1/en' if not os.path.isdir(link_source): print_error('Image source directory not found: {0}.'.format(link_source)) sys.exit(1) if git_repo[-1:] != '/': git_repo += '/' if no_pdf: tools_dir = None else: tools_dir = '/var/www/vhosts/door43.org/tools' if not os.path.isdir(tools_dir): tools_dir = os.path.expanduser('~/Projects/tools') # prompt if tools not found if not os.path.isdir(tools_dir): tools_dir = None print_notice('The tools directory was not found. The PDF cannot be generated.') resp = prompt('Do you want to continue without generating a PDF? [Y|n]: ') if resp != '' and resp != 'Y' and resp != 'y': sys.exit(0) if git_repo: if git_repo[-1:] == '/': git_repo = git_repo[:-1] download_dir = '/tmp/{0}'.format(git_repo.rpartition('/')[2]) make_dir(download_dir) # make sure OBS is initialized on Dokuwiki test_dir = root.format(lang_code, '') if not os.path.isdir(test_dir): print_warning('It seems OBS has not been initialized on Door43.org for {0}'.format(lang_code)) sys.exit(1) elif door43_url: print_error('URL not yet implemented.') return else: print_error('Source not provided.') return # get the source files from the git repository if 'github' in git_repo: # https://github.com/unfoldingWord/obs-ru # https://raw.githubusercontent.com/unfoldingWord/obs-ru/master/obs-ru.json raw_url = git_repo.replace('github.com', 'raw.githubusercontent.com') elif 'git.door43.org' in git_repo: raw_url = join_url_parts(git_repo, 'raw') else: # this is to keep IntelliJ happy, is should have been caught in sub main return # download needed files from the repository file_suffix = '-{0}.json'.format(lang_code.lower()) files_to_download = [ join_url_parts(raw_url, 'master/obs' + file_suffix), join_url_parts(raw_url, 'master/status' + file_suffix) ] for file_to_download in files_to_download: downloaded_file = os.path.join(download_dir, file_to_download.rpartition('/')[2]) try: print('Downloading {0}...'.format(file_to_download), end=' ') download_file(file_to_download, downloaded_file) finally: print('finished.') # read the files from the git repository file_suffix = '-{0}.json'.format(lang_code.lower()) obs_obj = None status_obj = None # front_matter_found = False # back_matter_found = False try: print('Examining the files...', end=' ') for root_path, dirs, files in os.walk(download_dir): if not len(files): continue for git_file in files: if git_file == 'obs' + file_suffix: obs_obj = OBS(os.path.join(root_path, git_file)) elif git_file == 'status' + file_suffix: status_obj = OBSStatus(os.path.join(root_path, git_file)) # elif 'front-matter' in git_file: # front_matter_found = True # elif 'back-matter' in git_file: # back_matter_found = True finally: print('finished.') # check data integrity if not obs_obj.verify_all(): sys.exit(1) if not status_obj: print_error('The file "status{0}" was not found in the git repository.'.format(file_suffix)) sys.exit(1) # create Dokuwiki pages print_ok('Begin: ', 'creating Dokuwiki pages.') for chapter in obs_obj.chapters: chapter_title = '====== {0} ======'.format(chapter['title']) chapter_ref = '//{0}//'.format(chapter['ref']) chapter_body = '' chapter_num = chapter['number'].zfill(2) for frame in chapter['frames']: chapter_body += '{{{{{0}?direct&}}}}\n\n{1}\n\n'.format(frame['img'], frame['text']) file_name = root.format(lang_code, chapter_num + '.txt') print(' Writing {0}'.format(file_name)) with codecs.open(file_name, 'w', 'utf-8-sig') as out_file: out_file.write('{0}\n\n{1}{2}\n'.format(chapter_title, chapter_body, chapter_ref)) print_ok('Finished: ', 'creating Dokuwiki pages.') # Create image symlinks on api.unfoldingword.org try: print('Creating symlink to images directory...', end=' ') link_name = '/var/www/vhosts/api.unfoldingword.org/httpdocs/obs/jpg/1/{0}'.format(lang_code.lower()) if not os.path.isfile(link_name) and not os.path.isdir(link_name) and not os.path.islink(link_name): os.symlink(link_source, link_name) finally: print('finished.') # Create PDF via ConTeXt if not no_pdf and tools_dir and os.path.isdir(tools_dir): try: print_ok('Beginning: ', 'PDF generation.') script_file = os.path.join(tools_dir, 'obs/book/pdf_export.sh') out_dir = api_dir.format(lang_code) make_dir(out_dir) process = subprocess.Popen([script_file, '-l', lang_code, '-c', status_obj.checking_level, '-v', status_obj.version, '-o', out_dir], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # wait for the process to terminate out, err = process.communicate() exit_code = process.returncode out = out.strip().decode('utf-8') err = err.strip().decode('utf-8') # the error message may be in stdout if exit_code != 0: if not err: err = out out = None if err: print_error(err, 2) if out: print(' ' + out) print(' PDF subprocess finished with exit code {0}'.format(exit_code)) finally: print_ok('Finished:', 'generating PDF.')
def main(git_repo, tag, domain): global download_dir, out_template # clean up the git repo url if git_repo[-4:] == '.git': git_repo = git_repo[:-4] if git_repo[-1:] == '/': git_repo = git_repo[:-1] # initialize some variables today = ''.join(str(datetime.date.today()).rsplit('-')[0:3]) download_dir = '/tmp/{0}'.format(git_repo.rpartition('/')[2]) make_dir(download_dir) downloaded_file = '{0}/{1}.zip'.format(download_dir, git_repo.rpartition('/')[2]) file_to_download = join_url_parts(git_repo, 'archive/' + tag + '.zip') books_published = {} metadata_obj = None usfm_dir = None # download the repository try: print('Downloading {0}...'.format(file_to_download), end=' ') if not os.path.isfile(downloaded_file): download_file(file_to_download, downloaded_file) finally: print('finished.') try: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, download_dir) finally: print('finished.') # examine the repository for root, dirs, files in os.walk(download_dir): if 'meta.json' in files: # read the metadata try: print('Reading the metadata...', end=' ') metadata_obj = BibleMetaData(os.path.join(root, 'meta.json')) finally: print('finished.') if 'usfm' in dirs: usfm_dir = os.path.join(root, 'usfm') # if we have everything, exit the loop if usfm_dir and metadata_obj: break # check for valid repository structure if not metadata_obj: print_error('Did not find meta.json in {}'.format(git_repo)) sys.exit(1) if not usfm_dir: print_error('Did not find the usfm directory in {}'.format(git_repo)) sys.exit(1) # get the versification data vrs = Bible.get_versification(metadata_obj.versification) # type: list<Book> out_dir = out_template.format(domain, metadata_obj.slug, metadata_obj.lang) # walk through the usfm files usfm_files = glob(os.path.join(usfm_dir, '*.usfm')) errors_found = False for usfm_file in usfm_files: # read the file with codecs.open(usfm_file, 'r', 'utf-8') as in_file: book_text = in_file.read() # get the book id book_search = id_re.search(book_text) if not book_search: print_error('Book id not found in {}'.format(usfm_file)) sys.exit(1) book_id = book_search.group(1) print('Beginning {}...'.format(book_id), end=' ') # get book versification info book = next((b for b in vrs if b.book_id == book_id), None) if not book: print_error('Book versification data was not found for "{}"'.format(book_id)) sys.exit(1) # remove \s5 lines book_text = s5_re.sub('', book_text) # get the usfm for the book book.set_usfm(book_text) # do basic checks book.verify_usfm_tags() book.verify_chapters_and_verses(True) if book.validation_errors: errors_found = True # get chunks for this book Bible.chunk_book(metadata_obj.versification, book) book.apply_chunks() # produces something like '01-GEN.usfm' book_file_name = '{0}-{1}.usfm'.format(str(book.number).zfill(2), book.book_id) print('Writing ' + book_file_name + '...', end=' ') write_file('{0}/{1}'.format(out_dir, book_file_name), book.usfm) meta = ['Bible: OT'] if book.number > 39: meta = ['Bible: NT'] books_published[book.book_id.lower()] = {'name': book.name, 'meta': meta, 'sort': str(book.number).zfill(2), 'desc': '' } print('finished.') # stop if errors were found if errors_found: print_error('These USFM errors must be corrected before publishing can continue.') sys.exit(1) print('Writing status.json...', end=' ') status = {"slug": '{0}'.format(metadata_obj.slug.lower()), "name": metadata_obj.name, "lang": metadata_obj.lang, "date_modified": today, "books_published": books_published, "status": {"checking_entity": metadata_obj.checking_entity, "checking_level": metadata_obj.checking_level, "comments": metadata_obj.comments, "contributors": metadata_obj.contributors, "publish_date": today, "source_text": metadata_obj.source_text, "source_text_version": metadata_obj.source_text_version, "version": metadata_obj.version } } write_file('{0}/status.json'.format(out_dir), status, indent=2) print('finished.') print() print('Publishing to the API...') with api_publish(out_dir) as api: api.run() print('Finished publishing to the API.') # update the catalog print() print('Updating the catalogs...', end=' ') update_catalog() print('finished.') print_notice('Check {0} and do a git push'.format(out_dir))
def run(self): try: self.temp_dir = tempfile.mkdtemp(prefix='txOBS_') # clean up the git repo url if self.source_repo_url[-4:] == '.git': self.source_repo_url = self.source_repo_url[:-4] if self.source_repo_url[-1:] == '/': self.source_repo_url = self.source_repo_url[:-1] # download the archive file_to_download = join_url_parts(self.source_repo_url, 'archive/master.zip') repo_dir = self.source_repo_url.rpartition('/')[2] downloaded_file = os.path.join(self.temp_dir, repo_dir + '.zip') try: print('Downloading {0}...'.format(file_to_download), end=' ') if not os.path.isfile(downloaded_file): download_file(file_to_download, downloaded_file) finally: print('finished.') # unzip the archive try: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, self.temp_dir) finally: print('finished.') # get the manifest try: print('Reading the manifest...', end=' ') manifest = load_json_object(os.path.join(self.temp_dir, 'manifest.json')) finally: print('finished.') # create output directory make_dir(self.output_directory) # read the markdown files and output html files try: print('Processing the OBS markdown files') files_to_process = [] for i in range(1, 51): files_to_process.append(str(i).zfill(2) + '.md') current_dir = os.path.dirname(inspect.stack()[0][1]) with codecs.open(os.path.join(current_dir, 'template.html'), 'r', 'utf-8-sig') as html_file: html_template = html_file.read() for file_to_process in files_to_process: # read the markdown file file_name = os.path.join(self.temp_dir, repo_dir, 'content', file_to_process) with codecs.open(file_name, 'r', 'utf-8-sig') as md_file: md = md_file.read() html = markdown.markdown(md) html = TransformOBS.dir_re.sub(r'\1\n' + html + r'\n\2', html_template) write_file(os.path.join(self.output_directory, file_to_process.replace('.md', '.html')), html) except IOError as ioe: print_error('{0}: {1}'.format(ioe.strerror, ioe.filename)) self.errors.append(ioe) except Exception as e: print_error(e.message) self.errors.append(e) finally: print('finished.') except Exception as e: print_error(e.message) self.errors.append(e)
def handle(event, context): # Getting data from payload which is the JSON that was sent from tx-manager if 'data' not in event: raise Exception('"data" not in payload') job = event['data'] env_vars = {} if 'vars' in event and isinstance(event['vars'], dict): env_vars = event['vars'] # Getting the bucket to where we will unzip the converted files for door43.org. It is different from # production and testing, thus it is an environment variable the API Gateway gives us if 'cdn_bucket' not in env_vars: raise Exception('"cdn_bucket" was not in payload') cdn_handler = S3Handler(env_vars['cdn_bucket']) if 'identifier' not in job or not job['identifier']: raise Exception('"identifier" not in payload') owner_name, repo_name, commit_id = job['identifier'].split('/') s3_commit_key = 'u/{0}/{1}/{2}'.format( owner_name, repo_name, commit_id ) # The identifier is how to know which username/repo/commit this callback goes to # Download the ZIP file of the converted files converted_zip_url = job['output'] converted_zip_file = os.path.join(tempfile.gettempdir(), converted_zip_url.rpartition('/')[2]) try: print('Downloading converted zip file from {0}...'.format( converted_zip_url)) if not os.path.isfile(converted_zip_file): download_file(converted_zip_url, converted_zip_file) finally: print('finished.') # Unzip the archive unzip_dir = tempfile.mkdtemp(prefix='unzip_') try: print('Unzipping {0}...'.format(converted_zip_file)) unzip(converted_zip_file, unzip_dir) finally: print('finished.') # Upload all files to the cdn_bucket with the key of <user>/<repo_name>/<commit> of the repo for root, dirs, files in os.walk(unzip_dir): for f in sorted(files): path = os.path.join(root, f) key = s3_commit_key + path.replace(unzip_dir, '') print('Uploading {0} to {1}'.format(f, key)) cdn_handler.upload_file(path, key) # Now download the existing build_log.json file, update it and upload it back to S3 build_log_json = cdn_handler.get_json(s3_commit_key + '/build_log.json') build_log_json['started_at'] = job['started_at'] build_log_json['ended_at'] = job['ended_at'] build_log_json['success'] = job['success'] build_log_json['status'] = job['status'] build_log_json['message'] = job['message'] if 'log' in job and job['log']: build_log_json['log'] = job['log'] else: build_log_json['log'] = [] if 'warnings' in job and job['warnings']: build_log_json['warnings'] = job['warnings'] else: build_log_json['warnings'] = [] if 'errors' in job and job['errors']: build_log_json['errors'] = job['errors'] else: build_log_json['errors'] = [] build_log_file = os.path.join(tempfile.gettempdir(), 'build_log_finished.json') write_file(build_log_file, build_log_json) cdn_handler.upload_file(build_log_file, s3_commit_key + '/build_log.json', 0) # Download the project.json file for this repo (create it if doesn't exist) and update it project_json_key = 'u/{0}/{1}/project.json'.format(owner_name, repo_name) project_json = cdn_handler.get_json(project_json_key) project_json['user'] = owner_name project_json['repo'] = repo_name project_json['repo_url'] = 'https://git.door43.org/{0}/{1}'.format( owner_name, repo_name) commit = { 'id': commit_id, 'created_at': job['created_at'], 'status': job['status'], 'success': job['success'], 'started_at': None, 'ended_at': None } if 'started_at' in job: commit['started_at'] = job['started_at'] if 'ended_at' in job: commit['ended_at'] = job['ended_at'] if 'commits' not in project_json: project_json['commits'] = [] commits = [] for c in project_json['commits']: if c['id'] != commit_id: commits.append(c) commits.append(commit) project_json['commits'] = commits project_file = os.path.join(tempfile.gettempdir(), 'project.json') write_file(project_file, project_json) cdn_handler.upload_file(project_file, project_json_key, 0) print('Finished deploying to cdn_bucket. Done.')
def main(git_repo, tag, no_pdf): global download_dir # clean up the git repo url if git_repo[-4:] == '.git': git_repo = git_repo[:-4] if git_repo[-1:] == '/': git_repo = git_repo[:-1] # initialize some variables today = ''.join(str(datetime.date.today()).rsplit( str('-'))[0:3]) # str(datetime.date.today()) download_dir = '/tmp/{0}'.format(git_repo.rpartition('/')[2]) make_dir(download_dir) downloaded_file = '{0}/{1}.zip'.format(download_dir, git_repo.rpartition('/')[2]) file_to_download = join_url_parts(git_repo, 'archive/{0}.zip'.format(tag)) manifest = None status = None # type: OBSStatus content_dir = None # download the repository try: print('Downloading {0}...'.format(file_to_download), end=' ') if not os.path.isfile(downloaded_file): download_file(file_to_download, downloaded_file) finally: print('finished.') try: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, download_dir) finally: print('finished.') # examine the repository for root, dirs, files in os.walk(download_dir): if 'manifest.json' in files: # read the manifest try: print('Reading the manifest...', end=' ') content_dir = root manifest = load_json_object(os.path.join( root, 'manifest.json')) status = OBSStatus.from_manifest(manifest) finally: print('finished.') if 'content' in dirs: content_dir = os.path.join(root, 'content') # if we have everything, exit the loop if content_dir and manifest and status: break # check for valid repository structure if not manifest: print_error('Did not find manifest.json in {}'.format(git_repo)) sys.exit(1) print('Initializing OBS object...', end=' ') lang = manifest['language']['slug'] obs_obj = OBS() obs_obj.date_modified = today obs_obj.direction = manifest['language']['dir'] obs_obj.language = lang print('finished') obs_obj.chapters = load_obs_chapters(content_dir) obs_obj.chapters.sort(key=lambda c: int(c['number'])) if not obs_obj.verify_all(): print_error('Quality check did not pass.') sys.exit(1) print('Loading languages...', end=' ') lang_dict = OBS.load_lang_strings() print('finished.') print('Loading the catalog...', end=' ') export_dir = '/var/www/vhosts/door43.org/httpdocs/exports' cat_path = os.path.join(export_dir, 'obs-catalog.json') catalog = load_json_object(cat_path, []) print('finished') print('Getting already published languages...', end=' ') json_lang_file_path = os.path.join(export_dir, lang, 'obs', 'obs-{0}.json'.format(lang)) if lang not in lang_dict: print("Configuration for language {0} missing.".format(lang)) sys.exit(1) print('finished.') updated = update_language_catalog(lang, obs_obj.direction, status, today, lang_dict, catalog) print('Writing the OBS file to the exports directory...', end=' ') cur_json = json.dumps(obs_obj, sort_keys=True, cls=OBSEncoder) if updated: ([x for x in catalog if x['language'] == lang][0]['date_modified']) = today # noinspection PyTypeChecker write_file(json_lang_file_path.replace('.txt', '.json'), cur_json) print('finished.') export_to_api(lang, status, today, cur_json) cat_json = json.dumps(catalog, sort_keys=True, cls=OBSEncoder) write_file(cat_path, cat_json) # update the catalog print_ok('STARTING: ', 'updating the catalogs.') update_catalog() print_ok('FINISHED: ', 'updating the catalogs.') if no_pdf: return create_pdf(lang, status.checking_level, status.version)
def handle(event, context): try: job = retrieve(event, 'data', 'payload') env_vars = retrieve(event, 'vars', 'payload') cdn_bucket = retrieve(env_vars, 'cdn_bucket', 'payload') identifier = retrieve(job, 'identifier', 'job') cdn_handler = S3Handler(cdn_bucket) owner_name, repo_name, commit_id = identifier.split('/') s3_commit_key = 'u/{0}/{1}/{2}'.format( owner_name, repo_name, commit_id ) # The identifier is how to know which username/repo/commit this callback goes to # Download the ZIP file of the converted files converted_zip_url = job['output'] converted_zip_file = os.path.join(tempfile.gettempdir(), converted_zip_url.rpartition('/')[2]) try: print('Downloading converted zip file from {0}...'.format( converted_zip_url)) if not os.path.isfile(converted_zip_file): download_file(converted_zip_url, converted_zip_file) finally: print('finished.') # Unzip the archive unzip_dir = tempfile.mkdtemp(prefix='unzip_') try: print('Unzipping {0}...'.format(converted_zip_file)) unzip(converted_zip_file, unzip_dir) finally: print('finished.') # Upload all files to the cdn_bucket with the key of <user>/<repo_name>/<commit> of the repo for root, dirs, files in os.walk(unzip_dir): for f in sorted(files): path = os.path.join(root, f) key = s3_commit_key + path.replace(unzip_dir, '') print('Uploading {0} to {1}'.format(f, key)) cdn_handler.upload_file(path, key) # Download the project.json file for this repo (create it if doesn't exist) and update it project_json_key = 'u/{0}/{1}/project.json'.format( owner_name, repo_name) project_json = cdn_handler.get_json(project_json_key) project_json['user'] = owner_name project_json['repo'] = repo_name project_json['repo_url'] = 'https://git.door43.org/{0}/{1}'.format( owner_name, repo_name) commit = { 'id': commit_id, 'created_at': job['created_at'], 'status': job['status'], 'success': job['success'], 'started_at': None, 'ended_at': None } if 'started_at' in job: commit['started_at'] = job['started_at'] if 'ended_at' in job: commit['ended_at'] = job['ended_at'] if 'commits' not in project_json: project_json['commits'] = [] commits = [] for c in project_json['commits']: if c['id'] != commit_id: commits.append(c) commits.append(commit) project_json['commits'] = commits project_file = os.path.join(tempfile.gettempdir(), 'project.json') write_file(project_file, project_json) cdn_handler.upload_file(project_file, project_json_key, 0) # Now download the existing build_log.json file, update it and upload it back to S3 build_log_json = cdn_handler.get_json(s3_commit_key + '/build_log.json') build_log_json['started_at'] = job['started_at'] build_log_json['ended_at'] = job['ended_at'] build_log_json['success'] = job['success'] build_log_json['status'] = job['status'] build_log_json['message'] = job['message'] if 'log' in job and job['log']: build_log_json['log'] = job['log'] else: build_log_json['log'] = [] if 'warnings' in job and job['warnings']: build_log_json['warnings'] = job['warnings'] else: build_log_json['warnings'] = [] if 'errors' in job and job['errors']: build_log_json['errors'] = job['errors'] else: build_log_json['errors'] = [] build_log_file = os.path.join(tempfile.gettempdir(), 'build_log_finished.json') write_file(build_log_file, build_log_json) cdn_handler.upload_file(build_log_file, s3_commit_key + '/build_log.json', 0) print('Finished deploying to cdn_bucket. Done.') return build_log_json except Exception as e: print("Failed doing callback:") print(e) raise Exception('Bad Request: {0}'.format(e))
def run(self): # download the archive file_to_download = self.source_url filename = self.source_url.rpartition('/')[2] downloaded_file = os.path.join(self.download_dir, filename) self.log_message('Downloading {0}...'.format(file_to_download)) if not os.path.isfile(downloaded_file): try: download_file(file_to_download, downloaded_file) finally: if not os.path.isfile(downloaded_file): raise Exception("Failed to download {0}".format(file_to_download)) else: self.log_message('Download successful.') # unzip the archive self.log_message('Unzipping {0}...'.format(downloaded_file)) unzip(downloaded_file, self.files_dir) self.log_message('Unzip successful.') # create output directory make_dir(self.output_dir) # read the markdown files and output html files self.log_message('Processing the OBS markdown files') files = sorted(glob(os.path.join(self.files_dir, '*'))) current_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(current_dir, 'obs-template.html')) as template_file: html_template = string.Template(template_file.read()) complete_html = '' for filename in files: if filename.endswith('.md'): # read the markdown file with codecs.open(filename, 'r', 'utf-8-sig') as md_file: md = md_file.read() html = markdown.markdown(md) complete_html += html html = html_template.safe_substitute(content=html) html_filename = os.path.splitext(os.path.basename(filename))[0] + ".html" output_file = os.path.join(self.output_dir, html_filename) write_file(output_file, html) self.log_message('Converted {0} to {1}.'.format(os.path.basename(filename), os.path.basename(html_filename))) else: try: output_file = os.path.join(self.output_dir, filename[len(self.files_dir)+1:]) if not os.path.exists(output_file): if not os.path.exists(os.path.dirname(output_file)): os.makedirs(os.path.dirname(output_file)) copyfile(filename, output_file) except Exception: pass # Do the OBS inspection inspector = OBSInspection(self.output_dir) try: inspector.run() except Exception as e: self.warning_message('Failed to run OBS inspector: {0}'.format(e.message)) for warning in inspector.warnings: self.warning_message(warning) for error in inspector.errors: self.error_message(error) complete_html = html_template.safe_substitute(content=complete_html) write_file(os.path.join(self.output_dir, 'all.html'), complete_html) self.log_message('Made one HTML of all stories in all.html.') self.log_message('Finished processing Markdown files.')
def import_obs(lang_data, git_repo, door43_url, no_pdf): global download_dir, root, api_dir lang_code = lang_data['lc'] # pre-flight checklist link_source = '/var/www/vhosts/api.unfoldingword.org/httpdocs/obs/jpg/1/en' if not os.path.isdir(link_source): print_error( 'Image source directory not found: {0}.'.format(link_source)) sys.exit(1) if git_repo[-1:] != '/': git_repo += '/' if no_pdf: tools_dir = None else: tools_dir = '/var/www/vhosts/door43.org/tools' if not os.path.isdir(tools_dir): tools_dir = os.path.expanduser('~/Projects/tools') # prompt if tools not found if not os.path.isdir(tools_dir): tools_dir = None print_notice( 'The tools directory was not found. The PDF cannot be generated.' ) resp = prompt( 'Do you want to continue without generating a PDF? [Y|n]: ') if resp != '' and resp != 'Y' and resp != 'y': sys.exit(0) if git_repo: if git_repo[-1:] == '/': git_repo = git_repo[:-1] download_dir = '/tmp/{0}'.format(git_repo.rpartition('/')[2]) make_dir(download_dir) # make sure OBS is initialized on Dokuwiki test_dir = root.format(lang_code, '') if not os.path.isdir(test_dir): print_warning( 'It seems OBS has not been initialized on Door43.org for {0}'. format(lang_code)) sys.exit(1) elif door43_url: print_error('URL not yet implemented.') return else: print_error('Source not provided.') return # get the source files from the git repository if 'github' in git_repo: # https://github.com/unfoldingWord/obs-ru # https://raw.githubusercontent.com/unfoldingWord/obs-ru/master/obs-ru.json raw_url = git_repo.replace('github.com', 'raw.githubusercontent.com') elif 'git.door43.org' in git_repo: raw_url = join_url_parts(git_repo, 'raw') else: # this is to keep IntelliJ happy, is should have been caught in sub main return # download needed files from the repository file_suffix = '-{0}.json'.format(lang_code.lower()) files_to_download = [ join_url_parts(raw_url, 'master/obs' + file_suffix), join_url_parts(raw_url, 'master/status' + file_suffix) ] for file_to_download in files_to_download: downloaded_file = os.path.join(download_dir, file_to_download.rpartition('/')[2]) try: print('Downloading {0}...'.format(file_to_download), end=' ') download_file(file_to_download, downloaded_file) finally: print('finished.') # read the files from the git repository file_suffix = '-{0}.json'.format(lang_code.lower()) obs_obj = None status_obj = None # front_matter_found = False # back_matter_found = False try: print('Examining the files...', end=' ') for root_path, dirs, files in os.walk(download_dir): if not len(files): continue for git_file in files: if git_file == 'obs' + file_suffix: obs_obj = OBS(os.path.join(root_path, git_file)) elif git_file == 'status' + file_suffix: status_obj = OBSStatus(os.path.join(root_path, git_file)) # elif 'front-matter' in git_file: # front_matter_found = True # elif 'back-matter' in git_file: # back_matter_found = True finally: print('finished.') # check data integrity if not obs_obj.verify_all(): sys.exit(1) if not status_obj: print_error( 'The file "status{0}" was not found in the git repository.'.format( file_suffix)) sys.exit(1) # create Dokuwiki pages print_ok('Begin: ', 'creating Dokuwiki pages.') for chapter in obs_obj.chapters: chapter_title = '====== {0} ======'.format(chapter['title']) chapter_ref = '//{0}//'.format(chapter['ref']) chapter_body = '' chapter_num = chapter['number'].zfill(2) for frame in chapter['frames']: chapter_body += '{{{{{0}?direct&}}}}\n\n{1}\n\n'.format( frame['img'], frame['text']) file_name = root.format(lang_code, chapter_num + '.txt') print(' Writing {0}'.format(file_name)) with codecs.open(file_name, 'w', 'utf-8-sig') as out_file: out_file.write('{0}\n\n{1}{2}\n'.format(chapter_title, chapter_body, chapter_ref)) print_ok('Finished: ', 'creating Dokuwiki pages.') # Create image symlinks on api.unfoldingword.org try: print('Creating symlink to images directory...', end=' ') link_name = '/var/www/vhosts/api.unfoldingword.org/httpdocs/obs/jpg/1/{0}'.format( lang_code.lower()) if not os.path.isfile(link_name) and not os.path.isdir( link_name) and not os.path.islink(link_name): os.symlink(link_source, link_name) finally: print('finished.') # Create PDF via ConTeXt if not no_pdf and tools_dir and os.path.isdir(tools_dir): try: print_ok('Beginning: ', 'PDF generation.') script_file = os.path.join(tools_dir, 'obs/book/pdf_export.sh') out_dir = api_dir.format(lang_code) make_dir(out_dir) process = subprocess.Popen([ script_file, '-l', lang_code, '-c', status_obj.checking_level, '-v', status_obj.version, '-o', out_dir ], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # wait for the process to terminate out, err = process.communicate() exit_code = process.returncode out = out.strip().decode('utf-8') err = err.strip().decode('utf-8') # the error message may be in stdout if exit_code != 0: if not err: err = out out = None if err: print_error(err, 2) if out: print(' ' + out) print(' PDF subprocess finished with exit code {0}'.format( exit_code)) finally: print_ok('Finished:', 'generating PDF.')
def clone(self, working_dir): if not self.url: self.url = self.get_resource_git_url(self.repo_name, self.owner) self.repo_dir = os.path.join(working_dir, self.repo_name) if not self.offline and not os.path.exists(self.repo_dir): try: self.repo = git.Repo.clone_from(self.url, self.repo_dir, depth=1) except git.GitCommandError as orig_err: owners = OWNERS for owner_idx, owner in enumerate(owners): self.url = self.get_resource_git_url(self.repo_name, owner) self.repo_dir = os.path.join(working_dir, owner, self.repo_name) try: self.repo = git.Repo.clone_from(self.url, self.repo_dir, depth=1) self.owner = owner except git.GitCommandError: if owner_idx + 1 == len(owners): raise orig_err else: continue if os.path.exists(self.repo_dir): break if not self.repo: self.repo = git.Repo(self.repo_dir) if self.update: for remote in self.repo.remotes: remote.fetch() if not self.ref: self.ref = self.latest_tag if not self.ref: self.ref = DEFAULT_REF self.repo.git.checkout(self.ref) if self.ref == DEFAULT_REF and self.update: self.repo.git.pull() if self.resource_name == 'obs' and \ not os.path.exists(os.path.join(self.repo_dir, 'manifest.yaml')) and \ os.path.exists(os.path.join(self.repo_dir, 'manifest.json')) and \ os.path.exists(os.path.join(self.repo_dir, '01', '01.txt')): new_repo_dir = self.repo_dir + '_rc' if os.path.exists(new_repo_dir): shutil.rmtree(new_repo_dir) do_preprocess(self.repo_dir, new_repo_dir) download_file( 'https://git.door43.org/api/v1/repos/unfoldingword/en_obs/raw/LICENSE.md', os.path.join(new_repo_dir, 'LICENSE.md')) download_file( 'https://git.door43.org/api/v1/repos/unfoldingword/en_obs/raw/LICENSE.md', os.path.join(new_repo_dir, 'README.md')) front_dir = os.path.join(new_repo_dir, 'content', 'front') if not os.path.exists(front_dir): os.mkdir(front_dir) download_file( 'https://git.door43.org/api/v1/repos/unfoldingword/en_obs/raw/content/front/intro.md', os.path.join(front_dir, 'intro.md')) download_file( 'https://git.door43.org/api/v1/repos/unfoldingword/en_obs/raw/content/front/title.md', os.path.join(front_dir, 'title.md')) back_dir = os.path.join(new_repo_dir, 'content', 'back') if not os.path.exists(back_dir): os.mkdir(back_dir) download_file( 'https://git.door43.org/api/v1/repos/unfoldingword/en_obs/raw/content/back/intro.md', os.path.join(new_repo_dir, 'content', 'back', 'intro.md')) self.repo_dir = new_repo_dir
def run(self): if 'git.door43.org' not in self.source_repo_url: print_warning( 'Currently only git.door43.org repositories are supported.') sys.exit(0) try: # clean up the git repo url if self.source_repo_url[-4:] == '.git': self.source_repo_url = self.source_repo_url[:-4] if self.source_repo_url[-1:] == '/': self.source_repo_url = self.source_repo_url[:-1] # download the archive file_to_download = join_url_parts(self.source_repo_url, 'archive/master.zip') repo_dir = self.source_repo_url.rpartition('/')[2] downloaded_file = os.path.join(self.temp_dir, repo_dir + '.zip') try: if not self.quiet: print('Downloading {0}...'.format(file_to_download), end=' ') if not os.path.isfile(downloaded_file): download_file(file_to_download, downloaded_file) finally: if not self.quiet: print('finished.') # unzip the archive try: if not self.quiet: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, self.temp_dir) finally: if not self.quiet: print('finished.') # get the manifest try: if not self.quiet: print('Reading the manifest...', end=' ') manifest = load_json_object( os.path.join(self.temp_dir, 'manifest.json')) finally: if not self.quiet: print('finished.') # create output directory make_dir(self.output_directory) # read the markdown files and output html files try: if not self.quiet: print('Processing the OBS markdown files') files_to_process = [] for i in range(1, 51): files_to_process.append(str(i).zfill(2) + '.md') current_dir = os.path.dirname(inspect.stack()[0][1]) with codecs.open(os.path.join(current_dir, 'template.html'), 'r', 'utf-8-sig') as html_file: html_template = html_file.read() for file_to_process in files_to_process: # read the markdown file file_name = os.path.join(self.temp_dir, repo_dir, 'content', file_to_process) with codecs.open(file_name, 'r', 'utf-8-sig') as md_file: md = md_file.read() html = markdown.markdown(md) html = TransformOBS.dir_re.sub(r'\1\n' + html + r'\n\2', html_template) write_file( os.path.join(self.output_directory, file_to_process.replace('.md', '.html')), html) except IOError as ioe: print_error('{0}: {1}'.format(ioe.strerror, ioe.filename)) self.errors.append(ioe) except Exception as e: print_error(e.message) self.errors.append(e) finally: if not self.quiet: print('finished.') except Exception as e: print_error(e.message) self.errors.append(e)
def main(resource, lang, slug, name, checking, contrib, ver, check_level, comments, source): global downloaded_file, unzipped_dir, out_template today = ''.join(str(datetime.date.today()).rsplit('-')[0:3]) downloaded_file = '/tmp/{0}'.format(resource.rpartition('/')[2]) unzipped_dir = '/tmp/{0}'.format(resource.rpartition('/')[2].strip('.zip')) out_dir = out_template.format(slug, lang) if not os.path.isfile(downloaded_file): download_file(resource, downloaded_file) unzip(downloaded_file, unzipped_dir) books_published = {} there_were_errors = False for root, dirs, files in os.walk(unzipped_dir): # only usfm files files = [f for f in files if f[-3:].lower() == 'sfm'] if not len(files): continue # there are usfm files, which book is this? test_dir = root.rpartition('/')[2] book = Book.create_book(test_dir) # type: Book if book: book_text = '' files.sort() for usfm_file in files: with codecs.open(os.path.join(root, usfm_file), 'r', 'utf-8') as in_file: book_text += in_file.read() + '\n' book.set_usfm(book_text) book.clean_usfm() # do basic checks book.verify_usfm_tags() book.verify_chapters_and_verses() if len(book.validation_errors) > 0: there_were_errors = True if there_were_errors: continue # get chunks for this book book.apply_chunks() # produces something like '01-GEN.usfm' book_file_name = '{0}-{1}.usfm'.format(str(book.number).zfill(2), book.book_id) print('Writing ' + book_file_name) write_file('{0}/{1}'.format(out_dir, book_file_name), book.usfm) meta = ['Bible: OT'] if book.number > 39: meta = ['Bible: NT'] books_published[book.book_id.lower()] = {'name': book.name, 'meta': meta, 'sort': str(book.number).zfill(2), 'desc': '' } if there_were_errors: print_warning('There are errors you need to fix before continuing.') exit() source_ver = ver if '.' in ver: source_ver = ver.split('.')[0] status = {"slug": '{0}-{1}'.format(slug.lower(), lang), "name": name, "lang": lang, "date_modified": today, "books_published": books_published, "status": {"checking_entity": checking, "checking_level": check_level, "comments": comments, "contributors": contrib, "publish_date": today, "source_text": source, "source_text_version": source_ver, "version": ver } } write_file('{0}/status.json'.format(out_dir), status) print('Publishing to the API...') with api_publish(out_dir) as api: api.run() print('Finished publishing to the API.') # update the catalog print() print('Updating the catalogs...', end=' ') update_catalog() print('finished.') print('Check {0} and do a git push'.format(out_dir))
def main(git_repo, tag, no_pdf): global download_dir # clean up the git repo url if git_repo[-4:] == '.git': git_repo = git_repo[:-4] if git_repo[-1:] == '/': git_repo = git_repo[:-1] # initialize some variables today = ''.join(str(datetime.date.today()).rsplit('-')[0:3]) # str(datetime.date.today()) download_dir = '/tmp/{0}'.format(git_repo.rpartition('/')[2]) make_dir(download_dir) downloaded_file = '{0}/{1}.zip'.format(download_dir, git_repo.rpartition('/')[2]) file_to_download = join_url_parts(git_repo, 'archive/' + tag + '.zip') manifest = None status = None # type: OBSStatus content_dir = None # download the repository try: print('Downloading {0}...'.format(file_to_download), end=' ') if not os.path.isfile(downloaded_file): download_file(file_to_download, downloaded_file) finally: print('finished.') try: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, download_dir) finally: print('finished.') # examine the repository for root, dirs, files in os.walk(download_dir): if 'manifest.json' in files: # read the manifest try: print('Reading the manifest...', end=' ') content_dir = root manifest = load_json_object(os.path.join(root, 'manifest.json')) finally: print('finished.') if 'status.json' in files: # read the meta data try: print('Reading the status...', end=' ') content_dir = root status = OBSStatus(os.path.join(root, 'status.json')) finally: print('finished.') # if we have everything, exit the loop if content_dir and manifest and status: break # check for valid repository structure if not manifest: print_error('Did not find manifest.json in {}'.format(git_repo)) sys.exit(1) if not status: print_error('Did not find status.json in {}'.format(git_repo)) sys.exit(1) print('Initializing OBS object...', end=' ') lang = manifest['target_language']['id'] obs_obj = OBS() obs_obj.date_modified = today obs_obj.direction = manifest['target_language']['direction'] obs_obj.language = lang print('finished') obs_obj.chapters = load_obs_chapters(content_dir) obs_obj.chapters.sort(key=lambda c: c['number']) if not obs_obj.verify_all(): print_error('Quality check did not pass.') sys.exit(1) print('Loading languages...', end=' ') lang_dict = OBS.load_lang_strings() print('finished.') print('Loading the catalog...', end=' ') export_dir = '/var/www/vhosts/door43.org/httpdocs/exports' # uw_cat_path = os.path.join(unfoldingWord_dir, 'obs-catalog.json') # uw_catalog = load_json_object(uw_cat_path, []) # uw_cat_langs = [x['language'] for x in uw_catalog] cat_path = os.path.join(export_dir, 'obs-catalog.json') catalog = load_json_object(cat_path, []) print('finished') print('Getting already published languages...', end=' ') json_lang_file_path = os.path.join(export_dir, lang, 'obs', 'obs-{0}.json'.format(lang)) # prev_json_lang = load_json_object(json_lang_file_path, {}) if lang not in lang_dict: print("Configuration for language {0} missing.".format(lang)) sys.exit(1) print('finished.') updated = update_language_catalog(lang, obs_obj.direction, status, today, lang_dict, catalog) print('Writing the OBS file to the exports directory...', end=' ') cur_json = json.dumps(obs_obj, sort_keys=True, cls=OBSEncoder) if updated: ([x for x in catalog if x['language'] == lang][0]['date_modified']) = today write_file(json_lang_file_path.replace('.txt', '.json'), cur_json) print('finished.') export_to_api(lang, status, today, cur_json) cat_json = json.dumps(catalog, sort_keys=True, cls=OBSEncoder) write_file(cat_path, cat_json) # update the catalog print_ok('STARTING: ', 'updating the catalogs.') update_catalog() print_ok('FINISHED: ', 'updating the catalogs.') if no_pdf: return create_pdf(lang, status.checking_level, status.version)
def handle(event, context): data = event['data'] commit_id = data['after'] commit = None for commit in data['commits']: if commit['id'] == commit_id: break commit_url = commit['url'] commit_message = commit['message'] if 'https://git.door43.org/' not in commit_url and 'http://test.door43.org:3000/' not in commit_url: raise Exception('Currently only git.door43.org repositories are supported.') pre_convert_bucket = event['pre_convert_bucket'] cdn_bucket = event['cdn_bucket'] gogs_user_token = event['gogs_user_token'] api_url = event['api_url'] repo_name = data['repository']['name'] repo_owner = data['repository']['owner']['username'] compare_url = data['compare_url'] if 'pusher' in data: pusher = data['pusher'] else: pusher = {'username': commit['author']['username']} pusher_username = pusher['username'] # The following sections of code will: # 1) download and unzip repo files # 2) massage the repo files by creating a new directory and file structure # 3) zip up the massages filed # 4) upload massaged files to S3 in zip file # 1) Download and unzip the repo files repo_zip_url = commit_url.replace('commit', 'archive') + '.zip' repo_zip_file = os.path.join(tempfile.gettempdir(), repo_zip_url.rpartition('/')[2]) repo_dir = tempfile.mkdtemp(prefix='repo_') try: print('Downloading {0}...'.format(repo_zip_url), end=' ') if not os.path.isfile(repo_zip_file): download_file(repo_zip_url, repo_zip_file) finally: print('finished.') # Unzip the archive try: print('Unzipping {0}...'.format(repo_zip_file), end=' ') unzip(repo_zip_file, repo_dir) finally: print('finished.') # 2) Massage the content to just be a directory of MD files in alphabetical order as they should be compiled together in the converter content_dir = os.path.join(repo_dir, repo_name, 'content') md_files = glob(os.path.join(content_dir, '*.md')) massaged_files_dir = tempfile.mktemp(prefix='files_') make_dir(massaged_files_dir) print('Massaging content from {0} to {1}...'.format(content_dir, massaged_files_dir), end=' ') for md_file in md_files: copyfile(md_file, os.path.join(massaged_files_dir, os.path.basename(md_file))) # want front matter to be before 01.md and back matter to be after 50.md copyfile(os.path.join(content_dir, '_front', 'front-matter.md'), os.path.join(massaged_files_dir, '00_front-matter.md')) copyfile(os.path.join(content_dir, '_back', 'back-matter.md'), os.path.join(massaged_files_dir, '51_back-matter.md')) print('finished.') # 3) Zip up the massaged files zip_filename = context.aws_request_id+'.zip' # context.aws_request_id is a unique ID for this lambda call, so using it to not conflict with other requests zip_filepath = os.path.join(tempfile.gettempdir(), zip_filename) md_files = glob(os.path.join(massaged_files_dir, '*.md')) print('Zipping files from {0} to {1}...'.format(massaged_files_dir, zip_filepath), end=' ') for md_file in md_files: add_file_to_zip(zip_filepath, md_file, os.path.basename(md_file)) print('finished.') # 4) Upload zipped file to the S3 bucket (you may want to do some try/catch and give an error if fails back to Gogs) print('Uploading {0} to {1}...'.format(zip_filepath, pre_convert_bucket), end=' ') s3_client = boto3.client('s3') s3_client.upload_file(zip_filepath, pre_convert_bucket, zip_filename) print('finished.') # Send job request to tx-manager source_url = 'https://s3-us-west-2.amazonaws.com/'+pre_convert_bucket+'/'+zip_filename # we use us-west-2 for our s3 buckets tx_manager_job_url = api_url+'/tx/job' payload = { "identifier": "{0}:::{1}:::{2}".format(repo_owner, repo_name, commit_id), "user_token": gogs_user_token, "username": pusher_username, "resource_type": "obs", "input_format": "md", "output_format": "html", "source": source_url, "callback": api_url+'/sampleclient/callback' } headers = {"content-type": "application/json"} print('Making request to tx-Manager URL {0} with payload:'.format(tx_manager_job_url)) print(payload) print('...', end=' ') response = requests.post(tx_manager_job_url, json=payload, headers=headers) print('finished.') # for testing print('tx-manager response:') print(response) json_data = json.loads(response.text) print("json:") print(json_data) build_log_json = { 'job_id': json_data['job']['job_id'], 'repo_name': repo_name, 'repo_owner': repo_owner, 'commit_id': commit_id, 'committed_by': pusher_username, 'commit_url': commit_url, 'compare_url': compare_url, 'commit_message': commit_message, 'request_timestamp': datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"), 'eta_timestamp': json_data['job']['eta'], 'success': None, 'status': 'started', 'message': 'Conversion in progress...' } if 'errorMessage' in json_data: build_log_json['status'] = 'failed' build_log_json['message'] = json_data['errorMessage'] # Make a build_log.json file with this repo and commit data for later processing, upload to S3 s3_project_key = 'u/{0}/{1}/{2}'.format(repo_owner, repo_name, commit_id[:10]) s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket(cdn_bucket) for obj in bucket.objects.filter(Prefix=s3_project_key): s3_resource.Object(bucket.name, obj.key).delete() build_log_file = os.path.join(tempfile.gettempdir(), 'build_log_request.json') write_file(build_log_file, build_log_json) bucket.upload_file(build_log_file, s3_project_key+'/build_log.json', ExtraArgs={'ContentType': 'application/json'}) print('Uploaded the following content from {0} to {1}/build_log.json'.format(build_log_file, s3_project_key)) print(build_log_json) # If there was an error, in order to trigger a 400 error in the API Gateway, we need to raise an # exception with the returned 'errorMessage' because the API Gateway needs to see 'Bad Request:' in the string if 'errorMessage' in json_data: raise Exception(json_data['errorMessage']) return build_log_json
def main(resource, lang, slug, name, checking, contrib, ver, check_level, comments, source): global downloaded_file, unzipped_dir, out_template today = ''.join(str(datetime.date.today()).rsplit('-')[0:3]) downloaded_file = '/tmp/{0}'.format(resource.rpartition('/')[2]) unzipped_dir = '/tmp/{0}'.format(resource.rpartition('/')[2].strip('.zip')) out_dir = out_template.format(slug, lang) if not os.path.isfile(downloaded_file): download_file(resource, downloaded_file) unzip(downloaded_file, unzipped_dir) books_published = {} there_were_errors = False for root, dirs, files in os.walk(unzipped_dir): # only usfm files files = [f for f in files if f[-3:].lower() == 'sfm'] if not len(files): continue # there are usfm files, which book is this? test_dir = root.rpartition('/')[2] book = Book.create_book(test_dir) # type: Book if book: book_text = '' files.sort() for usfm_file in files: with codecs.open(os.path.join(root, usfm_file), 'r', 'utf-8') as in_file: book_text += in_file.read() + '\n' book.set_usfm(book_text) book.clean_usfm() # do basic checks book.verify_usfm_tags() book.verify_chapters_and_verses() if len(book.validation_errors) > 0: there_were_errors = True if there_were_errors: continue # get chunks for this book book.apply_chunks() # produces something like '01-GEN.usfm' book_file_name = '{0}-{1}.usfm'.format( str(book.number).zfill(2), book.book_id) print('Writing ' + book_file_name) write_file('{0}/{1}'.format(out_dir, book_file_name), book.usfm) meta = ['Bible: OT'] if book.number > 39: meta = ['Bible: NT'] books_published[book.book_id.lower()] = { 'name': book.name, 'meta': meta, 'sort': str(book.number).zfill(2), 'desc': '' } if there_were_errors: print_warning('There are errors you need to fix before continuing.') exit() source_ver = ver if '.' in ver: source_ver = ver.split('.')[0] status = { "slug": '{0}-{1}'.format(slug.lower(), lang), "name": name, "lang": lang, "date_modified": today, "books_published": books_published, "status": { "checking_entity": checking, "checking_level": check_level, "comments": comments, "contributors": contrib, "publish_date": today, "source_text": source, "source_text_version": source_ver, "version": ver } } write_file('{0}/status.json'.format(out_dir), status) print('Publishing to the API...') with api_publish(out_dir) as api: api.run() print('Finished publishing to the API.') # update the catalog print() print('Updating the catalogs...', end=' ') update_catalog() print('finished.') print('Check {0} and do a git push'.format(out_dir))
def do_post_processing(self) -> Tuple[Optional[str], Dict[str,Any]]: AppSettings.logger.debug(f"ClientConverterCallback.do_post_processing()…") self.job.ended_at = datetime.utcnow() self.job.success = self.success for message in self.log: self.job.log_message(message) for message in self.warnings: self.job.warnings_message(message) for message in self.errors: self.job.error_message(message) if self.errors: self.job.log_message(f"{self.job.convert_module} function returned with errors.") elif self.warnings: self.job.log_message(f"{self.job.convert_module} function returned with warnings.") else: self.job.log_message(f"{self.job.convert_module} function returned successfully.") if not self.success or self.job.errors: self.job.success = False self.job.status = 'failed' message = "Conversion failed" AppSettings.logger.debug(f"Conversion failed, success: {self.success}, errors: {self.job.errors}") elif self.job.warnings: self.job.success = True self.job.status = 'warnings' message = "Conversion successful with warnings." else: self.job.success = True self.job.status = 'success' message = "Conversion successful." self.job.message = message self.job.log_message(message) self.job.log_message(f"Finished job {self.job.job_id} at {self.job.ended_at.strftime('%Y-%m-%dT%H:%M:%SZ')}") s3_commit_key = f'u/{self.job.repo_owner_username}/{self.job.repo_name}/{self.job.commit_id}' # AppSettings.logger.debug(f"Callback for commit = '{s3_commit_key}'") upload_key = s3_commit_key # Download the ZIP file of the converted files converted_zip_url = self.job.output converted_zip_file = os.path.join(self.temp_dir, converted_zip_url.rpartition('/')[2]) remove_file(converted_zip_file) # make sure old file not present download_success = True AppSettings.logger.debug(f"Downloading converted zip file from {converted_zip_url} …") try: download_file(converted_zip_url, converted_zip_file) except: download_success = False # if multiple project we note fail and move on # if not multiple_project: # if prefix and debug_mode_flag: # AppSettings.logger.debug(f"Temp folder '{self.temp_dir}' has been left on disk for debugging!") # else: # remove_tree(self.temp_dir) # cleanup if self.job.errors is None: self.job.errors = [] message = f"Missing converted file: {converted_zip_url}" AppSettings.logger.debug(message) if not self.job.errors or not self.job.errors[0].startswith("No converter "): # Missing file error is irrelevant if no conversion was attempted self.job.errors.append(message) finally: AppSettings.logger.debug(f"Download finished, success={download_success}.") # self.job.update() if download_success: # Unzip the archive unzip_dirpath = self.unzip_converted_files(converted_zip_file) # Upload all files to the cdn_bucket with the key of <user>/<repo_name>/<commit> of the repo # This is required for the print function to work self.upload_converted_files_to_CDN(upload_key, unzip_dirpath) else: unzip_dirpath = None # So we have something to return (fail later -- is that an advantage?) # TODO: Do we really need this now? # Now download the existing build_log.json file, update it and upload it back to S3 as convert_log # NOTE: Do we need this -- disabled 25Feb2019 # build_log_json = self.update_convert_log(s3_commit_key) # self.cdn_upload_contents({}, s3_commit_key + '/finished') # flag finished converter_build_log = self.make_our_build_log() # print("Got ConPP converter_build_log", converter_build_log) # NOTE: Disabled 4Mar2019 coz moved to callback.py # results = ClientLinterCallback.deploy_if_conversion_finished(s3_commit_key, self.identifier) # if results: # self.all_parts_completed = True # build_log_json = results # if prefix and debug_mode_flag: # AppSettings.logger.debug(f"Temp folder '{self.temp_dir}' has been left on disk for debugging!") # else: # remove_tree(self.temp_dir) # cleanup return unzip_dirpath, converter_build_log
def main(git_repo, tag): global download_dir # clean up the git repo url if git_repo[-4:] == '.git': git_repo = git_repo[:-4] if git_repo[-1:] == '/': git_repo = git_repo[:-1] # initialize some variables download_dir = '/tmp/{0}'.format(git_repo.rpartition('/')[2]) make_dir(download_dir) downloaded_file = '{0}/{1}.zip'.format(download_dir, git_repo.rpartition('/')[2]) file_to_download = join_url_parts(git_repo, 'archive/' + tag + '.zip') metadata_obj = None content_dir = None toc_obj = None # download the repository try: print('Downloading {0}...'.format(file_to_download), end=' ') if not os.path.isfile(downloaded_file): download_file(file_to_download, downloaded_file) finally: print('finished.') try: print('Unzipping...'.format(downloaded_file), end=' ') unzip(downloaded_file, download_dir) finally: print('finished.') # examine the repository for root, dirs, files in os.walk(download_dir): if 'meta.yaml' in files: # read the metadata try: print('Reading the metadata...', end=' ') metadata_obj = TAMetaData(os.path.join(root, 'meta.yaml')) finally: print('finished.') if 'toc.yaml' in files: # read the table of contents try: print('Reading the toc...', end=' ') toc_obj = TATableOfContents(os.path.join(root, 'toc.yaml')) finally: print('finished.') if 'content' in dirs: content_dir = os.path.join(root, 'content') # if we have everything, exit the loop if content_dir and metadata_obj and toc_obj: break # check for valid repository structure if not metadata_obj: print_error('Did not find meta.yaml in {}'.format(git_repo)) sys.exit(1) if not content_dir: print_error( 'Did not find the content directory in {}'.format(git_repo)) sys.exit(1) if not toc_obj: print_error('Did not find toc.yaml in {}'.format(git_repo)) sys.exit(1) # check for missing pages check_missing_pages(toc_obj, content_dir) # generate the pages print('Generating the manual...', end=' ') manual = TAManual(metadata_obj, toc_obj) manual.load_pages(content_dir) print('finished.') file_name = os.path.join( get_output_dir(), '{0}_{1}.json'.format(manual.meta.manual, manual.meta.volume)) print('saving to {0} ...'.format(file_name), end=' ') content = json.dumps(manual, sort_keys=True, indent=2, cls=TAEncoder) write_file(file_name, content) print('finished.')
def handle(event, context): # Getting the bucket to where we will unzip the converted files for door43.org. It is different from # production and testing, thus it is an environment variable the API Gateway gives us if 'cdn_bucket' not in event: raise Exception('"cdn_bucket" was not in payload') cdn_bucket = event['cdn_bucket'] # Getting data from payload which is the JSON that was sent from tx-manager if 'data' not in event: raise Exception('"data" not in payload') data = event['data'] print("data:") print(data) identifier = data['identifier'] parts = identifier.split(':::') if len(parts) < 3: return repo_owner = parts[0] repo_name = parts[1] commit_id = parts[2] s3_project_key = 'u/{0}/{1}/{2}'.format(repo_owner, repo_name, commit_id[:10]) s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket(cdn_bucket) # Unzip ZIP file into the cdn_bucket converted_zip_url = data['output'] converted_zip_file = os.path.join(tempfile.gettempdir(), converted_zip_url.rpartition('/')[2]) try: print( 'Downloading converted file from {0}...'.format(converted_zip_url)) if not os.path.isfile(converted_zip_file): download_file(converted_zip_url, converted_zip_file) finally: print('finished.') # Unzip the archive unzip_dir = tempfile.mkdtemp(prefix='unzip_') try: print('Unzipping {0}...'.format(converted_zip_file)) unzip(converted_zip_file, unzip_dir) finally: print('finished.') # Upload all files to the cdn_bucket with the key of <user>/<repo_name>/<commit> of the repo mime = MimeTypes() for root, dirs, files in os.walk(unzip_dir): for f in sorted(files): path = os.path.join(root, f) key = s3_project_key + path.replace(unzip_dir, '') mime_type = mime.guess_type(path)[0] if not mime_type: mime_type = "text/html" print('Uploading {0} to {1}, mime_type: {2}'.format( f, key, mime_type)) bucket.upload_file(path, key, ExtraArgs={'ContentType': mime_type}) # Now download the existing build_log.json file, update it and upload it back to S3 s3_file = s3_resource.Object(cdn_bucket, s3_project_key + '/build_log.json') build_log_json = json.loads(s3_file.get()['Body'].read()) build_log_json['start_timestamp'] = data['start_timestamp'] build_log_json['end_timestamp'] = datetime.utcnow().strftime( "%Y-%m-%dT%H:%M:%SZ") build_log_json['success'] = data['success'] build_log_json['status'] = data['status'] build_log_json['message'] = data['message'] if 'log' in data and data['log']: build_log_json['log'] = data['log'] else: build_log_json['log'] = [] if 'warnings' in data and data['warnings']: build_log_json['warnings'] = data['warnings'] else: build_log_json['warnings'] = [] if 'errors' in data and data['errors']: build_log_json['errors'] = data['errors'] else: build_log_json['errors'] = [] build_log_file = os.path.join(tempfile.gettempdir(), 'build_log_finished.json') write_file(build_log_file, build_log_json) bucket.upload_file(build_log_file, s3_project_key + '/build_log.json', ExtraArgs={'ContentType': 'application/json'}) print( 'Uploaded the following content from {0} to {1}/build_log.json'.format( build_log_file, s3_project_key)) print(build_log_json)