-
Notifications
You must be signed in to change notification settings - Fork 3
/
InspireCitationNumberRefreshOperation.m
94 lines (90 loc) · 2.77 KB
/
InspireCitationNumberRefreshOperation.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//
// InspireCitationNumberRefreshOperation.m
// spires
//
// Created by Yuji on 3/26/11.
// Copyright 2011 Y. Tachikawa. All rights reserved.
//
#import "InspireCitationNumberRefreshOperation.h"
#import "Article.h"
#import "NSString+magic.h"
#import "SpiresHelper.h"
#import "MOC.h"
@implementation InspireCitationNumberRefreshOperation
{
NSSet*articles;
NSMutableDictionary*recidToArticle;
NSManagedObjectContext*moc;
NSString*description_;
}
-(InspireCitationNumberRefreshOperation*)initWithArticles:(NSSet*)aa;
{
self=[super init];
articles=aa;
Article*a=[articles anyObject];
moc=a.managedObjectContext;
[moc performBlockAndWait:^{
description_=[NSString stringWithFormat:@"citation number query for %@ etc.",a.title];
}];
return self;
}
-(NSString*)description
{
if([articles count]==0){
return @"invalid query operation";
}else{
return description_;
}
}
-(void)dealWith:(NSArray*)x
{
NSString*query=[NSString stringWithFormat: @"recid:%@&of=hb",[x componentsJoinedByString:@" or recid:"]];
NSURL*url=[[SpiresHelper sharedHelper] inspireURLForQuery:query];
NSString*result=[NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:NULL];
NSArray*chunks=[result componentsSeparatedByString:@"<tr"];
NSMutableDictionary*recidToCites=[NSMutableDictionary dictionary];
for(NSString*chunk in chunks){
if([chunk rangeOfString:@"unapi-id"].location==NSNotFound)
continue;
NSString*recid=[chunk stringByMatching:@"<abbr.+?title=\"(.+?)\"" capture:1];
if(recid && ![recid isEqualToString:@""]){
NSString*cited=[chunk stringByMatching:@"Cited +by +(\\d+) +rec" capture:1];
if(cited)
recidToCites[recid] = cited;
}
}
for(NSString*rec in [recidToCites allKeys]){
NSString*cited=recidToCites[rec];
Article*article=recidToArticle[rec];
if(cited && article){
article.citecount=@([cited intValue]);
}
}
}
-(void)main
{
[moc performBlockAndWait:^{
recidToArticle=[NSMutableDictionary dictionary];
for(Article*a in articles){
if(a.inspireKey){
recidToArticle[[a.inspireKey stringValue]] = a;
}
}
NSMutableArray*a=[NSMutableArray array];
for(NSString*recid in [recidToArticle allKeys]){
[a addObject:recid];
if([a count]>16){
[self dealWith:a];
a=[NSMutableArray array];
[moc save:NULL];
}
}
if([a count]>0){
[self dealWith:a];
[moc save:NULL];
}
}];
}
@end