").Replace("\n", "").Replace("\r", "").Trim();
string[] values = recordinfotext.Split("
", StringSplitOptions.RemoveEmptyEntries);
foreach(string value in values)
{
if (value.Trim().Length == 0)
continue;
if (recordinfolabel == "Title")
{
title = value.Trim();
tag = await TagHandler.PrepareAttribute(context, "Title", title, 1);
meta.Add(tag);
}
else
if (recordinfolabel == "Author")
{
author = value.Trim();
tag = await TagHandler.PrepareAttribute(context, "Contributor Names", author, 1);
meta.Add(tag);
}
else
{
tag = await TagHandler.PrepareAttribute(context, recordinfolabel, value.Trim(), tagOrder++);
meta.Add(tag);
}
}
nIdxStart = html.IndexOf("recordinfolabel", nIdxEnd);
}
tag = await TagHandler.PrepareAttribute(context, "Type", "Book", 1);
meta.Add(tag);
tag = await TagHandler.PrepareAttribute(context, "Type", "Manuscript", 1);
meta.Add(tag);
tag = await TagHandler.PrepareAttribute(context, "Source", "Penn Libraries", 1);
string viewerUrl = $"http://dla.library.upenn.edu/dla/medren/detail.html?id={resourceNumber}";
tag.ValueSupplement = viewerUrl;
meta.Add(tag);
book.Name = book.NameInEnglish = book.Description = book.DescriptionInEnglish = title;
book.Tags = meta.ToArray();
List
pages = new List();
int order = 0;
while (true)
{
order++;
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.ProgressPercent = order;
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
string imageUrl = firstImageUrl;
RArtifactItemRecord page = new RArtifactItemRecord()
{
Name = $"تصویر {order}",
NameInEnglish = $"Image {order}",
Description = "",
DescriptionInEnglish = "",
Order = order,
FriendlyUrl = $"p{$"{order}".PadLeft(4, '0')}",
LastModified = DateTime.Now
};
tag = await TagHandler.PrepareAttribute(context, "Source", "Penn Libraries", 1);
tag.ValueSupplement = viewerUrl;
page.Tags = new RTagValue[] { tag };
if (!string.IsNullOrEmpty(imageUrl))
{
bool recovered = false;
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
)
&&
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
)
&&
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
RServiceResult picture = await _pictureFileService.RecoverFromeFiles(page.Name, page.Description, 1,
imageUrl,
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg"),
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg"),
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg"),
$"{order}".PadLeft(4, '0') + ".jpg", friendlyUrl);
if (picture.Result != null)
{
recovered = true;
page.Images = new RPictureFile[] { picture.Result };
page.CoverImageIndex = 0;
if (book.CoverItemIndex == (order - 1))
{
book.CoverImage = RPictureFile.Duplicate(picture.Result);
}
pages.Add(page);
}
}
if (!recovered)
{
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
if (order > 1)
{
string pageUrl = $"http://dla.library.upenn.edu/dla/medren/pageturn.html?id={resourceNumber}&doubleside=0&rotation=0&size=0¤tpage={order}";
var pageResult = await client.GetAsync(pageUrl);
if (pageResult.StatusCode == HttpStatusCode.NotFound)
{
break;//finished
}
string pageHtml = await pageResult.Content.ReadAsStringAsync();
nIdxStart = pageHtml.IndexOf("https://repo.library.upenn.edu/djatoka/resolver?");
if (nIdxStart == -1)
{
if (order > 1)
break; //finished
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = $"https://repo.library.upenn.edu/djatoka/resolver? not found on page {order}";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
imageUrl = pageHtml.Substring(nIdxStart, pageHtml.IndexOf('"', nIdxStart) - nIdxStart).Replace("&", "&");
}
var imageResult = await client.GetAsync(imageUrl);
if(imageResult.StatusCode == HttpStatusCode.NotFound)
{
break;//finished
}
int _ImportRetryCount = 200;
int _ImportRetryInitialSleep = 500;
int retryCount = 0;
while (retryCount < _ImportRetryCount && !imageResult.IsSuccessStatusCode && imageResult.StatusCode == HttpStatusCode.ServiceUnavailable)
{
imageResult.Dispose();
Thread.Sleep(_ImportRetryInitialSleep * (retryCount + 1));
imageResult = await client.GetAsync(imageUrl);
retryCount++;
}
if (imageResult.IsSuccessStatusCode)
{
using (Stream imageStream = await imageResult.Content.ReadAsStreamAsync())
{
RServiceResult picture = await _pictureFileService.Add(page.Name, page.Description, 1, null, imageUrl, imageStream, $"{order}".PadLeft(4, '0') + ".jpg", friendlyUrl);
if (picture.Result == null)
{
throw new Exception($"_pictureFileService.Add : {picture.ExceptionString}");
}
page.Images = new RPictureFile[] { picture.Result };
page.CoverImageIndex = 0;
if (book.CoverItemIndex == (order - 1))
{
book.CoverImage = RPictureFile.Duplicate(picture.Result);
}
pages.Add(page);
}
}
else
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = $"Http result is not ok ({imageResult.StatusCode}) for page {order}, url {imageUrl}";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
imageResult.Dispose();
return;
}
imageResult.Dispose();
GC.Collect();
}
}
}
book.Items = pages.ToArray();
book.ItemCount = pages.Count;
if (pages.Count == 0)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "Pages.Count == 0";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
await context.Artifacts.AddAsync(book);
await context.SaveChangesAsync();
job.ProgressPercent = 100;
job.Status = ImportJobStatus.Succeeded;
job.ArtifactId = book.Id;
job.EndTime = DateTime.Now;
context.Update(job);
await context.SaveChangesAsync();
}
}
else
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = $"Http result is not ok ({result.StatusCode}) for {url}";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
}
}
}
catch (Exception exp)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = exp.ToString();
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
}
}
);
return new RServiceResult(true);
}
catch (Exception exp)
{
return new RServiceResult(false, exp.ToString());
}
}
///
/// from http://cudl.lib.cam.ac.uk
///
/// MS-RAS-00258
///
///
private async Task> StartImportingFromCambridge(string resourceNumber, string friendlyUrl)
{
string url = $"http://cudl.lib.cam.ac.uk/view/{resourceNumber}.json";
if (
(
await _context.ImportJobs
.Where(j => j.JobType == JobType.Cambridge && j.ResourceNumber == resourceNumber && !(j.Status == ImportJobStatus.Failed || j.Status == ImportJobStatus.Aborted))
.SingleOrDefaultAsync()
)
!=
null
)
{
return new RServiceResult(false, $"Job is already scheduled or running for importing {url}");
}
if (string.IsNullOrEmpty(friendlyUrl))
{
friendlyUrl = resourceNumber;
}
if (
(await _context.Artifacts.Where(a => a.FriendlyUrl == friendlyUrl).SingleOrDefaultAsync())
!=
null
)
{
return new RServiceResult(false, $"duplicated artifact friendly url '{friendlyUrl}'");
}
ImportJob job = new ImportJob()
{
JobType = JobType.Cambridge,
ResourceNumber = resourceNumber,
FriendlyUrl = friendlyUrl,
SrcUrl = url,
QueueTime = DateTime.Now,
ProgressPercent = 0,
Status = ImportJobStatus.NotStarted
};
await _context.ImportJobs.AddAsync
(
job
);
await _context.SaveChangesAsync();
try
{
_backgroundTaskQueue.QueueBackgroundWorkItem
(
async token =>
{
try
{
using (var client = new HttpClient())
{
using (var result = await client.GetAsync(url))
{
if (result.IsSuccessStatusCode)
{
using (RMuseumDbContext context = new RMuseumDbContext(Configuration))
{
if (
(await context.Artifacts.Where(a => a.FriendlyUrl == job.FriendlyUrl).SingleOrDefaultAsync())
!=
null
)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "aborted because of duplicated friendly url";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
RArtifactMasterRecord book = new RArtifactMasterRecord($"extracted from {url}", $"extracted from {url}")
{
Status = PublishStatus.Draft,
DateTime = DateTime.Now,
LastModified = DateTime.Now,
CoverItemIndex = 0,
FriendlyUrl = friendlyUrl
};
List meta = new List();
RTagValue tag;
string json = await result.Content.ReadAsStringAsync();
var parsed = JObject.Parse(json);
book.Name = book.NameInEnglish =
parsed.SelectToken("logicalStructures[*].label").Value();
book.Description = book.DescriptionInEnglish =
Regex.Replace(
parsed.SelectToken("descriptiveMetadata[*].abstract.displayForm").Value(),
"<.*?>", string.Empty);
int tagOrder = 1;
foreach (JToken descriptiveMetadata in parsed.SelectTokens("$.descriptiveMetadata[*]").Children())
{
foreach(JToken child in descriptiveMetadata.Children())
{
if (child.SelectToken("label") != null && child.SelectToken("display") != null)
{
if (child.SelectToken("display").Value() == "True")
{
string metaName = child.SelectToken("label").Value();
string metaValue = "";
if (child.SelectToken("displayForm") != null)
{
metaValue = Regex.Replace(
child.SelectToken("displayForm").Value(),
"<.*?>", string.Empty);
tag = await TagHandler.PrepareAttribute(context, metaName, metaValue, tagOrder++);
meta.Add(tag);
}
else
if (child.SelectToken("value") != null)
{
foreach (JToken value in child.SelectTokens("value").Children())
{
if (value.SelectToken("displayForm") != null)
{
metaValue = Regex.Replace(
value.SelectToken("displayForm").Value(),
"<.*?>", string.Empty);
tag = await TagHandler.PrepareAttribute(context, metaName, metaValue, tagOrder++);
meta.Add(tag);
}
}
}
}
}
}
}
string imageReproPageURL = "https://image01.cudl.lib.cam.ac.uk";
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.StartTime = DateTime.Now;
job.Status = ImportJobStatus.Running;
job.SrcContent = json;
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
tag = await TagHandler.PrepareAttribute(context, "Type", "Book", 1);
meta.Add(tag);
tag = await TagHandler.PrepareAttribute(context, "Type", "Manuscript", 1);
meta.Add(tag);
tag = await TagHandler.PrepareAttribute(context, "Source", "University of Cambridge Digital Library", 1);
string viewerUrl = $"http://cudl.lib.cam.ac.uk/view/{resourceNumber}";
tag.ValueSupplement = viewerUrl;
meta.Add(tag);
book.Tags = meta.ToArray();
List pages = new List();
int order = 0;
foreach (JToken pageToken in parsed.SelectTokens("$.pages").Children())
{
order++;
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.ProgressPercent = order;
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
string imageUrl = imageReproPageURL + pageToken.SelectToken("downloadImageURL").Value();
RArtifactItemRecord page = new RArtifactItemRecord()
{
Name = $"تصویر {order}",
NameInEnglish = $"Image {order}",
Description = "",
DescriptionInEnglish = "",
Order = order,
FriendlyUrl = $"p{$"{order}".PadLeft(4, '0')}",
LastModified = DateTime.Now
};
List pageMata = new List();
tag = await TagHandler.PrepareAttribute(context, "Source", "University of Cambridge Digital Library", 1);
tag.ValueSupplement = $"{viewerUrl}/{order}";
pageMata.Add(tag);
if(pageToken.SelectToken("label") != null)
{
tag = await TagHandler.PrepareAttribute(context, "Label", pageToken.SelectToken("label").Value(), 1);
pageMata.Add(tag);
}
page.Tags = pageMata.ToArray();
if (!string.IsNullOrEmpty(imageUrl))
{
bool recovered = false;
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
)
&&
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
)
&&
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
RServiceResult picture = await _pictureFileService.RecoverFromeFiles(page.Name, page.Description, 1,
imageUrl,
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg"),
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg"),
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg"),
$"{order}".PadLeft(4, '0') + ".jpg", friendlyUrl);
if (picture.Result != null)
{
recovered = true;
page.Images = new RPictureFile[] { picture.Result };
page.CoverImageIndex = 0;
if (book.CoverItemIndex == (order - 1))
{
book.CoverImage = RPictureFile.Duplicate(picture.Result);
}
pages.Add(page);
}
}
if (!recovered)
{
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
var imageResult = await client.GetAsync(imageUrl);
if (imageResult.StatusCode == HttpStatusCode.NotFound)
{
break;//finished
}
int _ImportRetryCount = 200;
int _ImportRetryInitialSleep = 500;
int retryCount = 0;
while (retryCount < _ImportRetryCount && !imageResult.IsSuccessStatusCode && imageResult.StatusCode == HttpStatusCode.ServiceUnavailable)
{
imageResult.Dispose();
Thread.Sleep(_ImportRetryInitialSleep * (retryCount + 1));
imageResult = await client.GetAsync(imageUrl);
retryCount++;
}
if (imageResult.IsSuccessStatusCode)
{
using (Stream imageStream = await imageResult.Content.ReadAsStreamAsync())
{
RServiceResult picture = await _pictureFileService.Add(page.Name, page.Description, 1, null, imageUrl, imageStream, $"{order}".PadLeft(4, '0') + ".jpg", friendlyUrl);
if (picture.Result == null)
{
throw new Exception($"_pictureFileService.Add : {picture.ExceptionString}");
}
page.Images = new RPictureFile[] { picture.Result };
page.CoverImageIndex = 0;
if (book.CoverItemIndex == (order - 1))
{
book.CoverImage = RPictureFile.Duplicate(picture.Result);
}
pages.Add(page);
}
}
else
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = $"Http result is not ok ({imageResult.StatusCode}) for page {order}, url {imageUrl}";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
imageResult.Dispose();
return;
}
imageResult.Dispose();
GC.Collect();
}
}
}
book.Items = pages.ToArray();
book.ItemCount = pages.Count;
if (pages.Count == 0)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "Pages.Count == 0";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
await context.Artifacts.AddAsync(book);
await context.SaveChangesAsync();
job.ProgressPercent = 100;
job.Status = ImportJobStatus.Succeeded;
job.ArtifactId = book.Id;
job.EndTime = DateTime.Now;
context.Update(job);
await context.SaveChangesAsync();
}
}
else
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = $"Http result is not ok ({result.StatusCode}) for {url}";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
}
}
}
catch (Exception exp)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = exp.ToString();
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
}
}
);
return new RServiceResult(true);
}
catch (Exception exp)
{
return new RServiceResult(false, exp.ToString());
}
}
///
/// from http://www.bl.uk
///
/// grenville_xli_f001r
///
///
private async Task> StartImportingFromBritishLibrary(string resourceNumber, string friendlyUrl)
{
string url = $"http://www.bl.uk/manuscripts/Viewer.aspx?ref={resourceNumber}";
if (
(
await _context.ImportJobs
.Where(j => j.JobType == JobType.BritishLibrary && j.ResourceNumber == resourceNumber && !(j.Status == ImportJobStatus.Failed || j.Status == ImportJobStatus.Aborted))
.SingleOrDefaultAsync()
)
!=
null
)
{
return new RServiceResult(false, $"Job is already scheduled or running for importing {url}");
}
if (string.IsNullOrEmpty(friendlyUrl))
{
friendlyUrl = resourceNumber;
}
if (
(await _context.Artifacts.Where(a => a.FriendlyUrl == friendlyUrl).SingleOrDefaultAsync())
!=
null
)
{
return new RServiceResult(false, $"duplicated artifact friendly url '{friendlyUrl}'");
}
ImportJob job = new ImportJob()
{
JobType = JobType.BritishLibrary,
ResourceNumber = resourceNumber,
FriendlyUrl = friendlyUrl,
SrcUrl = url,
QueueTime = DateTime.Now,
ProgressPercent = 0,
Status = ImportJobStatus.NotStarted
};
await _context.ImportJobs.AddAsync
(
job
);
await _context.SaveChangesAsync();
try
{
_backgroundTaskQueue.QueueBackgroundWorkItem
(
async token =>
{
try
{
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromMinutes(5);
using (var result = await client.GetAsync(url))
{
if (result.IsSuccessStatusCode)
{
using (RMuseumDbContext context = new RMuseumDbContext(Configuration))
{
if (
(await context.Artifacts.Where(a => a.FriendlyUrl == job.FriendlyUrl).SingleOrDefaultAsync())
!=
null
)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "aborted because of duplicated friendly url";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
RArtifactMasterRecord book = new RArtifactMasterRecord($"extracted from {url}", $"extracted from {url}")
{
Status = PublishStatus.Draft,
DateTime = DateTime.Now,
LastModified = DateTime.Now,
CoverItemIndex = 0,
FriendlyUrl = friendlyUrl
};
List meta = new List();
RTagValue tag;
string html = await result.Content.ReadAsStringAsync();
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.StartTime = DateTime.Now;
job.Status = ImportJobStatus.Running;
job.SrcContent = html;
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
int nIdxStart = html.IndexOf("PageList");
if (nIdxStart == -1)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "PageList not found";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
nIdxStart = html.IndexOf("value=\"", nIdxStart);
if (nIdxStart == -1)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "value after PageList not found";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
nIdxStart += "value=\"".Length;
string strPageList = html.Substring(nIdxStart, html.IndexOf('"', nIdxStart) - nIdxStart);
nIdxStart = html.IndexOf("TextList");
if (nIdxStart == -1)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "TextList not found";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
nIdxStart = html.IndexOf("value=\"", nIdxStart);
if (nIdxStart == -1)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "value after TextList not found";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
nIdxStart += "value=\"".Length;
string strTextList = html.Substring(nIdxStart, html.IndexOf('"', nIdxStart) - nIdxStart);
nIdxStart = html.IndexOf("TitleList");
if (nIdxStart == -1)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "TitleList not found";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
nIdxStart = html.IndexOf("value=\"", nIdxStart);
if (nIdxStart == -1)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "value after TitleList not found";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
nIdxStart += "value=\"".Length;
string strTitleList = html.Substring(nIdxStart, html.IndexOf('"', nIdxStart) - nIdxStart);
string[] PageUrls = strPageList.Split("||", StringSplitOptions.None);
string[] PageTexts = strTextList.Split("||", StringSplitOptions.None);
string[] PageTitles = strTitleList.Split("||", StringSplitOptions.None);
if(PageUrls.Length != PageTexts.Length || PageTexts.Length != PageTitles.Length)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "PageUrls.Length != PageTexts.Length || PageTexts.Length != PageTitles.Length";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
tag = await TagHandler.PrepareAttribute(context, "Title", "Untitled", 1);
meta.Add(tag);
tag = await TagHandler.PrepareAttribute(context, "Contributor Names", "Unknown", 1);
meta.Add(tag);
tag = await TagHandler.PrepareAttribute(context, "Type", "Book", 1);
meta.Add(tag);
tag = await TagHandler.PrepareAttribute(context, "Type", "Manuscript", 1);
meta.Add(tag);
book.Tags = meta.ToArray();
tag = await TagHandler.PrepareAttribute(context, "Source", "British Library", 1);
string viewerUrl = $"http://www.bl.uk/manuscripts/FullDisplay.aspx?ref={resourceNumber.Substring(0, resourceNumber.LastIndexOf('_'))}";
tag.ValueSupplement = viewerUrl;
meta.Add(tag);
List pages = new List();
int order = 0;
for(int i = 0; i < PageUrls.Length; i++)
{
if (PageUrls[i] == "##")
continue;
order++;
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.ProgressPercent = order;
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
RArtifactItemRecord page = new RArtifactItemRecord()
{
Name = $"تصویر {order}",
NameInEnglish = $"Image {order}",
Description = "",
DescriptionInEnglish = "",
Order = order,
FriendlyUrl = $"p{$"{order}".PadLeft(4, '0')}",
LastModified = DateTime.Now
};
List pageTags = new List();
tag = await TagHandler.PrepareAttribute(context, "Source", "British Library", 1);
tag.ValueSupplement = $"http://www.bl.uk/manuscripts/Viewer.aspx?ref={PageUrls[i]}";
pageTags.Add(tag);
if (!string.IsNullOrEmpty(PageTitles[i]))
{
RTagValue toc = await TagHandler.PrepareAttribute(context, "Title in TOC", PageTitles[i], 1);
toc.ValueSupplement = "1";//font size
pageTags.Add(toc);
}
if (!string.IsNullOrEmpty(PageTexts[i]))
{
tag = await TagHandler.PrepareAttribute(context, "Label", PageTexts[i], 1);
pageTags.Add(tag);
}
page.Tags = pageTags.ToArray();
bool recovered = false;
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
)
&&
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
)
&&
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
RServiceResult picture = await _pictureFileService.RecoverFromeFiles(page.Name, page.Description, 1,
viewerUrl,
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg"),
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg"),
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg"),
$"{order}".PadLeft(4, '0') + ".jpg", friendlyUrl);
if (picture.Result != null)
{
recovered = true;
page.Images = new RPictureFile[] { picture.Result };
page.CoverImageIndex = 0;
if (book.CoverItemIndex == (order - 1))
{
book.CoverImage = RPictureFile.Duplicate(picture.Result);
}
pages.Add(page);
}
}
if (!recovered)
{
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
/*
failed multithread attempt:
BLTileMixer mixer = new BLTileMixer();
RServiceResult blResult = await mixer.DownloadMix(PageUrls[i], order);
*/
Dictionary<(int x, int y), Image> tiles = new Dictionary<(int x, int y), Image>();
int max_x = -1;
for(int x = 0; ;x++)
{
string imageUrl = $"http://www.bl.uk/manuscripts/Proxy.ashx?view={PageUrls[i]}_files/13/{x}_0.jpg";
var imageResult = await client.GetAsync(imageUrl);
int _ImportRetryCount = 5;
int _ImportRetryInitialSleep = 500;
int retryCount = 0;
while (retryCount < _ImportRetryCount && !imageResult.IsSuccessStatusCode && imageResult.StatusCode == HttpStatusCode.ServiceUnavailable)
{
imageResult.Dispose();
Thread.Sleep(_ImportRetryInitialSleep * (retryCount + 1));
imageResult = await client.GetAsync(imageUrl);
retryCount++;
}
if (imageResult.IsSuccessStatusCode)
{
using (Stream imageStream = await imageResult.Content.ReadAsStreamAsync())
{
imageStream.Position = 0;
try
{
Image tile = Image.FromStream(imageStream);
tiles.Add((x, 0), tile);
max_x = x;
}
catch(Exception aexp)
{
if (aexp is ArgumentException)
{
break;
}
throw aexp;
}
}
}
else
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = $"Http result is not ok ({imageResult.StatusCode}) for page {order}, url {imageUrl}";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
imageResult.Dispose();
return;
}
}
int max_y = -1;
for (int y = 1; ; y++)
{
string imageUrl = $"http://www.bl.uk/manuscripts/Proxy.ashx?view={PageUrls[i]}_files/13/0_{y}.jpg";
var imageResult = await client.GetAsync(imageUrl);
int _ImportRetryCount = 5;
int _ImportRetryInitialSleep = 500;
int retryCount = 0;
while (retryCount < _ImportRetryCount && !imageResult.IsSuccessStatusCode && imageResult.StatusCode == HttpStatusCode.ServiceUnavailable)
{
imageResult.Dispose();
Thread.Sleep(_ImportRetryInitialSleep * (retryCount + 1));
imageResult = await client.GetAsync(imageUrl);
retryCount++;
}
if (imageResult.IsSuccessStatusCode)
{
using (Stream imageStream = await imageResult.Content.ReadAsStreamAsync())
{
if (imageStream.Length <= 248)
break;
imageStream.Position = 0;
try
{
Image tile = Image.FromStream(imageStream);
tiles.Add((0, y), tile);
max_y = y;
}
catch (Exception aexp)
{
if (aexp is ArgumentException)
{
break;
}
throw aexp;
}
}
}
else
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = $"Http result is not ok ({imageResult.StatusCode}) for page {order}, url {imageUrl}";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
imageResult.Dispose();
return;
}
}
for(int x = 0; x <= max_x; x++)
for(int y = 0; y <= max_y; y++)
if(tiles.TryGetValue((x, y), out Image tmp) == false)
{
string imageUrl = $"http://www.bl.uk/manuscripts/Proxy.ashx?view={PageUrls[i]}_files/13/{x}_{y}.jpg";
var imageResult = await client.GetAsync(imageUrl);
int _ImportRetryCount = 5;
int _ImportRetryInitialSleep = 500;
int retryCount = 0;
while (retryCount < _ImportRetryCount && !imageResult.IsSuccessStatusCode && imageResult.StatusCode == HttpStatusCode.ServiceUnavailable)
{
imageResult.Dispose();
Thread.Sleep(_ImportRetryInitialSleep * (retryCount + 1));
imageResult = await client.GetAsync(imageUrl);
retryCount++;
}
if (imageResult.IsSuccessStatusCode)
{
using (Stream imageStream = await imageResult.Content.ReadAsStreamAsync())
{
if (imageStream.Length == 0)
break;
imageStream.Position = 0;
tiles.Add((x, y), Image.FromStream(imageStream));
}
}
else
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = $"Http result is not ok ({imageResult.StatusCode}) for page {order}, url {imageUrl}";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
imageResult.Dispose();
return;
}
}
int tileWidth = tiles[(0, 0)].Width;
int tileHeight = tiles[(0, 0)].Height;
int imageWidth = tileWidth * (max_x + 1);
int imageHeight = tileHeight * (max_y + 1);
using(Image image = new Bitmap(imageWidth, imageHeight))
{
using(Graphics g = Graphics.FromImage(image))
{
for(int x = 0; x <= max_x; x++)
for(int y = 0; y < max_y; y++)
{
g.DrawImage(tiles[(x, y)], new Point(x * tileWidth, y * tileHeight));
tiles[(x, y)].Dispose();
}
using (Stream imageStream = new MemoryStream())
{
ImageCodecInfo jpgEncoder = _pictureFileService.GetEncoder(ImageFormat.Jpeg);
Encoder myEncoder =
Encoder.Quality;
EncoderParameters jpegParameters = new EncoderParameters(1);
EncoderParameter qualityParameter = new EncoderParameter(myEncoder, 92L);
jpegParameters.Param[0] = qualityParameter;
image.Save(imageStream, jpgEncoder, jpegParameters);
RServiceResult picture = await _pictureFileService.Add(page.Name, page.Description, 1, null, $"http://www.bl.uk/manuscripts/Viewer.aspx?ref={PageUrls[i]}", imageStream, $"{order}".PadLeft(4, '0') + ".jpg", friendlyUrl);
if (picture.Result == null)
{
throw new Exception($"_pictureFileService.Add : {picture.ExceptionString}");
}
page.Images = new RPictureFile[] { picture.Result };
page.CoverImageIndex = 0;
if (book.CoverItemIndex == (order - 1))
{
book.CoverImage = RPictureFile.Duplicate(picture.Result);
}
pages.Add(page);
}
}
}
GC.Collect();
}
}
book.Items = pages.ToArray();
book.ItemCount = pages.Count;
if (pages.Count == 0)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "Pages.Count == 0";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
await context.Artifacts.AddAsync(book);
await context.SaveChangesAsync();
job.ProgressPercent = 100;
job.Status = ImportJobStatus.Succeeded;
job.ArtifactId = book.Id;
job.EndTime = DateTime.Now;
context.Update(job);
await context.SaveChangesAsync();
}
}
else
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = $"Http result is not ok ({result.StatusCode}) for {url}";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
}
}
}
catch (Exception exp)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = exp.ToString();
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
}
}
);
return new RServiceResult(true);
}
catch (Exception exp)
{
return new RServiceResult(false, exp.ToString());
}
}
///
/// import from server folder
///
/// C:\Tools\batches\florence
/// shahname-florence
/// https://t.me/dr_khatibi_abolfazl/888
///
private async Task> StartImportingFromServerFolder(string folderPath, string friendlyUrl, string srcUrl)
{
try
{
if (
(
await _context.ImportJobs
.Where(j => j.JobType == JobType.ServerFolder && j.ResourceNumber == folderPath && !(j.Status == ImportJobStatus.Failed || j.Status == ImportJobStatus.Aborted))
.SingleOrDefaultAsync()
)
!=
null
)
{
return new RServiceResult(false, $"Job is already scheduled or running for importing server folder {folderPath}");
}
if (string.IsNullOrEmpty(friendlyUrl))
{
return new RServiceResult(false, $"Friendly url is empty, server folder {folderPath}");
}
if (
(await _context.Artifacts.Where(a => a.FriendlyUrl == friendlyUrl).SingleOrDefaultAsync())
!=
null
)
{
return new RServiceResult(false, $"duplicated friendly url '{friendlyUrl}'");
}
ImportJob job = new ImportJob()
{
JobType = JobType.ServerFolder,
ResourceNumber = folderPath,
FriendlyUrl = friendlyUrl,
SrcUrl = srcUrl,
QueueTime = DateTime.Now,
ProgressPercent = 0,
Status = ImportJobStatus.NotStarted
};
await _context.ImportJobs.AddAsync
(
job
);
await _context.SaveChangesAsync();
_backgroundTaskQueue.QueueBackgroundWorkItem
(
async token =>
{
try
{
using (RMuseumDbContext context = new RMuseumDbContext(Configuration))
{
RArtifactMasterRecord book = new RArtifactMasterRecord($"extracted from server folder {job.ResourceNumber}", $"extracted from server folder {job.ResourceNumber}")
{
Status = PublishStatus.Draft,
DateTime = DateTime.Now,
LastModified = DateTime.Now,
CoverItemIndex = 0,
FriendlyUrl = friendlyUrl
};
List meta = new List();
RTagValue tag;
tag = await TagHandler.PrepareAttribute(context, "Type", "Book", 1);
meta.Add(tag);
tag = await TagHandler.PrepareAttribute(context, "Type", "Manuscript", 1);
meta.Add(tag);
meta.Add(tag);
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.StartTime = DateTime.Now;
job.Status = ImportJobStatus.Running;
job.SrcContent = "";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
List pages = new List();
string[] fileNames = Directory.GetFiles(job.ResourceNumber, "*.jpg");
int order = 0;
foreach (string fileName in fileNames)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.ProgressPercent = order * 100 / (decimal)fileNames.Length;
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
order++;
RArtifactItemRecord page = new RArtifactItemRecord()
{
Name = $"تصویر {order}",
NameInEnglish = $"Image {order} of {book.NameInEnglish}",
Description = "",
DescriptionInEnglish = "",
Order = order,
FriendlyUrl = $"p{$"{order}".PadLeft(4, '0')}",
LastModified = DateTime.Now
};
page.Tags = new RTagValue[] { };
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "orig"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "norm"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
if (
File.Exists
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
)
)
{
File.Delete
(
Path.Combine(Path.Combine(Path.Combine(_pictureFileService.ImageStoragePath, friendlyUrl), "thumb"), $"{order}".PadLeft(4, '0') + ".jpg")
);
}
using (FileStream imageStream = new FileStream(fileName, FileMode.Open))
{
RServiceResult picture = await _pictureFileService.Add(page.Name, page.Description, 1, null, job.SrcUrl, imageStream, $"{order}".PadLeft(4, '0') + ".jpg", friendlyUrl);
if (picture.Result == null)
{
throw new Exception($"_pictureFileService.Add : {picture.ExceptionString}");
}
page.Images = new RPictureFile[] { picture.Result };
page.CoverImageIndex = 0;
if (book.CoverItemIndex == (order - 1))
{
book.CoverImage = RPictureFile.Duplicate(picture.Result);
}
}
pages.Add(page);
}
book.Tags = meta.ToArray();
book.Items = pages.ToArray();
book.ItemCount = pages.Count;
if (pages.Count == 0)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = "Pages.Count == 0";
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
return;
}
await context.Artifacts.AddAsync(book);
await context.SaveChangesAsync();
job.ProgressPercent = 100;
job.Status = ImportJobStatus.Succeeded;
job.ArtifactId = book.Id;
job.EndTime = DateTime.Now;
context.Update(job);
await context.SaveChangesAsync();
}
}
catch (Exception exp)
{
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.EndTime = DateTime.Now;
job.Status = ImportJobStatus.Failed;
job.Exception = exp.ToString();
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
}
}
);
return new RServiceResult(true);
}
catch (Exception exp)
{
return new RServiceResult(false, exp.ToString());
}
}
///
/// from http://www.thedigitalwalters.org/01_ACCESS_WALTERS_MANUSCRIPTS.html
///
/// W619
/// golestan-walters-01
///
private async Task> StartImportingFromWalters(string resourceNumber, string friendlyUrl)
{
string url = $"http://www.thedigitalwalters.org/Data/WaltersManuscripts/ManuscriptDescriptions/{resourceNumber}_tei.xml";
if (
(
await _context.ImportJobs
.Where(j => j.JobType == JobType.Walters && j.ResourceNumber == resourceNumber && !(j.Status == ImportJobStatus.Failed || j.Status == ImportJobStatus.Aborted))
.SingleOrDefaultAsync()
)
!=
null
)
{
return new RServiceResult(false, $"Job is already scheduled or running for importing {url}");
}
if (string.IsNullOrEmpty(friendlyUrl))
{
friendlyUrl = resourceNumber;
}
if (
(await _context.Artifacts.Where(a => a.FriendlyUrl == friendlyUrl).SingleOrDefaultAsync())
!=
null
)
{
return new RServiceResult(false, $"duplicated friendly url '{friendlyUrl}'");
}
ImportJob job = new ImportJob()
{
JobType = JobType.Walters,
ResourceNumber = resourceNumber,
FriendlyUrl = friendlyUrl,
SrcUrl = url,
QueueTime = DateTime.Now,
ProgressPercent = 0,
Status = ImportJobStatus.NotStarted
};
await _context.ImportJobs.AddAsync
(
job
);
await _context.SaveChangesAsync();
try
{
_backgroundTaskQueue.QueueBackgroundWorkItem
(
async token =>
{
try
{
using (var client = new HttpClient())
{
using (var result = await client.GetAsync(url))
{
if (result.IsSuccessStatusCode)
{
using (RMuseumDbContext context = new RMuseumDbContext(Configuration))
{
RArtifactMasterRecord book = new RArtifactMasterRecord($"extracted from {url}", $"extracted from {url}")
{
Status = PublishStatus.Draft,
DateTime = DateTime.Now,
LastModified = DateTime.Now,
CoverItemIndex = 0,
FriendlyUrl = friendlyUrl
};
List meta = new List();
RTagValue tag;
string xml = await result.Content.ReadAsStringAsync();
using (RMuseumDbContext importJobUpdaterDb = new RMuseumDbContext(Configuration))
{
job.StartTime = DateTime.Now;
job.Status = ImportJobStatus.Running;
job.SrcContent = xml;
importJobUpdaterDb.Update(job);
await importJobUpdaterDb.SaveChangesAsync();
}
XElement elObject = XDocument.Parse(xml).Root;
tag = await TagHandler.PrepareAttribute(context, "Type", "Book", 1);
meta.Add(tag);
tag = await TagHandler.PrepareAttribute(context, "Type", "Manuscript", 1);
meta.Add(tag);
try
{
foreach (var prop in elObject
.Elements("{http://www.tei-c.org/ns/1.0}teiHeader").First()
.Elements("{http://www.tei-c.org/ns/1.0}fileDesc").First()
.Elements("{http://www.tei-c.org/ns/1.0}titleStmt").First()
.Elements("{http://www.tei-c.org/ns/1.0}title"))
{
string label = prop.Value;
book.Name = book.NameInEnglish =
book.Description = book.DescriptionInEnglish =
label;
tag = await TagHandler.PrepareAttribute(context, "Title", label, 1);
meta.Add(tag);
break;
}
}
catch
{
//ignore non-existing = null tags
}
try
{
foreach (var prop in elObject
.Elements("{http://www.tei-c.org/ns/1.0}teiHeader").First()
.Elements("{http://www.tei-c.org/ns/1.0}fileDesc").First()
.Elements("{http://www.tei-c.org/ns/1.0}titleStmt").First()
.Elements("{http://www.tei-c.org/ns/1.0}author"))
{
string label = prop.Value;
tag = await TagHandler.PrepareAttribute(context, "Contributor Names", label, 1);
meta.Add(tag);
break;
}
}
catch
{
//ignore non-existing = null tags
}
try
{
foreach (var prop in elObject
.Elements("{http://www.tei-c.org/ns/1.0}teiHeader").First()
.Elements("{http://www.tei-c.org/ns/1.0}fileDesc").First()
.Elements("{http://www.tei-c.org/ns/1.0}titleStmt").First()
.Elements("{http://www.tei-c.org/ns/1.0}respStmt"))
{
string label = prop.Elements("{http://www.tei-c.org/ns/1.0}name").First().Value;
tag = await TagHandler.PrepareAttribute(context, "Contributor Names", label, 1);
meta.Add(tag);
break;
}
}
catch
{
//ignore non-existing = null tags
}
try
{
foreach (var prop in elObject
.Elements("{http://www.tei-c.org/ns/1.0}teiHeader").First()
.Elements("{http://www.tei-c.org/ns/1.0}fileDesc").First()
.Elements("{http://www.tei-c.org/ns/1.0}notesStmt").First()
.Elements("{http://www.tei-c.org/ns/1.0}note"))
{
string label = prop.Value;
tag = await TagHandler.PrepareAttribute(context, "Notes", label, 1);
meta.Add(tag);
}
}
catch
{
//ignore non-existing = null tags
}
tag = await TagHandler.PrepareAttribute(context, "Source", "Digitized Walters Manuscripts", 1);
tag.ValueSupplement = $"http://www.thedigitalwalters.org/Data/WaltersManuscripts/html/{job.ResourceNumber}/";
meta.Add(tag);
book.Tags = meta.ToArray();
List