proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
pig-mesh_pig
|
pig/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/VelocityKit.java
|
VelocityKit
|
render
|
class VelocityKit {
/**
* Velocity 模板渲染方法
* @param template 模板
* @param map 数据模型
* @return 渲染结果
*/
public static String render(String template, Map<String, Object> map) {<FILL_FUNCTION_BODY>}
/**
* 渲染文本
* @param str
* @param dataModel 数据
* @return
*/
public static String renderStr(String str, Map<String, Object> dataModel) {
// 设置velocity资源加载器
Velocity.init();
StringWriter stringWriter = new StringWriter();
VelocityContext context = new VelocityContext(dataModel);
// 函数库
context.put("math", new MathTool());
context.put("dateTool", new DateTool());
context.put("dict", new DictTool());
context.put("str", new NamingCaseTool());
Velocity.evaluate(context, stringWriter, "renderStr", str);
return stringWriter.toString();
}
}
|
// 设置velocity资源加载器
Properties prop = new Properties();
prop.put("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(prop);
VelocityContext context = new VelocityContext(map);
// 函数库,使用 Lambda 表达式简化代码
Optional.of(new MathTool()).ifPresent(mt -> context.put("math", mt));
Optional.of(new DateTool()).ifPresent(dt -> context.put("dateTool", dt));
Optional.of(new DictTool()).ifPresent(dt -> context.put("dict", dt));
Optional.of(new NamingCaseTool()).ifPresent(nct -> context.put("str", nct));
// 渲染模板,使用 Lambda 表达式简化代码
StringWriter sw = new StringWriter();
Optional.ofNullable(Velocity.getTemplate(template, CharsetUtil.UTF_8)).ifPresent(tpl -> tpl.merge(context, sw));
return sw.toString();
| 284
| 290
| 574
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-monitor/src/main/java/com/pig4cloud/pig/monitor/config/CustomCsrfFilter.java
|
CustomCsrfFilter
|
doFilterInternal
|
class CustomCsrfFilter extends OncePerRequestFilter {
public static final String CSRF_COOKIE_NAME = "XSRF-TOKEN";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {<FILL_FUNCTION_BODY>}
}
|
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME);
String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie(CSRF_COOKIE_NAME, token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
| 90
| 175
| 265
|
<methods>public void <init>() ,public final void doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) throws jakarta.servlet.ServletException, java.io.IOException<variables>public static final java.lang.String ALREADY_FILTERED_SUFFIX
|
pig-mesh_pig
|
pig/pig-visual/pig-monitor/src/main/java/com/pig4cloud/pig/monitor/config/SecuritySecureConfig.java
|
SecuritySecureConfig
|
filterChain
|
class SecuritySecureConfig {
private final AdminServerProperties adminServer;
private final SecurityProperties security;
public SecuritySecureConfig(AdminServerProperties adminServer, SecurityProperties security) {
this.adminServer = adminServer;
this.security = security;
}
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>}
// Required to provide UserDetailsService for "remember functionality"
@Bean
public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.withUsername(security.getUser().getName())
.password(passwordEncoder.encode(security.getUser().getPassword()))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests //
.requestMatchers(new AntPathRequestMatcher(this.adminServer.path("/assets/**")))
.permitAll()
.requestMatchers(new AntPathRequestMatcher(this.adminServer.path("/actuator/info")))
.permitAll()
.requestMatchers(new AntPathRequestMatcher(adminServer.path("/actuator/health")))
.permitAll()
.requestMatchers(new AntPathRequestMatcher(this.adminServer.path("/login")))
.permitAll()
.dispatcherTypeMatchers(DispatcherType.ASYNC)
.permitAll() // https://github.com/spring-projects/spring-security/issues/11027
.anyRequest()
.authenticated())
.formLogin(
(formLogin) -> formLogin.loginPage(this.adminServer.path("/login")).successHandler(successHandler))
.logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")))
.httpBasic(Customizer.withDefaults());
http.addFilterAfter(new CustomCsrfFilter(), BasicAuthenticationFilter.class) // <5>
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
.ignoringRequestMatchers(
new AntPathRequestMatcher(this.adminServer.path("/instances"), POST.toString()), // <6>
new AntPathRequestMatcher(this.adminServer.path("/instances/*"), DELETE.toString()), // <6>
new AntPathRequestMatcher(this.adminServer.path("/actuator/**")) // <7>
));
http.rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
return http.build();
| 231
| 580
| 811
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-monitor/src/main/java/com/pig4cloud/pig/monitor/converter/NacosServiceInstanceConverter.java
|
NacosServiceInstanceConverter
|
getMetadata
|
class NacosServiceInstanceConverter extends DefaultServiceInstanceConverter {
@Override
protected Map<String, String> getMetadata(ServiceInstance instance) {<FILL_FUNCTION_BODY>}
}
|
return (instance.getMetadata() != null) ? instance.getMetadata()
.entrySet()
.stream()
.filter((e) -> e.getKey() != null && e.getValue() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) : emptyMap();
| 50
| 87
| 137
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/config/AutowireCapableBeanJobFactory.java
|
AutowireCapableBeanJobFactory
|
createJobInstance
|
class AutowireCapableBeanJobFactory extends SpringBeanJobFactory {
private final AutowireCapableBeanFactory beanFactory;
AutowireCapableBeanJobFactory(AutowireCapableBeanFactory beanFactory) {
Assert.notNull(beanFactory, "Bean factory must not be null");
this.beanFactory = beanFactory;
}
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Object jobInstance = super.createJobInstance(bundle);
this.beanFactory.autowireBean(jobInstance);
// 此处必须注入 beanName 不然sentinel 报错
JobKey jobKey = bundle.getTrigger().getJobKey();
String beanName = jobKey + jobKey.getName();
this.beanFactory.initializeBean(jobInstance, beanName);
return jobInstance;
| 121
| 108
| 229
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/config/PigInitQuartzJob.java
|
PigInitQuartzJob
|
afterPropertiesSet
|
class PigInitQuartzJob implements InitializingBean {
private final SysJobService sysJobService;
private final TaskUtil taskUtil;
private final Scheduler scheduler;
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
}
|
sysJobService.list().forEach(sysjob -> {
if (PigQuartzEnum.JOB_STATUS_RELEASE.getType().equals(sysjob.getJobStatus())) {
taskUtil.removeJob(sysjob, scheduler);
}
else if (PigQuartzEnum.JOB_STATUS_RUNNING.getType().equals(sysjob.getJobStatus())) {
taskUtil.resumeJob(sysjob, scheduler);
}
else if (PigQuartzEnum.JOB_STATUS_NOT_RUNNING.getType().equals(sysjob.getJobStatus())) {
taskUtil.pauseJob(sysjob, scheduler);
}
else {
taskUtil.removeJob(sysjob, scheduler);
}
});
| 74
| 202
| 276
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/config/PigQuartzConfig.java
|
PigQuartzConfig
|
quartzScheduler
|
class PigQuartzConfig {
private final QuartzProperties properties;
private final List<SchedulerFactoryBeanCustomizer> customizers;
private final JobDetail[] jobDetails;
private final Map<String, Calendar> calendars;
private final Trigger[] triggers;
private final ApplicationContext applicationContext;
public PigQuartzConfig(QuartzProperties properties,
ObjectProvider<List<SchedulerFactoryBeanCustomizer>> customizers, ObjectProvider<JobDetail[]> jobDetails,
ObjectProvider<Map<String, Calendar>> calendars, ObjectProvider<Trigger[]> triggers,
ApplicationContext applicationContext) {
this.properties = properties;
this.customizers = customizers.getIfAvailable();
this.jobDetails = jobDetails.getIfAvailable();
this.calendars = calendars.getIfAvailable();
this.triggers = triggers.getIfAvailable();
this.applicationContext = applicationContext;
}
@Bean
@ConditionalOnMissingBean
public SchedulerFactoryBean quartzScheduler() {<FILL_FUNCTION_BODY>}
private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}
private void customize(SchedulerFactoryBean schedulerFactoryBean) {
if (this.customizers != null) {
for (SchedulerFactoryBeanCustomizer customizer : this.customizers) {
customizer.customize(schedulerFactoryBean);
}
}
}
/**
* 通过SchedulerFactoryBean获取Scheduler的实例
* @return
*/
@Bean
public Scheduler scheduler() {
return quartzScheduler().getScheduler();
}
}
|
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean
.setJobFactory(new AutowireCapableBeanJobFactory(this.applicationContext.getAutowireCapableBeanFactory()));
if (!this.properties.getProperties().isEmpty()) {
schedulerFactoryBean.setQuartzProperties(this.asProperties(this.properties.getProperties()));
}
if (this.jobDetails != null && this.jobDetails.length > 0) {
schedulerFactoryBean.setJobDetails(this.jobDetails);
}
if (this.calendars != null && !this.calendars.isEmpty()) {
schedulerFactoryBean.setCalendars(this.calendars);
}
if (this.triggers != null && this.triggers.length > 0) {
schedulerFactoryBean.setTriggers(this.triggers);
}
this.customize(schedulerFactoryBean);
return schedulerFactoryBean;
| 437
| 260
| 697
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/event/SysJobListener.java
|
SysJobListener
|
comSysJob
|
class SysJobListener {
private final TaskInvokUtil taskInvokUtil;
@Async
@Order
@EventListener(SysJobEvent.class)
public void comSysJob(SysJobEvent event) {<FILL_FUNCTION_BODY>}
}
|
SysJob sysJob = event.getSysJob();
Trigger trigger = event.getTrigger();
taskInvokUtil.invokMethod(sysJob, trigger);
| 68
| 49
| 117
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/util/JarTaskInvok.java
|
JarTaskInvok
|
invokMethod
|
class JarTaskInvok implements ITaskInvok {
@Override
public void invokMethod(SysJob sysJob) throws TaskException {<FILL_FUNCTION_BODY>}
}
|
ProcessBuilder processBuilder = new ProcessBuilder();
File jar = new File(sysJob.getExecutePath());
processBuilder.directory(jar.getParentFile());
List<String> commands = new ArrayList<>();
commands.add("java");
commands.add("-jar");
commands.add(sysJob.getExecutePath());
if (StrUtil.isNotEmpty(sysJob.getMethodParamsValue())) {
commands.add(sysJob.getMethodParamsValue());
}
processBuilder.command(commands);
try {
processBuilder.start();
}
catch (IOException e) {
log.error("定时任务jar反射执行异常,执行任务:{}", sysJob.getExecutePath());
throw new TaskException("定时任务jar反射执行异常,执行任务:" + sysJob.getExecutePath());
}
| 48
| 231
| 279
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/util/JavaClassTaskInvok.java
|
JavaClassTaskInvok
|
invokMethod
|
class JavaClassTaskInvok implements ITaskInvok {
@Override
public void invokMethod(SysJob sysJob) throws TaskException {<FILL_FUNCTION_BODY>}
}
|
Object obj;
Class clazz;
Method method;
Object returnValue;
try {
if (StrUtil.isNotEmpty(sysJob.getMethodParamsValue())) {
clazz = Class.forName(sysJob.getClassName());
obj = clazz.newInstance();
method = clazz.getDeclaredMethod(sysJob.getMethodName(), String.class);
returnValue = method.invoke(obj, sysJob.getMethodParamsValue());
}
else {
clazz = Class.forName(sysJob.getClassName());
obj = clazz.newInstance();
method = clazz.getDeclaredMethod(sysJob.getMethodName());
returnValue = method.invoke(obj);
}
if (StrUtil.isEmpty(returnValue.toString())
|| PigQuartzEnum.JOB_LOG_STATUS_FAIL.getType().equals(returnValue.toString())) {
log.error("定时任务javaClassTaskInvok异常,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务javaClassTaskInvok业务执行失败,任务:" + sysJob.getClassName());
}
}
catch (ClassNotFoundException e) {
log.error("定时任务java反射类没有找到,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务java反射类没有找到,执行任务:" + sysJob.getClassName());
}
catch (IllegalAccessException e) {
log.error("定时任务java反射类异常,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务java反射类异常,执行任务:" + sysJob.getClassName());
}
catch (InstantiationException e) {
log.error("定时任务java反射类异常,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务java反射类异常,执行任务:" + sysJob.getClassName());
}
catch (NoSuchMethodException e) {
log.error("定时任务java反射执行方法名异常,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务java反射执行方法名异常,执行任务:" + sysJob.getClassName());
}
catch (InvocationTargetException e) {
log.error("定时任务java反射执行异常,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务java反射执行异常,执行任务:" + sysJob.getClassName());
}
| 49
| 685
| 734
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/util/RestTaskInvok.java
|
RestTaskInvok
|
invokMethod
|
class RestTaskInvok implements ITaskInvok {
@Override
public void invokMethod(SysJob sysJob) throws TaskException {<FILL_FUNCTION_BODY>}
}
|
try {
HttpRequest request = HttpUtil.createGet(sysJob.getExecutePath());
request.execute();
}
catch (Exception e) {
log.error("定时任务restTaskInvok异常,执行任务:{}", sysJob.getExecutePath());
throw new TaskException("定时任务restTaskInvok业务执行失败,任务:" + sysJob.getExecutePath());
}
| 48
| 110
| 158
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/util/SpringBeanTaskInvok.java
|
SpringBeanTaskInvok
|
invokMethod
|
class SpringBeanTaskInvok implements ITaskInvok {
@Override
public void invokMethod(SysJob sysJob) throws TaskException {<FILL_FUNCTION_BODY>}
}
|
Object target;
Method method;
Object returnValue;
// 通过Spring上下文去找 也有可能找不到
target = SpringContextHolder.getBean(sysJob.getClassName());
try {
if (StrUtil.isNotEmpty(sysJob.getMethodParamsValue())) {
method = target.getClass().getDeclaredMethod(sysJob.getMethodName(), String.class);
ReflectionUtils.makeAccessible(method);
returnValue = method.invoke(target, sysJob.getMethodParamsValue());
}
else {
method = target.getClass().getDeclaredMethod(sysJob.getMethodName());
ReflectionUtils.makeAccessible(method);
returnValue = method.invoke(target);
}
if (StrUtil.isEmpty(returnValue.toString())
|| PigQuartzEnum.JOB_LOG_STATUS_FAIL.getType().equals(returnValue.toString())) {
log.error("定时任务springBeanTaskInvok异常,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务springBeanTaskInvok业务执行失败,任务:" + sysJob.getClassName());
}
}
catch (NoSuchMethodException e) {
log.error("定时任务spring bean反射异常方法未找到,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务spring bean反射异常方法未找到,执行任务:" + sysJob.getClassName());
}
catch (IllegalAccessException e) {
log.error("定时任务spring bean反射异常,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务spring bean反射异常,执行任务:" + sysJob.getClassName());
}
catch (InvocationTargetException e) {
log.error("定时任务spring bean反射执行异常,执行任务:{}", sysJob.getClassName());
throw new TaskException("定时任务spring bean反射执行异常,执行任务:" + sysJob.getClassName());
}
| 49
| 539
| 588
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/util/TaskInvokFactory.java
|
TaskInvokFactory
|
getInvoker
|
class TaskInvokFactory {
/**
* 根据对应jobType获取对应 invoker
* @param jobType
* @return
* @throws TaskException
*/
public static ITaskInvok getInvoker(String jobType) throws TaskException {<FILL_FUNCTION_BODY>}
}
|
if (StrUtil.isBlank(jobType)) {
log.info("获取TaskInvok传递参数有误,jobType:{}", jobType);
throw new TaskException("");
}
ITaskInvok iTaskInvok = null;
if (JobTypeQuartzEnum.JAVA.getType().equals(jobType)) {
iTaskInvok = SpringContextHolder.getBean("javaClassTaskInvok");
}
else if (JobTypeQuartzEnum.SPRING_BEAN.getType().equals(jobType)) {
iTaskInvok = SpringContextHolder.getBean("springBeanTaskInvok");
}
else if (JobTypeQuartzEnum.REST.getType().equals(jobType)) {
iTaskInvok = SpringContextHolder.getBean("restTaskInvok");
}
else if (JobTypeQuartzEnum.JAR.getType().equals(jobType)) {
iTaskInvok = SpringContextHolder.getBean("jarTaskInvok");
}
else if (StrUtil.isBlank(jobType)) {
log.info("定时任务类型无对应反射方式,反射类型:{}", jobType);
throw new TaskException("");
}
return iTaskInvok;
| 80
| 328
| 408
|
<no_super_class>
|
pig-mesh_pig
|
pig/pig-visual/pig-quartz/src/main/java/com/pig4cloud/pig/daemon/quartz/util/TaskInvokUtil.java
|
TaskInvokUtil
|
invokMethod
|
class TaskInvokUtil {
private final ApplicationEventPublisher publisher;
private final SysJobService sysJobService;
@SneakyThrows
public void invokMethod(SysJob sysJob, Trigger trigger) {<FILL_FUNCTION_BODY>}
}
|
// 执行开始时间
long startTime;
// 执行结束时间
long endTime;
// 获取执行开始时间
startTime = System.currentTimeMillis();
// 更新定时任务表内的状态、执行时间、上次执行时间、下次执行时间等信息
SysJob updateSysjob = new SysJob();
updateSysjob.setJobId(sysJob.getJobId());
// 日志
SysJobLog sysJobLog = new SysJobLog();
sysJobLog.setJobId(sysJob.getJobId());
sysJobLog.setJobName(sysJob.getJobName());
sysJobLog.setJobGroup(sysJob.getJobGroup());
sysJobLog.setJobOrder(sysJob.getJobOrder());
sysJobLog.setJobType(sysJob.getJobType());
sysJobLog.setExecutePath(sysJob.getExecutePath());
sysJobLog.setClassName(sysJob.getClassName());
sysJobLog.setMethodName(sysJob.getMethodName());
sysJobLog.setMethodParamsValue(sysJob.getMethodParamsValue());
sysJobLog.setCronExpression(sysJob.getCronExpression());
try {
// 执行任务
ITaskInvok iTaskInvok = TaskInvokFactory.getInvoker(sysJob.getJobType());
// 确保租户上下文有值,使得当前线程中的多租户特性生效。
iTaskInvok.invokMethod(sysJob);
// 记录成功状态
sysJobLog.setJobMessage(PigQuartzEnum.JOB_LOG_STATUS_SUCCESS.getDescription());
sysJobLog.setJobLogStatus(PigQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType());
// 任务表信息更新
updateSysjob.setJobExecuteStatus(PigQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType());
}
catch (Throwable e) {
log.error("定时任务执行失败,任务名称:{};任务组名:{},cron执行表达式:{},执行时间:{}", sysJob.getJobName(), sysJob.getJobGroup(),
sysJob.getCronExpression(), new Date());
// 记录失败状态
sysJobLog.setJobMessage(PigQuartzEnum.JOB_LOG_STATUS_FAIL.getDescription());
sysJobLog.setJobLogStatus(PigQuartzEnum.JOB_LOG_STATUS_FAIL.getType());
sysJobLog.setExceptionInfo(StrUtil.sub(e.getMessage(), 0, 2000));
// 任务表信息更新
updateSysjob.setJobExecuteStatus(PigQuartzEnum.JOB_LOG_STATUS_FAIL.getType());
}
finally {
// 记录执行时间 立刻执行使用的是simpleTeigger
if (trigger instanceof CronTrigger) {
updateSysjob
.setStartTime(trigger.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
updateSysjob.setPreviousTime(
trigger.getPreviousFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
updateSysjob.setNextTime(
trigger.getNextFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
}
// 记录执行时长
endTime = System.currentTimeMillis();
sysJobLog.setExecuteTime(String.valueOf(endTime - startTime));
publisher.publishEvent(new SysJobLogEvent(sysJobLog));
sysJobService.updateById(updateSysjob);
}
| 70
| 975
| 1,045
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/account-service/src/main/java/com/piggymetrics/account/service/AccountServiceImpl.java
|
AccountServiceImpl
|
saveChanges
|
class AccountServiceImpl implements AccountService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private StatisticsServiceClient statisticsClient;
@Autowired
private AuthServiceClient authClient;
@Autowired
private AccountRepository repository;
/**
* {@inheritDoc}
*/
@Override
public Account findByName(String accountName) {
Assert.hasLength(accountName);
return repository.findByName(accountName);
}
/**
* {@inheritDoc}
*/
@Override
public Account create(User user) {
Account existing = repository.findByName(user.getUsername());
Assert.isNull(existing, "account already exists: " + user.getUsername());
authClient.createUser(user);
Saving saving = new Saving();
saving.setAmount(new BigDecimal(0));
saving.setCurrency(Currency.getDefault());
saving.setInterest(new BigDecimal(0));
saving.setDeposit(false);
saving.setCapitalization(false);
Account account = new Account();
account.setName(user.getUsername());
account.setLastSeen(new Date());
account.setSaving(saving);
repository.save(account);
log.info("new account has been created: " + account.getName());
return account;
}
/**
* {@inheritDoc}
*/
@Override
public void saveChanges(String name, Account update) {<FILL_FUNCTION_BODY>}
}
|
Account account = repository.findByName(name);
Assert.notNull(account, "can't find account with name " + name);
account.setIncomes(update.getIncomes());
account.setExpenses(update.getExpenses());
account.setSaving(update.getSaving());
account.setNote(update.getNote());
account.setLastSeen(new Date());
repository.save(account);
log.debug("account {} changes has been saved", name);
statisticsClient.updateStatistics(name, account);
| 413
| 154
| 567
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/account-service/src/main/java/com/piggymetrics/account/service/security/CustomUserInfoTokenServices.java
|
CustomUserInfoTokenServices
|
extractAuthentication
|
class CustomUserInfoTokenServices implements ResourceServerTokenServices {
protected final Log logger = LogFactory.getLog(getClass());
private static final String[] PRINCIPAL_KEYS = new String[] { "user", "username",
"userid", "user_id", "login", "id", "name" };
private final String userInfoEndpointUrl;
private final String clientId;
private OAuth2RestOperations restTemplate;
private String tokenType = DefaultOAuth2AccessToken.BEARER_TYPE;
private AuthoritiesExtractor authoritiesExtractor = new FixedAuthoritiesExtractor();
public CustomUserInfoTokenServices(String userInfoEndpointUrl, String clientId) {
this.userInfoEndpointUrl = userInfoEndpointUrl;
this.clientId = clientId;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public void setRestTemplate(OAuth2RestOperations restTemplate) {
this.restTemplate = restTemplate;
}
public void setAuthoritiesExtractor(AuthoritiesExtractor authoritiesExtractor) {
this.authoritiesExtractor = authoritiesExtractor;
}
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException {
Map<String, Object> map = getMap(this.userInfoEndpointUrl, accessToken);
if (map.containsKey("error")) {
this.logger.debug("userinfo returned error: " + map.get("error"));
throw new InvalidTokenException(accessToken);
}
return extractAuthentication(map);
}
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {<FILL_FUNCTION_BODY>}
private Object getPrincipal(Map<String, Object> map) {
for (String key : PRINCIPAL_KEYS) {
if (map.containsKey(key)) {
return map.get(key);
}
}
return "unknown";
}
@SuppressWarnings({ "unchecked" })
private OAuth2Request getRequest(Map<String, Object> map) {
Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request");
String clientId = (String) request.get("clientId");
Set<String> scope = new LinkedHashSet<>(request.containsKey("scope") ?
(Collection<String>) request.get("scope") : Collections.<String>emptySet());
return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope),
null, null, null, null);
}
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
throw new UnsupportedOperationException("Not supported: read access token");
}
@SuppressWarnings({ "unchecked" })
private Map<String, Object> getMap(String path, String accessToken) {
this.logger.debug("Getting user info from: " + path);
try {
OAuth2RestOperations restTemplate = this.restTemplate;
if (restTemplate == null) {
BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
resource.setClientId(this.clientId);
restTemplate = new OAuth2RestTemplate(resource);
}
OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext()
.getAccessToken();
if (existingToken == null || !accessToken.equals(existingToken.getValue())) {
DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(
accessToken);
token.setTokenType(this.tokenType);
restTemplate.getOAuth2ClientContext().setAccessToken(token);
}
return restTemplate.getForEntity(path, Map.class).getBody();
}
catch (Exception ex) {
this.logger.info("Could not fetch user details: " + ex.getClass() + ", "
+ ex.getMessage());
return Collections.<String, Object>singletonMap("error",
"Could not fetch user details");
}
}
}
|
Object principal = getPrincipal(map);
OAuth2Request request = getRequest(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
| 1,040
| 110
| 1,150
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/auth-service/src/main/java/com/piggymetrics/auth/config/OAuth2AuthorizationConfig.java
|
OAuth2AuthorizationConfig
|
configure
|
class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
private TokenStore tokenStore = new InMemoryTokenStore();
private final String NOOP_PASSWORD_ENCODE = "{noop}";
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private MongoUserDetailsService userDetailsService;
@Autowired
private Environment env;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
}
|
// TODO persist clients details
// @formatter:off
clients.inMemory()
.withClient("browser")
.authorizedGrantTypes("refresh_token", "password")
.scopes("ui")
.and()
.withClient("account-service")
.secret(env.getProperty("ACCOUNT_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("statistics-service")
.secret(env.getProperty("STATISTICS_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("notification-service")
.secret(env.getProperty("NOTIFICATION_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server");
// @formatter:on
| 286
| 258
| 544
|
<methods>public void <init>() ,public void configure(org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer) throws java.lang.Exception,public void configure(org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer) throws java.lang.Exception,public void configure(org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer) throws java.lang.Exception<variables>
|
sqshq_piggymetrics
|
piggymetrics/auth-service/src/main/java/com/piggymetrics/auth/service/UserServiceImpl.java
|
UserServiceImpl
|
create
|
class UserServiceImpl implements UserService {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
@Autowired
private UserRepository repository;
@Override
public void create(User user) {<FILL_FUNCTION_BODY>}
}
|
Optional<User> existing = repository.findById(user.getUsername());
existing.ifPresent(it-> {throw new IllegalArgumentException("user already exists: " + it.getUsername());});
String hash = encoder.encode(user.getPassword());
user.setPassword(hash);
repository.save(user);
log.info("new user has been created: {}", user.getUsername());
| 85
| 112
| 197
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/notification-service/src/main/java/com/piggymetrics/notification/domain/Recipient.java
|
Recipient
|
toString
|
class Recipient {
@Id
private String accountName;
@NotNull
@Email
private String email;
@Valid
private Map<NotificationType, NotificationSettings> scheduledNotifications;
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Map<NotificationType, NotificationSettings> getScheduledNotifications() {
return scheduledNotifications;
}
public void setScheduledNotifications(Map<NotificationType, NotificationSettings> scheduledNotifications) {
this.scheduledNotifications = scheduledNotifications;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Recipient{" +
"accountName='" + accountName + '\'' +
", email='" + email + '\'' +
'}';
| 217
| 44
| 261
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/notification-service/src/main/java/com/piggymetrics/notification/service/EmailServiceImpl.java
|
EmailServiceImpl
|
send
|
class EmailServiceImpl implements EmailService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private JavaMailSender mailSender;
@Autowired
private Environment env;
@Override
public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException {<FILL_FUNCTION_BODY>}
}
|
final String subject = env.getProperty(type.getSubject());
final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName());
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(recipient.getEmail());
helper.setSubject(subject);
helper.setText(text);
if (StringUtils.hasLength(attachment)) {
helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes()));
}
mailSender.send(message);
log.info("{} email notification has been send to {}", type, recipient.getEmail());
| 96
| 205
| 301
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/notification-service/src/main/java/com/piggymetrics/notification/service/NotificationServiceImpl.java
|
NotificationServiceImpl
|
sendRemindNotifications
|
class NotificationServiceImpl implements NotificationService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private AccountServiceClient client;
@Autowired
private RecipientService recipientService;
@Autowired
private EmailService emailService;
@Override
@Scheduled(cron = "${backup.cron}")
public void sendBackupNotifications() {
final NotificationType type = NotificationType.BACKUP;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for backup notification", recipients.size());
recipients.forEach(recipient -> CompletableFuture.runAsync(() -> {
try {
String attachment = client.getAccount(recipient.getAccountName());
emailService.send(type, recipient, attachment);
recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during backup notification for {}", recipient, t);
}
}));
}
@Override
@Scheduled(cron = "${remind.cron}")
public void sendRemindNotifications() {<FILL_FUNCTION_BODY>}
}
|
final NotificationType type = NotificationType.REMIND;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for remind notification", recipients.size());
recipients.forEach(recipient -> CompletableFuture.runAsync(() -> {
try {
emailService.send(type, recipient, null);
recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during remind notification for {}", recipient, t);
}
}));
| 324
| 162
| 486
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/notification-service/src/main/java/com/piggymetrics/notification/service/RecipientServiceImpl.java
|
RecipientServiceImpl
|
findReadyToNotify
|
class RecipientServiceImpl implements RecipientService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private RecipientRepository repository;
@Override
public Recipient findByAccountName(String accountName) {
Assert.hasLength(accountName);
return repository.findByAccountName(accountName);
}
/**
* {@inheritDoc}
*/
@Override
public Recipient save(String accountName, Recipient recipient) {
recipient.setAccountName(accountName);
recipient.getScheduledNotifications().values()
.forEach(settings -> {
if (settings.getLastNotified() == null) {
settings.setLastNotified(new Date());
}
});
repository.save(recipient);
log.info("recipient {} settings has been updated", recipient);
return recipient;
}
/**
* {@inheritDoc}
*/
@Override
public List<Recipient> findReadyToNotify(NotificationType type) {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*/
@Override
public void markNotified(NotificationType type, Recipient recipient) {
recipient.getScheduledNotifications().get(type).setLastNotified(new Date());
repository.save(recipient);
}
}
|
switch (type) {
case BACKUP:
return repository.findReadyForBackup();
case REMIND:
return repository.findReadyForRemind();
default:
throw new IllegalArgumentException();
}
| 355
| 62
| 417
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/client/ExchangeRatesClientFallback.java
|
ExchangeRatesClientFallback
|
getRates
|
class ExchangeRatesClientFallback implements ExchangeRatesClient {
@Override
public ExchangeRatesContainer getRates(Currency base) {<FILL_FUNCTION_BODY>}
}
|
ExchangeRatesContainer container = new ExchangeRatesContainer();
container.setBase(Currency.getBase());
container.setRates(Collections.emptyMap());
return container;
| 50
| 48
| 98
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/domain/ExchangeRatesContainer.java
|
ExchangeRatesContainer
|
toString
|
class ExchangeRatesContainer {
private LocalDate date = LocalDate.now();
private Currency base;
private Map<String, BigDecimal> rates;
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Currency getBase() {
return base;
}
public void setBase(Currency base) {
this.base = base;
}
public Map<String, BigDecimal> getRates() {
return rates;
}
public void setRates(Map<String, BigDecimal> rates) {
this.rates = rates;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "RateList{" +
"date=" + date +
", base=" + base +
", rates=" + rates +
'}';
| 192
| 45
| 237
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/domain/timeseries/DataPointId.java
|
DataPointId
|
toString
|
class DataPointId implements Serializable {
private static final long serialVersionUID = 1L;
private String account;
private Date date;
public DataPointId(String account, Date date) {
this.account = account;
this.date = date;
}
public String getAccount() {
return account;
}
public Date getDate() {
return date;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "DataPointId{" +
"account='" + account + '\'' +
", date=" + date +
'}';
| 121
| 39
| 160
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/domain/timeseries/ItemMetric.java
|
ItemMetric
|
equals
|
class ItemMetric {
private String title;
private BigDecimal amount;
public ItemMetric(String title, BigDecimal amount) {
this.title = title;
this.amount = amount;
}
public String getTitle() {
return title;
}
public BigDecimal getAmount() {
return amount;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return title.hashCode();
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ItemMetric that = (ItemMetric) o;
return title.equalsIgnoreCase(that.title);
| 134
| 66
| 200
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/repository/converter/DataPointIdReaderConverter.java
|
DataPointIdReaderConverter
|
convert
|
class DataPointIdReaderConverter implements Converter<DBObject, DataPointId> {
@Override
public DataPointId convert(DBObject object) {<FILL_FUNCTION_BODY>}
}
|
Date date = (Date) object.get("date");
String account = (String) object.get("account");
return new DataPointId(account, date);
| 49
| 46
| 95
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/repository/converter/DataPointIdWriterConverter.java
|
DataPointIdWriterConverter
|
convert
|
class DataPointIdWriterConverter implements Converter<DataPointId, DBObject> {
private static final int FIELDS = 2;
@Override
public DBObject convert(DataPointId id) {<FILL_FUNCTION_BODY>}
}
|
DBObject object = new BasicDBObject(FIELDS);
object.put("date", id.getDate());
object.put("account", id.getAccount());
return object;
| 61
| 55
| 116
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/service/ExchangeRatesServiceImpl.java
|
ExchangeRatesServiceImpl
|
getCurrentRates
|
class ExchangeRatesServiceImpl implements ExchangeRatesService {
private static final Logger log = LoggerFactory.getLogger(ExchangeRatesServiceImpl.class);
private ExchangeRatesContainer container;
@Autowired
private ExchangeRatesClient client;
/**
* {@inheritDoc}
*/
@Override
public Map<Currency, BigDecimal> getCurrentRates() {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*/
@Override
public BigDecimal convert(Currency from, Currency to, BigDecimal amount) {
Assert.notNull(amount);
Map<Currency, BigDecimal> rates = getCurrentRates();
BigDecimal ratio = rates.get(to).divide(rates.get(from), 4, RoundingMode.HALF_UP);
return amount.multiply(ratio);
}
}
|
if (container == null || !container.getDate().equals(LocalDate.now())) {
container = client.getRates(Currency.getBase());
log.info("exchange rates has been updated: {}", container);
}
return ImmutableMap.of(
Currency.EUR, container.getRates().get(Currency.EUR.name()),
Currency.RUB, container.getRates().get(Currency.RUB.name()),
Currency.USD, BigDecimal.ONE
);
| 226
| 142
| 368
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/service/StatisticsServiceImpl.java
|
StatisticsServiceImpl
|
createStatisticMetrics
|
class StatisticsServiceImpl implements StatisticsService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private DataPointRepository repository;
@Autowired
private ExchangeRatesService ratesService;
/**
* {@inheritDoc}
*/
@Override
public List<DataPoint> findByAccountName(String accountName) {
Assert.hasLength(accountName);
return repository.findByIdAccount(accountName);
}
/**
* {@inheritDoc}
*/
@Override
public DataPoint save(String accountName, Account account) {
Instant instant = LocalDate.now().atStartOfDay()
.atZone(ZoneId.systemDefault()).toInstant();
DataPointId pointId = new DataPointId(accountName, Date.from(instant));
Set<ItemMetric> incomes = account.getIncomes().stream()
.map(this::createItemMetric)
.collect(Collectors.toSet());
Set<ItemMetric> expenses = account.getExpenses().stream()
.map(this::createItemMetric)
.collect(Collectors.toSet());
Map<StatisticMetric, BigDecimal> statistics = createStatisticMetrics(incomes, expenses, account.getSaving());
DataPoint dataPoint = new DataPoint();
dataPoint.setId(pointId);
dataPoint.setIncomes(incomes);
dataPoint.setExpenses(expenses);
dataPoint.setStatistics(statistics);
dataPoint.setRates(ratesService.getCurrentRates());
log.debug("new datapoint has been created: {}", pointId);
return repository.save(dataPoint);
}
private Map<StatisticMetric, BigDecimal> createStatisticMetrics(Set<ItemMetric> incomes, Set<ItemMetric> expenses, Saving saving) {<FILL_FUNCTION_BODY>}
/**
* Normalizes given item amount to {@link Currency#getBase()} currency with
* {@link TimePeriod#getBase()} time period
*/
private ItemMetric createItemMetric(Item item) {
BigDecimal amount = ratesService
.convert(item.getCurrency(), Currency.getBase(), item.getAmount())
.divide(item.getPeriod().getBaseRatio(), 4, RoundingMode.HALF_UP);
return new ItemMetric(item.getTitle(), amount);
}
}
|
BigDecimal savingAmount = ratesService.convert(saving.getCurrency(), Currency.getBase(), saving.getAmount());
BigDecimal expensesAmount = expenses.stream()
.map(ItemMetric::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal incomesAmount = incomes.stream()
.map(ItemMetric::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return ImmutableMap.of(
StatisticMetric.EXPENSES_AMOUNT, expensesAmount,
StatisticMetric.INCOMES_AMOUNT, incomesAmount,
StatisticMetric.SAVING_AMOUNT, savingAmount
);
| 629
| 202
| 831
|
<no_super_class>
|
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/service/security/CustomUserInfoTokenServices.java
|
CustomUserInfoTokenServices
|
getRequest
|
class CustomUserInfoTokenServices implements ResourceServerTokenServices {
protected final Log logger = LogFactory.getLog(getClass());
private static final String[] PRINCIPAL_KEYS = new String[] { "user", "username",
"userid", "user_id", "login", "id", "name" };
private final String userInfoEndpointUrl;
private final String clientId;
private OAuth2RestOperations restTemplate;
private String tokenType = DefaultOAuth2AccessToken.BEARER_TYPE;
private AuthoritiesExtractor authoritiesExtractor = new FixedAuthoritiesExtractor();
public CustomUserInfoTokenServices(String userInfoEndpointUrl, String clientId) {
this.userInfoEndpointUrl = userInfoEndpointUrl;
this.clientId = clientId;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public void setRestTemplate(OAuth2RestOperations restTemplate) {
this.restTemplate = restTemplate;
}
public void setAuthoritiesExtractor(AuthoritiesExtractor authoritiesExtractor) {
this.authoritiesExtractor = authoritiesExtractor;
}
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException {
Map<String, Object> map = getMap(this.userInfoEndpointUrl, accessToken);
if (map.containsKey("error")) {
this.logger.debug("userinfo returned error: " + map.get("error"));
throw new InvalidTokenException(accessToken);
}
return extractAuthentication(map);
}
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
Object principal = getPrincipal(map);
OAuth2Request request = getRequest(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
private Object getPrincipal(Map<String, Object> map) {
for (String key : PRINCIPAL_KEYS) {
if (map.containsKey(key)) {
return map.get(key);
}
}
return "unknown";
}
@SuppressWarnings({ "unchecked" })
private OAuth2Request getRequest(Map<String, Object> map) {<FILL_FUNCTION_BODY>}
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
throw new UnsupportedOperationException("Not supported: read access token");
}
@SuppressWarnings({ "unchecked" })
private Map<String, Object> getMap(String path, String accessToken) {
this.logger.debug("Getting user info from: " + path);
try {
OAuth2RestOperations restTemplate = this.restTemplate;
if (restTemplate == null) {
BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
resource.setClientId(this.clientId);
restTemplate = new OAuth2RestTemplate(resource);
}
OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext()
.getAccessToken();
if (existingToken == null || !accessToken.equals(existingToken.getValue())) {
DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(
accessToken);
token.setTokenType(this.tokenType);
restTemplate.getOAuth2ClientContext().setAccessToken(token);
}
return restTemplate.getForEntity(path, Map.class).getBody();
}
catch (Exception ex) {
this.logger.info("Could not fetch user details: " + ex.getClass() + ", "
+ ex.getMessage());
return Collections.<String, Object>singletonMap("error",
"Could not fetch user details");
}
}
}
|
Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request");
String clientId = (String) request.get("clientId");
Set<String> scope = new LinkedHashSet<>(request.containsKey("scope") ?
(Collection<String>) request.get("scope") : Collections.<String>emptySet());
return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope),
null, null, null, null);
| 1,018
| 132
| 1,150
|
<no_super_class>
|
apilayer_restcountries
|
restcountries/src/main/java/eu/fayder/restcountries/rest/CountryServiceBase.java
|
CountryServiceBase
|
getBySubregion
|
class CountryServiceBase {
private static final Logger LOG = Logger.getLogger(CountryServiceBase.class);
protected <T extends BaseCountry> T getByAlpha(String alpha, List<T> countries) {
int alphaLength = alpha.length();
for (T country : countries) {
if (alphaLength == 2) {
if (country.getAlpha2Code().toLowerCase().equals(alpha.toLowerCase())) {
return country;
}
} else if (alphaLength == 3) {
if (country.getAlpha3Code().toLowerCase().equals(alpha.toLowerCase())) {
return country;
}
}
}
return null;
}
protected List<? extends BaseCountry> getByCodeList(String codeList, List<? extends BaseCountry> countries) {
List<BaseCountry> result = new ArrayList<>();
if(codeList == null) return result;
List<String> codes = Arrays.asList(codeList.split(ICountryRestSymbols.SEMICOLON));
for(String code : codes) {
BaseCountry country = getByAlpha(code, countries);
if(!result.contains(country))
result.add(country);
}
return result;
}
protected List<? extends BaseCountry> getByName(String name, boolean fullText, List<? extends BaseCountry> countries) {
if(fullText) {
return fulltextSearch(name, countries);
} else {
return substringSearch(name, countries);
}
}
protected List<? extends BaseCountry> getByCallingCode(String callingCode, List<? extends BaseCountry> countries) {
List<BaseCountry> result = new ArrayList<>();
for(BaseCountry country : countries) {
for(String c : country.getCallingCodes()) {
if(c.equals(callingCode))
result.add(country);
}
}
return result;
}
protected List<? extends BaseCountry> getByCapital(String capital, List<? extends BaseCountry> countries) {
List<BaseCountry> result = new ArrayList<>();
for(BaseCountry country : countries) {
if(normalize(country.getCapital().toLowerCase()).contains(normalize(capital.toLowerCase()))) {
result.add(country);
}
}
return result;
}
protected List<? extends BaseCountry> getByRegion(String region, List<? extends BaseCountry> countries) {
List<BaseCountry> result = new ArrayList<>();
for(BaseCountry country : countries) {
if(country.getRegion().toLowerCase().equals(region.toLowerCase())) {
result.add(country);
}
}
return result;
}
protected List<? extends BaseCountry> getBySubregion(String subregion, List<? extends BaseCountry> countries) {<FILL_FUNCTION_BODY>}
private List<? extends BaseCountry> fulltextSearch(String name, List<? extends BaseCountry> countries) {
// Using 2 different 'for' loops to give priority to 'name' matches over alternative spellings
List<BaseCountry> result = new ArrayList<>();
for (BaseCountry country : countries) {
if (normalize(country.getName().toLowerCase()).equals(normalize(name.toLowerCase()))) {
result.add(country);
}
}
for (BaseCountry country : countries) {
for (String alternative : country.getAltSpellings()) {
if (normalize(alternative.toLowerCase()).equals(normalize(name.toLowerCase()))
&& !result.contains(country)) {
result.add(country);
}
}
}
return result;
}
private List<? extends BaseCountry> substringSearch(String name, List<? extends BaseCountry> countries) {
// Using 2 different 'for' loops to give priority to 'name' matches over alternative spellings
List<BaseCountry> result = new ArrayList<>();
for(BaseCountry country : countries) {
if(normalize(country.getName().toLowerCase()).contains(normalize(name.toLowerCase()))) {
result.add(country);
}
}
for(BaseCountry country : countries) {
for (String alternative : country.getAltSpellings()) {
if( normalize(alternative.toLowerCase()).contains(normalize(name.toLowerCase()))
&& !result.contains(country) ) {
result.add(country);
}
}
}
return result;
}
protected String normalize(String string) {
return Normalizer.normalize(string, Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
protected List<? extends BaseCountry> loadJson(String filename, Class<? extends BaseCountry> clazz) {
LOG.debug("Loading JSON " + filename);
List<BaseCountry> countries = new ArrayList<>();
InputStream is = CountryServiceBase.class.getClassLoader().getResourceAsStream(filename);
Gson gson = new Gson();
JsonReader reader;
try {
reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
reader.beginArray();
while(reader.hasNext()) {
BaseCountry country = gson.fromJson(reader, clazz);
countries.add(country);
}
} catch (Exception e) {
LOG.error("Could not load JSON " + filename);
}
return countries;
}
}
|
List<BaseCountry> result = new ArrayList<>();
for(BaseCountry country : countries) {
if(country.getSubregion().toLowerCase().equals(subregion.toLowerCase())) {
result.add(country);
}
}
return result;
| 1,406
| 70
| 1,476
|
<no_super_class>
|
apilayer_restcountries
|
restcountries/src/main/java/eu/fayder/restcountries/servlet/CORSFilter.java
|
CORSFilter
|
doFilter
|
class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
}
}
|
((HttpServletResponse)response).addHeader("Access-Control-Allow-Origin", "*");
((HttpServletResponse)response).addHeader("Access-Control-Allow-Methods", "GET");
((HttpServletResponse)response).addHeader("Access-Control-Allow-Headers", "Accept, X-Requested-With");
((HttpServletResponse)response).addHeader("Cache-Control","public, max-age=86400");
chain.doFilter(request, response);
| 94
| 118
| 212
|
<no_super_class>
|
apilayer_restcountries
|
restcountries/src/main/java/eu/fayder/restcountries/v1/rest/CountryRest.java
|
CountryRest
|
getByName
|
class CountryRest {
private static final Logger LOG = Logger.getLogger(CountryRest.class);
@GET
@Path("all")
public Object getAllCountries() {
return this.getCountries();
}
@GET
public Object getCountries() {
LOG.info("Getting all");
return CountryService.getInstance().getAll();
}
@GET
@Path("alpha/{alphacode}")
public Object getByAlpha(@PathParam("alphacode") String alpha) {
LOG.info("Getting by alpha " + alpha);
if (isEmpty(alpha) || alpha.length() < 2 || alpha.length() > 3) {
return getResponse(Status.BAD_REQUEST);
}
Country country = CountryService.getInstance().getByAlpha(alpha);
if (country != null) {
return country;
}
return getResponse(Status.NOT_FOUND);
}
@GET
@Path("alpha/")
public Object getByAlphaList(@QueryParam("codes") String codes) {
LOG.info("Getting by list " + codes);
if (isEmpty(codes) || codes.length() < 2 || (codes.length() > 3 && !codes.contains(";"))) {
return getResponse(Status.BAD_REQUEST);
}
try {
List<Country> countries = CountryService.getInstance().getByCodeList(codes);
if (!countries.isEmpty()) {
return countries;
}
return getResponse(Status.NOT_FOUND);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return getResponse(Status.INTERNAL_SERVER_ERROR);
}
}
@GET
@Path("currency/{currency}")
public Object getByCurrency(@PathParam("currency") String currency) {
LOG.info("Getting by currency " + currency);
if (isEmpty(currency) || currency.length() != 3) {
return getResponse(Status.BAD_REQUEST);
}
try {
List<Country> countries = CountryService.getInstance().getByCurrency(currency);
if (!countries.isEmpty()) {
return countries;
}
return getResponse(Status.NOT_FOUND);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return getResponse(Status.INTERNAL_SERVER_ERROR);
}
}
@GET
@Path("name/{name}")
public Object getByName(@PathParam("name") String name, @QueryParam("fullText") boolean fullText) {<FILL_FUNCTION_BODY>}
@GET
@Path("callingcode/{callingcode}")
public Object getByCallingCode(@PathParam("callingcode") String callingcode) {
LOG.info("Getting by calling code " + callingcode);
try {
List<Country> countries = CountryService.getInstance().getByCallingCode(callingcode);
if (!countries.isEmpty()) {
return countries;
}
return getResponse(Status.NOT_FOUND);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return getResponse(Status.INTERNAL_SERVER_ERROR);
}
}
@GET
@Path("capital/{capital}")
public Object getByCapital(@PathParam("capital") String capital) {
LOG.info("Getting by capital " + capital);
try {
List<Country> countries = CountryService.getInstance().getByCapital(capital);
if (!countries.isEmpty()) {
return countries;
}
return getResponse(Status.NOT_FOUND);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return getResponse(Status.INTERNAL_SERVER_ERROR);
}
}
@GET
@Path("region/{region}")
public Object getByRegion(@PathParam("region") String region) {
LOG.info("Getting by region " + region);
try {
List<Country> countries = CountryService.getInstance().getByRegion(region);
if (!countries.isEmpty()) {
return countries;
}
return getResponse(Status.NOT_FOUND);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return getResponse(Status.INTERNAL_SERVER_ERROR);
}
}
@GET
@Path("subregion/{subregion}")
public Object getBySubregion(@PathParam("subregion") String subregion) {
LOG.info("Getting by region " + subregion);
try {
List<Country> countries = CountryService.getInstance().getBySubregion(subregion);
if (!countries.isEmpty()) {
return countries;
}
return getResponse(Status.NOT_FOUND);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return getResponse(Status.INTERNAL_SERVER_ERROR);
}
}
@GET
@Path("lang/{lang}")
public Object getByLanguage(@PathParam("lang") String language) {
LOG.info("Getting by language " + language);
try {
List<Country> countries = CountryService.getInstance().getByLanguage(language);
if (!countries.isEmpty()) {
return countries;
}
return getResponse(Status.NOT_FOUND);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return getResponse(Status.INTERNAL_SERVER_ERROR);
}
}
@POST
public Object doPOST() {
LOG.info("Handling POST Request");
return getResponse(Status.METHOD_NOT_ALLOWED);
}
private Response getResponse(Status status) {
Gson gson = new Gson();
return Response
.status(status)
.entity(gson.toJson(new ResponseEntity(status.getStatusCode(),
status.getReasonPhrase()))).build();
}
private boolean isEmpty(String value) {
return value == null || value.isEmpty();
}
}
|
LOG.info("Getting by name " + name);
try {
List<Country> countries = CountryService.getInstance().getByName(name, fullText);
if (!countries.isEmpty()) {
return countries;
}
return getResponse(Status.NOT_FOUND);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return getResponse(Status.INTERNAL_SERVER_ERROR);
}
| 1,557
| 114
| 1,671
|
<no_super_class>
|
apilayer_restcountries
|
restcountries/src/main/java/eu/fayder/restcountries/v1/rest/CountryService.java
|
InstanceHolder
|
getByCurrency
|
class InstanceHolder {
private static final CountryService INSTANCE = new CountryService();
}
public static CountryService getInstance() {
return InstanceHolder.INSTANCE;
}
public List<Country> getAll() {
return countries;
}
public Country getByAlpha(String alpha) {
return super.getByAlpha(alpha, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByCodeList(String codeList) {
return (List<Country>) super.getByCodeList(codeList, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByName(String name, boolean isFullText) {
return (List<Country>) super.getByName(name, isFullText, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByCallingCode(String callingcode) {
return (List<Country>) super.getByCallingCode(callingcode, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByCapital(String capital) {
return (List<Country>) super.getByCapital(capital, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByRegion(String region) {
return (List<Country>) super.getByRegion(region, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getBySubregion(String subregion) {
return (List<Country>) super.getBySubregion(subregion, countries);
}
public List<Country> getByCurrency(String currency) {<FILL_FUNCTION_BODY>
|
List<Country> result = new ArrayList<>();
for (Country country : countries) {
for (String curr : country.getCurrencies()) {
if (curr.toLowerCase().equals(currency.toLowerCase())) {
result.add(country);
}
}
}
return result;
| 455
| 83
| 538
|
<methods>public non-sealed void <init>() <variables>private static final Logger LOG
|
apilayer_restcountries
|
restcountries/src/main/java/eu/fayder/restcountries/v2/domain/RegionalBloc.java
|
RegionalBloc
|
getOtherAcronyms
|
class RegionalBloc {
private String acronym;
private String name;
private List<String> otherAcronyms;
private List<String> otherNames;
public String getAcronym() {
return acronym;
}
public String getName() {
return name;
}
public List<String> getOtherAcronyms() {<FILL_FUNCTION_BODY>}
public List<String> getOtherNames() {
if (otherNames == null) {
otherNames = new ArrayList<>();
}
return otherNames;
}
}
|
if (otherAcronyms == null) {
otherAcronyms = new ArrayList<>();
}
return otherAcronyms;
| 156
| 40
| 196
|
<no_super_class>
|
apilayer_restcountries
|
restcountries/src/main/java/eu/fayder/restcountries/v2/rest/CountryService.java
|
InstanceHolder
|
getByDemonym
|
class InstanceHolder {
private static final CountryService INSTANCE = new CountryService();
}
public static CountryService getInstance() {
return InstanceHolder.INSTANCE;
}
public List<Country> getAll() {
return countries;
}
public Country getByAlpha(String alpha) {
return super.getByAlpha(alpha, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByCodeList(String codeList) {
return (List<Country>) super.getByCodeList(codeList, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByName(String name, boolean isFullText) {
return (List<Country>) super.getByName(name, isFullText, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByCallingCode(String callingcode) {
return (List<Country>) super.getByCallingCode(callingcode, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByCapital(String capital) {
return (List<Country>) super.getByCapital(capital, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getByRegion(String region) {
return (List<Country>) super.getByRegion(region, countries);
}
@SuppressWarnings("unchecked")
public List<Country> getBySubRegion(String subregion) {
return (List<Country>) super.getBySubregion(subregion, countries);
}
public List<Country> getByCurrency(String currency) {
List<Country> result = new ArrayList<>();
for (Country country : countries) {
for (Currency curr : country.getCurrencies()) {
if (curr.getCode() != null && currency.toLowerCase().equals(curr.getCode().toLowerCase())) {
result.add(country);
}
}
}
return result;
}
public List<Country> getByLanguage(String language) {
List<Country> result = new ArrayList<>();
if (language.length() == 2) {
for (Country country : countries) {
for (Language lang : country.getLanguages()) {
if (language.toLowerCase().equals(lang.getIso639_1())) {
result.add(country);
}
}
}
} else if (language.length() == 3) {
for (Country country : countries) {
for (Language lang : country.getLanguages()) {
if (language.toLowerCase().equals(lang.getIso639_2())) {
result.add(country);
}
}
}
}
return result;
}
public List<Country> getByDemonym(String demonym) {<FILL_FUNCTION_BODY>
|
List<Country> result = new ArrayList<>();
for (Country country : countries) {
if (country.getDemonym().toLowerCase().equals(normalize(demonym.toLowerCase()))) {
result.add(country);
}
}
return result;
| 764
| 72
| 836
|
<methods>public non-sealed void <init>() <variables>private static final Logger LOG
|
apilayer_restcountries
|
restcountries/src/main/java/eu/fayder/restcountries/v2/rest/StripeRest.java
|
StripeRest
|
contribute
|
class StripeRest {
private static final Logger LOG = Logger.getLogger(StripeRest.class);
@POST
public Object contribute(Contribution contribution) {<FILL_FUNCTION_BODY>}
private Response getResponse(Response.Status status) {
Gson gson = new Gson();
return Response
.status(status)
.entity(gson.toJson(new ResponseEntity(status.getStatusCode(),
status.getReasonPhrase()))).build();
}
}
|
LOG.debug("Contribution: " + contribution);
if (contribution == null || TextUtils.isBlank(contribution.getToken())) {
return getResponse(Response.Status.BAD_REQUEST);
}
Stripe.apiKey = "";
Map<String, Object> params = new HashMap<>();
params.put("amount", contribution.getAmount());
params.put("currency", "eur");
params.put("description", "REST Countries");
params.put("source", contribution.getToken());
try {
Charge.create(params);
} catch (AuthenticationException | InvalidRequestException | CardException | APIConnectionException | APIException e) {
LOG.error(e.getMessage(), e);
return getResponse(Response.Status.BAD_REQUEST);
}
return getResponse(Response.Status.ACCEPTED);
| 132
| 218
| 350
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/AlbumRipper.java
|
AlbumRipper
|
addURLToDownload
|
class AlbumRipper extends AbstractRipper {
private Map<URL, File> itemsPending = Collections.synchronizedMap(new HashMap<URL, File>());
private Map<URL, File> itemsCompleted = Collections.synchronizedMap(new HashMap<URL, File>());
private Map<URL, String> itemsErrored = Collections.synchronizedMap(new HashMap<URL, String>());
protected AlbumRipper(URL url) throws IOException {
super(url);
}
public abstract boolean canRip(URL url);
public abstract URL sanitizeURL(URL url) throws MalformedURLException;
public abstract void rip() throws IOException;
public abstract String getHost();
public abstract String getGID(URL url) throws MalformedURLException;
protected boolean allowDuplicates() {
return false;
}
@Override
/**
* Returns total amount of files attempted.
*/
public int getCount() {
return itemsCompleted.size() + itemsErrored.size();
}
@Override
/**
* Queues multiple URLs of single images to download from a single Album URL
*/
public boolean addURLToDownload(URL url, File saveAs, String referrer, Map<String,String> cookies, Boolean getFileExtFromMIME) {<FILL_FUNCTION_BODY>}
@Override
public boolean addURLToDownload(URL url, File saveAs) {
return addURLToDownload(url, saveAs, null, null, false);
}
/**
* Queues image to be downloaded and saved.
* Uses filename from URL to decide filename.
* @param url
* URL to download
* @return
* True on success
*/
protected boolean addURLToDownload(URL url) {
// Use empty prefix and empty subdirectory
return addURLToDownload(url, "", "");
}
@Override
/**
* Cleans up & tells user about successful download
*/
public void downloadCompleted(URL url, File saveAs) {
if (observer == null) {
return;
}
try {
String path = Utils.removeCWD(saveAs);
RipStatusMessage msg = new RipStatusMessage(STATUS.DOWNLOAD_COMPLETE, path);
itemsPending.remove(url);
itemsCompleted.put(url, saveAs);
observer.update(this, msg);
checkIfComplete();
} catch (Exception e) {
LOGGER.error("Exception while updating observer: ", e);
}
}
@Override
/**
* Cleans up & tells user about failed download.
*/
public void downloadErrored(URL url, String reason) {
if (observer == null) {
return;
}
itemsPending.remove(url);
itemsErrored.put(url, reason);
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_ERRORED, url + " : " + reason));
checkIfComplete();
}
@Override
/**
* Tells user that a single file in the album they wish to download has
* already been downloaded in the past.
*/
public void downloadExists(URL url, File file) {
if (observer == null) {
return;
}
itemsPending.remove(url);
itemsCompleted.put(url, file);
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " already saved as " + file.getAbsolutePath()));
checkIfComplete();
}
/**
* Notifies observers and updates state if all files have been ripped.
*/
@Override
protected void checkIfComplete() {
if (observer == null) {
return;
}
if (itemsPending.isEmpty()) {
super.checkIfComplete();
}
}
/**
* Sets directory to save all ripped files to.
* @param url
* URL to define how the working directory should be saved.
* @throws
* IOException
*/
@Override
public void setWorkingDir(URL url) throws IOException {
String path = Utils.getWorkingDirectory().getCanonicalPath();
if (!path.endsWith(File.separator)) {
path += File.separator;
}
String title;
if (Utils.getConfigBoolean("album_titles.save", true)) {
title = getAlbumTitle(this.url);
} else {
title = super.getAlbumTitle(this.url);
}
LOGGER.debug("Using album title '" + title + "'");
title = Utils.filesystemSafe(title);
path += title;
path = Utils.getOriginalDirectory(path) + File.separator; // check for case sensitive (unix only)
this.workingDir = new File(path);
if (!this.workingDir.exists()) {
LOGGER.info("[+] Creating directory: " + Utils.removeCWD(this.workingDir));
this.workingDir.mkdirs();
}
LOGGER.debug("Set working directory to: " + this.workingDir);
}
/**
* @return
* Integer between 0 and 100 defining the progress of the album rip.
*/
@Override
public int getCompletionPercentage() {
double total = itemsPending.size() + itemsErrored.size() + itemsCompleted.size();
return (int) (100 * ( (total - itemsPending.size()) / total));
}
/**
* @return
* Human-readable information on the status of the current rip.
*/
@Override
public String getStatusText() {
StringBuilder sb = new StringBuilder();
sb.append(getCompletionPercentage())
.append("% ")
.append("- Pending: " ).append(itemsPending.size())
.append(", Completed: ").append(itemsCompleted.size())
.append(", Errored: " ).append(itemsErrored.size());
return sb.toString();
}
}
|
// Only download one file if this is a test.
if (super.isThisATest() &&
(itemsPending.size() > 0 || itemsCompleted.size() > 0 || itemsErrored.size() > 0)) {
stop();
return false;
}
if (!allowDuplicates()
&& ( itemsPending.containsKey(url)
|| itemsCompleted.containsKey(url)
|| itemsErrored.containsKey(url) )) {
// Item is already downloaded/downloading, skip it.
LOGGER.info("[!] Skipping " + url + " -- already attempted: " + Utils.removeCWD(saveAs));
return false;
}
if (Utils.getConfigBoolean("urls_only.save", false)) {
// Output URL to file
String urlFile = this.workingDir + File.separator + "urls.txt";
try (FileWriter fw = new FileWriter(urlFile, true)) {
fw.write(url.toExternalForm());
fw.write(System.lineSeparator());
itemsCompleted.put(url, new File(urlFile));
} catch (IOException e) {
LOGGER.error("Error while writing to " + urlFile, e);
}
}
else {
itemsPending.put(url, saveAs);
DownloadFileThread dft = new DownloadFileThread(url, saveAs, this, getFileExtFromMIME);
if (referrer != null) {
dft.setReferrer(referrer);
}
if (cookies != null) {
dft.setCookies(cookies);
}
threadPool.addThread(dft);
}
return true;
| 1,571
| 442
| 2,013
|
<methods>public void <init>(java.net.URL) throws java.io.IOException,public abstract boolean addURLToDownload(java.net.URL, java.io.File) ,public abstract void downloadCompleted(java.net.URL, java.io.File) ,public abstract void downloadErrored(java.net.URL, java.lang.String) ,public abstract void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) throws java.net.MalformedURLException,public abstract int getCompletionPercentage() ,public static java.lang.String getFileName(java.net.URL, java.lang.String, java.lang.String) ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public static com.rarchives.ripme.ripper.AbstractRipper getRipper(java.net.URL) throws java.lang.Exception,public static List<Constructor<?>> getRipperConstructors(java.lang.String) throws java.lang.Exception,public abstract java.lang.String getStatusText() ,public java.net.URL getURL() ,public java.io.File getWorkingDir() ,public boolean hasASAPRipping() ,public boolean isStopped() ,public void markAsTest() ,public java.lang.String normalizeUrl(java.lang.String) ,public void retrievingSource(java.lang.String) ,public abstract void rip() throws java.io.IOException,public void run() ,public void sendUpdate(com.rarchives.ripme.ui.RipStatusMessage.STATUS, java.lang.Object) ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setObserver(com.rarchives.ripme.ui.RipStatusHandler) ,public abstract void setWorkingDir(java.net.URL) throws java.io.IOException,public void setup() throws java.io.IOException,public void stop() <variables>protected static final Logger LOGGER,private final java.lang.String URLHistoryFile,public static final java.lang.String USER_AGENT,public int alreadyDownloadedUrls,private boolean completed,com.rarchives.ripme.ui.RipStatusHandler observer,private boolean shouldStop,private static boolean thisIsATest,com.rarchives.ripme.ripper.DownloadThreadPool threadPool,protected java.net.URL url,protected java.io.File workingDir
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/DownloadThreadPool.java
|
DownloadThreadPool
|
initialize
|
class DownloadThreadPool {
private static final Logger logger = Logger.getLogger(DownloadThreadPool.class);
private ThreadPoolExecutor threadPool = null;
public DownloadThreadPool() {
initialize("Main");
}
public DownloadThreadPool(String threadPoolName) {
initialize(threadPoolName);
}
/**
* Initializes the threadpool.
* @param threadPoolName Name of the threadpool.
*/
private void initialize(String threadPoolName) {<FILL_FUNCTION_BODY>}
/**
* For adding threads to execution pool.
* @param t
* Thread to be added.
*/
public void addThread(Thread t) {
threadPool.execute(t);
}
/**
* Tries to shutdown threadpool.
*/
public void waitForThreads() {
threadPool.shutdown();
try {
threadPool.awaitTermination(3600, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error("[!] Interrupted while waiting for threads to finish: ", e);
}
}
}
|
int threads = Utils.getConfigInteger("threads.size", 10);
logger.debug("Initializing " + threadPoolName + " thread pool with " + threads + " threads");
threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(threads);
| 292
| 70
| 362
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/DownloadVideoThread.java
|
DownloadVideoThread
|
run
|
class DownloadVideoThread extends Thread {
private static final Logger logger = Logger.getLogger(DownloadVideoThread.class);
private URL url;
private File saveAs;
private String prettySaveAs;
private AbstractRipper observer;
private int retries;
public DownloadVideoThread(URL url, File saveAs, AbstractRipper observer) {
super();
this.url = url;
this.saveAs = saveAs;
this.prettySaveAs = Utils.removeCWD(saveAs);
this.observer = observer;
this.retries = Utils.getConfigInteger("download.retries", 1);
}
/**
* Attempts to download the file. Retries as needed.
* Notifies observers upon completion/error/warn.
*/
public void run() {<FILL_FUNCTION_BODY>}
/**
* @param url
* Target URL
* @return
* Returns connection length
*/
private int getTotalBytes(URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Referer", this.url.toExternalForm()); // Sic
conn.setRequestProperty("User-agent", AbstractRipper.USER_AGENT);
return conn.getContentLength();
}
}
|
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
if (saveAs.exists()) {
if (Utils.getConfigBoolean("file.overwrite", false)) {
logger.info("[!] Deleting existing file" + prettySaveAs);
saveAs.delete();
} else {
logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs);
observer.downloadExists(url, saveAs);
return;
}
}
int bytesTotal, bytesDownloaded = 0;
try {
bytesTotal = getTotalBytes(this.url);
} catch (IOException e) {
logger.error("Failed to get file size at " + this.url, e);
observer.downloadErrored(this.url, "Failed to get file size of " + this.url);
return;
}
observer.setBytesTotal(bytesTotal);
observer.sendUpdate(STATUS.TOTAL_BYTES, bytesTotal);
logger.debug("Size of file at " + this.url + " = " + bytesTotal + "b");
int tries = 0; // Number of attempts to download
do {
InputStream bis = null; OutputStream fos = null;
byte[] data = new byte[1024 * 256];
int bytesRead;
try {
logger.info(" Downloading file: " + url + (tries > 0 ? " Retry #" + tries : ""));
observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm());
// Setup HTTP request
HttpURLConnection huc;
if (this.url.toString().startsWith("https")) {
huc = (HttpsURLConnection) this.url.openConnection();
}
else {
huc = (HttpURLConnection) this.url.openConnection();
}
huc.setInstanceFollowRedirects(true);
huc.setConnectTimeout(0); // Never timeout
huc.setRequestProperty("accept", "*/*");
huc.setRequestProperty("Referer", this.url.toExternalForm()); // Sic
huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT);
tries += 1;
logger.debug("Request properties: " + huc.getRequestProperties().toString());
huc.connect();
// Check status code
bis = new BufferedInputStream(huc.getInputStream());
fos = new FileOutputStream(saveAs);
while ( (bytesRead = bis.read(data)) != -1) {
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
fos.write(data, 0, bytesRead);
bytesDownloaded += bytesRead;
observer.setBytesCompleted(bytesDownloaded);
observer.sendUpdate(STATUS.COMPLETED_BYTES, bytesDownloaded);
}
bis.close();
fos.close();
break; // Download successful: break out of infinite loop
} catch (IOException e) {
logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage(), e);
} finally {
// Close any open streams
try {
if (bis != null) { bis.close(); }
} catch (IOException e) { }
try {
if (fos != null) { fos.close(); }
} catch (IOException e) { }
}
if (tries > this.retries) {
logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url);
observer.downloadErrored(url, "Failed to download " + url.toExternalForm());
return;
}
} while (true);
observer.downloadCompleted(url, saveAs);
logger.info("[+] Saved " + url + " as " + this.prettySaveAs);
| 366
| 1,021
| 1,387
|
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/VideoRipper.java
|
VideoRipper
|
downloadCompleted
|
class VideoRipper extends AbstractRipper {
private int bytesTotal = 1;
private int bytesCompleted = 1;
protected VideoRipper(URL url) throws IOException {
super(url);
}
public abstract void rip() throws IOException;
public abstract String getHost();
public abstract String getGID(URL url) throws MalformedURLException;
@Override
public void setBytesTotal(int bytes) {
this.bytesTotal = bytes;
}
@Override
public void setBytesCompleted(int bytes) {
this.bytesCompleted = bytes;
}
@Override
public String getAlbumTitle(URL url) {
return "videos";
}
@Override
public boolean addURLToDownload(URL url, File saveAs) {
if (Utils.getConfigBoolean("urls_only.save", false)) {
// Output URL to file
String urlFile = this.workingDir + File.separator + "urls.txt";
try (FileWriter fw = new FileWriter(urlFile, true)) {
fw.write(url.toExternalForm());
fw.write("\n");
RipStatusMessage msg = new RipStatusMessage(STATUS.DOWNLOAD_COMPLETE, urlFile);
observer.update(this, msg);
} catch (IOException e) {
LOGGER.error("Error while writing to " + urlFile, e);
return false;
}
} else {
if (isThisATest()) {
// Tests shouldn't download the whole video
// Just change this.url to the download URL so the test knows we found it.
LOGGER.debug("Test rip, found URL: " + url);
this.url = url;
return true;
}
threadPool.addThread(new DownloadVideoThread(url, saveAs, this));
}
return true;
}
@Override
public boolean addURLToDownload(URL url, File saveAs, String referrer, Map<String, String> cookies, Boolean getFileExtFromMIME) {
return addURLToDownload(url, saveAs);
}
/**
* Creates & sets working directory based on URL.
*
* @param url Target URL
*/
@Override
public void setWorkingDir(URL url) throws IOException {
String path = Utils.getWorkingDirectory().getCanonicalPath();
if (!path.endsWith(File.separator)) {
path += File.separator;
}
path += "videos" + File.separator;
workingDir = new File(path);
if (!workingDir.exists()) {
LOGGER.info("[+] Creating directory: " + Utils.removeCWD(workingDir));
workingDir.mkdirs();
}
LOGGER.debug("Set working directory to: " + workingDir);
}
/**
* @return Returns % of video done downloading.
*/
@Override
public int getCompletionPercentage() {
return (int) (100 * (bytesCompleted / (float) bytesTotal));
}
/**
* Runs if download successfully completed.
*
* @param url Target URL
* @param saveAs Path to file, including filename.
*/
@Override
public void downloadCompleted(URL url, File saveAs) {<FILL_FUNCTION_BODY>}
/**
* Runs if the download errored somewhere.
*
* @param url Target URL
* @param reason Reason why the download failed.
*/
@Override
public void downloadErrored(URL url, String reason) {
if (observer == null) {
return;
}
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_ERRORED, url + " : " + reason));
checkIfComplete();
}
/**
* Runs if user tries to redownload an already existing File.
*
* @param url Target URL
* @param file Existing file
*/
@Override
public void downloadExists(URL url, File file) {
if (observer == null) {
return;
}
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " already saved as " + file));
checkIfComplete();
}
/**
* Gets the status and changes it to a human-readable form.
*
* @return Status of current download.
*/
@Override
public String getStatusText() {
return String.valueOf(getCompletionPercentage()) +
"% - " +
Utils.bytesToHumanReadable(bytesCompleted) +
" / " +
Utils.bytesToHumanReadable(bytesTotal);
}
/**
* Sanitizes URL.
* Usually just returns itself.
*/
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
/**
* Notifies observers and updates state if all files have been ripped.
*/
@Override
protected void checkIfComplete() {
if (observer == null) {
return;
}
if (bytesCompleted >= bytesTotal) {
super.checkIfComplete();
}
}
}
|
if (observer == null) {
return;
}
try {
String path = Utils.removeCWD(saveAs);
RipStatusMessage msg = new RipStatusMessage(STATUS.DOWNLOAD_COMPLETE, path);
observer.update(this, msg);
checkIfComplete();
} catch (Exception e) {
LOGGER.error("Exception while updating observer: ", e);
}
| 1,357
| 107
| 1,464
|
<methods>public void <init>(java.net.URL) throws java.io.IOException,public abstract boolean addURLToDownload(java.net.URL, java.io.File) ,public abstract void downloadCompleted(java.net.URL, java.io.File) ,public abstract void downloadErrored(java.net.URL, java.lang.String) ,public abstract void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) throws java.net.MalformedURLException,public abstract int getCompletionPercentage() ,public static java.lang.String getFileName(java.net.URL, java.lang.String, java.lang.String) ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public static com.rarchives.ripme.ripper.AbstractRipper getRipper(java.net.URL) throws java.lang.Exception,public static List<Constructor<?>> getRipperConstructors(java.lang.String) throws java.lang.Exception,public abstract java.lang.String getStatusText() ,public java.net.URL getURL() ,public java.io.File getWorkingDir() ,public boolean hasASAPRipping() ,public boolean isStopped() ,public void markAsTest() ,public java.lang.String normalizeUrl(java.lang.String) ,public void retrievingSource(java.lang.String) ,public abstract void rip() throws java.io.IOException,public void run() ,public void sendUpdate(com.rarchives.ripme.ui.RipStatusMessage.STATUS, java.lang.Object) ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setObserver(com.rarchives.ripme.ui.RipStatusHandler) ,public abstract void setWorkingDir(java.net.URL) throws java.io.IOException,public void setup() throws java.io.IOException,public void stop() <variables>protected static final Logger LOGGER,private final java.lang.String URLHistoryFile,public static final java.lang.String USER_AGENT,public int alreadyDownloadedUrls,private boolean completed,com.rarchives.ripme.ui.RipStatusHandler observer,private boolean shouldStop,private static boolean thisIsATest,com.rarchives.ripme.ripper.DownloadThreadPool threadPool,protected java.net.URL url,protected java.io.File workingDir
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/AerisdiesRipper.java
|
AerisdiesRipper
|
getURLsFromPage
|
class AerisdiesRipper extends AbstractHTMLRipper {
private Map<String,String> cookies = new HashMap<>();
public AerisdiesRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "aerisdies";
}
@Override
public String getDomain() {
return "aerisdies.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://www.aerisdies.com/html/lb/[a-z]*_(\\d+)_\\d\\.html");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected URL format: http://www.aerisdies.com/html/lb/albumDIG, got: " + url);
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
try {
Element el = getFirstPage().select(".headtext").first();
if (el == null) {
throw new IOException("Unable to get album title");
}
String title = el.text();
return getHost() + "_" + getGID(url) + "_" + title.trim();
} catch (IOException e) {
// Fall back to default album naming convention
LOGGER.info("Unable to find title at " + url);
}
return super.getAlbumTitle(url);
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document page) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), cookies);
}
@Override
public String getPrefix(int index) {
return String.format("%03d_", index);
}
}
|
List<String> imageURLs = new ArrayList<>();
Elements albumElements = page.select("div.imgbox > a > img");
for (Element imageBox : albumElements) {
String imageUrl = imageBox.attr("src");
imageUrl = imageUrl.replaceAll("thumbnails", "images");
imageUrl = imageUrl.replaceAll("../../", "");
imageUrl = imageUrl.replaceAll("gif", "jpg");
imageURLs.add("http://www.aerisdies.com/" + imageUrl);
}
return imageURLs;
| 570
| 145
| 715
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/AllporncomicRipper.java
|
AllporncomicRipper
|
pageContainsAlbums
|
class AllporncomicRipper extends AbstractHTMLRipper {
public AllporncomicRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "allporncomic";
}
@Override
public String getDomain() {
return "allporncomic.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://allporncomic.com/porncomic/([a-zA-Z0-9_\\-]+)/([a-zA-Z0-9_\\-]+)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1) + "_" + m.group(2);
}
p = Pattern.compile("^https?://allporncomic.com/porncomic/([a-zA-Z0-9_\\-]+)/?$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected allporncomic URL format: " +
"allporncomic.com/TITLE/CHAPTER - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select(".wp-manga-chapter-img")) {
result.add(el.attr("data-src"));
}
return result;
}
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {<FILL_FUNCTION_BODY>}
@Override
public List<String> getAlbumsToQueue(Document doc) {
List<String> urlsToAddToQueue = new ArrayList<>();
for (Element elem : doc.select(".wp-manga-chapter > a")) {
urlsToAddToQueue.add(elem.attr("href"));
}
return urlsToAddToQueue;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern pa = Pattern.compile("^https?://allporncomic.com/porncomic/([a-zA-Z0-9_\\-]+)/?$");
Matcher ma = pa.matcher(url.toExternalForm());
return ma.matches();
| 670
| 74
| 744
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ArtStationRipper.java
|
ParsedURL
|
getJson
|
class ParsedURL {
URL_TYPE urlType;
String jsonURL, urlID;
/**
* Construct a new ParsedURL object.
*
* @param urlType URL_TYPE enum containing the URL type
* @param jsonURL String containing the JSON URL location
* @param urlID String containing the ID of this URL
*
*/
ParsedURL(URL_TYPE urlType, String jsonURL, String urlID) {
this.urlType = urlType;
this.jsonURL = jsonURL;
this.urlID = urlID;
}
/**
* Get URL Type of this ParsedURL object.
*
* @return URL_TYPE enum containing this object type
*
*/
URL_TYPE getType() {
return this.urlType;
}
/**
* Get JSON location of this ParsedURL object.
*
* @return String containing the JSON URL
*
*/
String getLocation() {
return this.jsonURL;
}
/**
* Get ID of this ParsedURL object.
*
* @return For URL_TYPE.SINGLE_PROJECT, returns the project hash. For
* URL_TYPE.USER_PORTFOLIO, returns the account name
*/
String getID() {
return this.urlID;
}
}
/**
* Parses an ArtStation URL.
*
* @param url URL to an ArtStation user profile
* (https://www.artstation.com/username) or single project
* (https://www.artstation.com/artwork/projectid)
* @return ParsedURL object containing URL type, JSON location and ID (stores
* account name or project hash, depending of the URL type identified)
*
*/
private ParsedURL parseURL(URL url) {
String htmlSource;
ParsedURL parsedURL;
// Load HTML Source of the specified URL
try {
// htmlSource = Http.url(url).get().html();
Connection con = Http.url(url).method(Method.GET).connection();
con.ignoreHttpErrors(true);
con.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0");
con.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
con.header("Accept-Language", "en-US,en;q=0.5");
// con.header("Accept-Encoding", "gzip, deflate, br");
con.header("Upgrade-Insecure-Requests", "1");
Response res = con.execute();
int status = res.statusCode();
if (status / 100 == 2) {
htmlSource = res.parse().html();
} else if (status == 403 && url.toString().contains("artwork/")) {
// Catches cloudflare page. Error 403.
// Usually caused by artwork URLs( arstation.com/artwork/someProjectId)
String urlId = url.toString().substring(url.toString().lastIndexOf("/") + 1);
String jsonURL = "https://www.artstation.com/projects/" + urlId + ".json";
parsedURL = new ParsedURL(URL_TYPE.SINGLE_PROJECT, jsonURL, urlId);
return parsedURL;
} else {
LOGGER.error("Couldnt fetch URL: " + url);
throw new IOException("Error fetching URL: " + url + " Status Code: " + status);
}
} catch (IOException e) {
htmlSource = "";
}
// Check if HTML Source of the specified URL references a project
Pattern p = Pattern.compile("'/projects/(\\w+)\\.json'");
Matcher m = p.matcher(htmlSource);
if (m.find()) {
parsedURL = new ParsedURL(URL_TYPE.SINGLE_PROJECT,
"https://www.artstation.com/projects/" + m.group(1) + ".json", m.group(1));
return parsedURL;
}
// Check if HTML Source of the specified URL references a user profile
p = Pattern.compile("'/users/([\\w-]+)/quick\\.json'");
m = p.matcher(htmlSource);
if (m.find()) {
parsedURL = new ParsedURL(URL_TYPE.USER_PORTFOLIO,
"https://www.artstation.com/users/" + m.group(1) + "/projects.json", m.group(1));
return parsedURL;
}
// HTML Source of the specified URL doesn't reference a user profile or project
parsedURL = new ParsedURL(URL_TYPE.UNKNOWN, null, null);
return parsedURL;
}
// Use this method instead of direct call to Http.url(url).getJson() to avoid
// cloudflare 403 page.
private JSONObject getJson(URL url) throws IOException {<FILL_FUNCTION_BODY>
|
Connection con = Http.url(url).method(Method.GET).connection();
con.ignoreHttpErrors(true);
con.ignoreContentType(true);
con.userAgent(
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
con.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
con.header("Accept-Language", "en-US,en;q=0.5");
// con.header("Accept-Encoding", "gzip, deflate, br");
con.header("Upgrade-Insecure-Requests", "1");
Response res = con.execute();
int status = res.statusCode();
if (status / 100 == 2) {
String jsonString = res.body();
return new JSONObject(jsonString);
}
throw new IOException("Error fetching json. Status code:" + status);
| 1,333
| 286
| 1,619
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ArtstnRipper.java
|
ArtstnRipper
|
getGID
|
class ArtstnRipper extends ArtStationRipper {
public URL artStationUrl = null;
public ArtstnRipper(URL url) throws IOException {
super(url);
}
@Override
public boolean canRip(URL url) {
return url.getHost().endsWith("artstn.co");
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
public URL getFinalUrl(URL url) throws IOException {
if (url.getHost().endsWith("artstation.com")) {
return url;
}
LOGGER.info("Checking url: " + url);
Response response = Http.url(url).connection().followRedirects(false).execute();
if (response.statusCode() / 100 == 3 && response.hasHeader("location")) {
return getFinalUrl(new URL(response.header("location")));
} else {
return null;
}
}
}
|
if (artStationUrl == null) {
// Run only once.
try {
artStationUrl = getFinalUrl(url);
if (artStationUrl == null) {
throw new IOException("Null url received.");
}
} catch (IOException e) {
LOGGER.error("Couldnt resolve URL.", e);
}
}
return super.getGID(artStationUrl);
| 282
| 122
| 404
|
<methods>public void <init>(java.net.URL) throws java.io.IOException,public java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public java.lang.String getHost() ,public java.lang.String normalizeUrl(java.lang.String) <variables>private com.rarchives.ripme.ripper.rippers.ArtStationRipper.ParsedURL albumURL,private java.lang.Integer projectIndex,private java.lang.String projectName,private java.lang.Integer projectPageNumber
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/BatoRipper.java
|
BatoRipper
|
getURLsFromPage
|
class BatoRipper extends AbstractHTMLRipper {
public BatoRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "bato";
}
@Override
public String getDomain() {
return "bato.to";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://bato.to/chapter/([\\d]+)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
// As this is just for quick queue support it does matter what this if returns
p = Pattern.compile("https?://bato.to/series/([\\d]+)/?");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return "";
}
throw new MalformedURLException("Expected bato.to URL format: " +
"bato.to/chapter/ID - got " + url + " instead");
}
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {
Pattern p = Pattern.compile("https?://bato.to/series/([\\d]+)/?");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public List<String> getAlbumsToQueue(Document doc) {
List<String> urlsToAddToQueue = new ArrayList<>();
for (Element elem : doc.select("div.main > div > a")) {
urlsToAddToQueue.add("https://" + getDomain() + elem.attr("href"));
}
return urlsToAddToQueue;
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
try {
// Attempt to use album title as GID
return getHost() + "_" + getGID(url) + "_" + getFirstPage().select("title").first().text().replaceAll(" ", "_");
} catch (IOException e) {
// Fall back to default album naming convention
LOGGER.info("Unable to find title at " + url);
}
return super.getAlbumTitle(url);
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("https?://bato.to/series/([\\d]+)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return true;
}
p = Pattern.compile("https?://bato.to/chapter/([\\d]+)/?");
m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
for (Element script : doc.select("script")) {
if (script.data().contains("var images = ")) {
String s = script.data();
s = s.replaceAll("var seriesId = \\d+;", "");
s = s.replaceAll("var chapterId = \\d+;", "");
s = s.replaceAll("var pages = \\d+;", "");
s = s.replaceAll("var page = \\d+;", "");
s = s.replaceAll("var prevCha = null;", "");
s = s.replaceAll("var nextCha = \\.*;", "");
String json = s.replaceAll("var images = ", "").replaceAll(";", "");
JSONObject images = new JSONObject(json);
for (int i = 1; i < images.length() +1; i++) {
result.add(images.getString(Integer.toString(i)));
}
}
}
return result;
| 881
| 258
| 1,139
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/BcfakesRipper.java
|
BcfakesRipper
|
getGID
|
class BcfakesRipper extends AbstractHTMLRipper {
public BcfakesRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "bcfakes";
}
@Override
public String getDomain() {
return "bcfakes.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
// Find next page
Elements hrefs = doc.select("a.next");
if (hrefs.isEmpty()) {
throw new IOException("No more pages");
}
String nextUrl = "http://www.bcfakes.com" + hrefs.first().attr("href");
sleep(500);
return Http.url(nextUrl).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
for (Element thumb : doc.select("div.ngg-gallery-thumbnail > a > img")) {
String imageURL = thumb.attr("src");
imageURL = imageURL.replace("thumbs/thumbs_", "");
imageURLs.add(imageURL);
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p;
Matcher m;
p = Pattern.compile("^https?://[wm.]*bcfakes.com/celebritylist/([a-zA-Z0-9\\-_]+).*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected bcfakes gallery format: "
+ "http://www.bcfakes.com/celebritylist/name"
+ " Got: " + url);
| 426
| 155
| 581
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/BlackbrickroadofozRipper.java
|
BlackbrickroadofozRipper
|
getNextPage
|
class BlackbrickroadofozRipper extends AbstractHTMLRipper {
public BlackbrickroadofozRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "blackbrickroadofoz";
}
@Override
public String getDomain() {
return "blackbrickroadofoz.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://www.blackbrickroadofoz.com/comic/([a-zA-Z0-9_-]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected blackbrickroadofoz URL format: " +
"www.blackbrickroadofoz.com/comic/PAGE - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
Element elem = doc.select("div[id=cc-comicbody] > a > img[id=cc-comic]").first();
// The site doesn't return properly encoded urls we replace all spaces ( ) with %20
result.add(elem.attr("src").replaceAll(" ", "%20"));
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
sleep(1000);
Element elem = doc.select("div[id=topnav] > nav.cc-nav > a.cc-next").first();
if (elem == null) {
throw new IOException("No more pages");
}
String nextPage = elem.attr("href");
return Http.url(nextPage).get();
| 494
| 90
| 584
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/BooruRipper.java
|
BooruRipper
|
getGID
|
class BooruRipper extends AbstractHTMLRipper {
private static final Logger logger = Logger.getLogger(BooruRipper.class);
private static Pattern gidPattern = null;
public BooruRipper(URL url) throws IOException {
super(url);
}
@Override
public boolean canRip(URL url) {
if (url.toExternalForm().contains("xbooru") || url.toExternalForm().contains("gelbooru")) {
return true;
}
return false;
}
@Override
public String getHost() {
logger.info(url.toExternalForm().split("/")[2]);
return url.toExternalForm().split("/")[2].split("\\.")[0];
}
@Override
public String getDomain() {
return url.toExternalForm().split("/")[2];
}
private String getPage(int num) throws MalformedURLException {
return "http://" + getHost() + ".com/index.php?page=dapi&s=post&q=index&pid=" + num + "&tags=" + getTerm(url);
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(getPage(0)).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
int offset = Integer.parseInt(doc.getElementsByTag("posts").first().attr("offset"));
int num = Integer.parseInt(doc.getElementsByTag("posts").first().attr("count"));
if (offset + 100 > num) {
return null;
}
return Http.url(getPage(offset / 100 + 1)).get();
}
@Override
public List<String> getURLsFromPage(Document page) {
List<String> res = new ArrayList<>(100);
for (Element e : page.getElementsByTag("post")) {
res.add(e.absUrl("file_url") + "#" + e.attr("id"));
}
return res;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, Utils.getConfigBoolean("download.save_order", true) ? url.getRef() + "-" : "");
}
private String getTerm(URL url) throws MalformedURLException {
if (gidPattern == null) {
gidPattern = Pattern.compile("^https?://(www\\.)?(x|gel)booru\\.com/(index.php)?.*([?&]tags=([a-zA-Z0-9$_.+!*'(),%-]+))(&|(#.*)?$)");
}
Matcher m = gidPattern.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(4);
}
throw new MalformedURLException("Expected xbooru.com URL format: " + getHost() + ".com/index.php?tags=searchterm - got " + url + " instead");
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
}
|
try {
return Utils.filesystemSafe(new URI(getTerm(url).replaceAll("&tags=", "")).getPath());
} catch (URISyntaxException ex) {
logger.error(ex);
}
throw new MalformedURLException("Expected xbooru.com URL format: " + getHost() + ".com/index.php?tags=searchterm - got " + url + " instead");
| 834
| 107
| 941
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/CfakeRipper.java
|
CfakeRipper
|
getNextPage
|
class CfakeRipper extends AbstractHTMLRipper {
public CfakeRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "cfake";
}
@Override
public String getDomain() {
return "cfake.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://cfake\\.com/picture/([a-zA-Z1-9_-]*)/\\d+/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected cfake URL format: " +
"cfake.com/picture/MODEL/ID - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select("table.display > tbody > tr > td > table > tbody > tr > td > a")) {
if (el.attr("href").contains("upload")) {
return result;
} else {
String imageSource = el.select("img").attr("src");
// We remove the .md from images so we download the full size image
// not the thumbnail ones
imageSource = imageSource.replace("thumbs", "photos");
result.add("http://cfake.com" + imageSource);
}
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
// Find next page
String nextUrl = "";
// We use comic-nav-next to the find the next page
Element elem = doc.select("td > div.next > a").first();
if (elem == null) {
throw new IOException("No more pages");
}
String nextPage = elem.attr("href");
// Some times this returns a empty string
// This for stops that
if (nextPage.equals("")) {
return null;
}
else {
return Http.url("http://cfake.com" + nextPage).get();
}
| 531
| 148
| 679
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/CheveretoRipper.java
|
CheveretoRipper
|
getAlbumTitle
|
class CheveretoRipper extends AbstractHTMLRipper {
private static final Map<String, String> CONSENT_COOKIE;
static {
CONSENT_COOKIE = new TreeMap<String, String>();
CONSENT_COOKIE.put("AGREE_CONSENT", "1");
}
public CheveretoRipper(URL url) throws IOException {
super(url);
}
private static List<String> explicit_domains = Arrays.asList("tag-fox.com", "kenzato.uk");
@Override
public String getHost() {
return url.toExternalForm().split("/")[2];
}
@Override
public String getDomain() {
return url.toExternalForm().split("/")[2];
}
@Override
public boolean canRip(URL url) {
String url_name = url.toExternalForm();
if (explicit_domains.contains(url_name.split("/")[2])) {
return true;
}
return false;
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("(?:https?://)?(?:www\\.)?[a-z1-9-]*\\.[a-z1-9]*(?:[a-zA-Z1-9]*)/album/([a-zA-Z1-9]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected chevereto URL format: " +
"site.domain/album/albumName or site.domain/username/albums- got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).cookies(CONSENT_COOKIE).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
// Find next page
String nextUrl = "";
// We use comic-nav-next to the find the next page
Element elem = doc.select("li.pagination-next > a").first();
if (elem == null) {
throw new IOException("No more pages");
}
String nextPage = elem.attr("href");
// Some times this returns a empty string
// This for stops that
if (nextPage == "") {
return null;
} else {
return Http.url(nextPage).cookies(CONSENT_COOKIE).get();
}
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select("a.image-container > img")) {
String imageSource = el.attr("src");
// We remove the .md from images so we download the full size image
// not the medium ones
imageSource = imageSource.replace(".md", "");
result.add(imageSource);
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
try {
// Attempt to use album title as GID
Element titleElement = getFirstPage().select("meta[property=og:title]").first();
String title = titleElement.attr("content");
title = title.substring(title.lastIndexOf('/') + 1);
return getHost() + "_" + title.trim();
} catch (IOException e) {
// Fall back to default album naming convention
LOGGER.info("Unable to find title at " + url);
}
return super.getAlbumTitle(url);
| 883
| 139
| 1,022
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ComicextraRipper.java
|
ComicextraRipper
|
getNextPage
|
class ComicextraRipper extends AbstractHTMLRipper {
private static final String FILE_NAME = "page";
private Pattern p1 =
Pattern.compile("https:\\/\\/www.comicextra.com\\/comic\\/([A-Za-z0-9_-]+)");
private Pattern p2 = Pattern.compile(
"https:\\/\\/www.comicextra.com\\/([A-Za-z0-9_-]+)\\/([A-Za-z0-9_-]+)(?:\\/full)?");
private UrlType urlType = UrlType.UNKNOWN;
private List<String> chaptersList = null;
private int chapterIndex = -1; // index for the chaptersList, useful in getting the next page.
private int imageIndex = 0; // image index for each chapter images.
public ComicextraRipper(URL url) throws IOException {
super(url);
}
@Override
protected String getDomain() {
return "comicextra.com";
}
@Override
public String getHost() {
return "comicextra";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Matcher m1 = p1.matcher(url.toExternalForm());
if (m1.matches()) {
// URL is of comic( https://www.comicextra.com/comic/the-punisher-frank-castle-max).
urlType = UrlType.COMIC;
return m1.group(1);
}
Matcher m2 = p2.matcher(url.toExternalForm());
if (m2.matches()) {
// URL is of chapter( https://www.comicextra.com/the-punisher-frank-castle-max/chapter-75).
urlType = UrlType.CHAPTER;
return m2.group(1);
}
throw new MalformedURLException(
"Expected comicextra.com url of type: https://www.comicextra.com/comic/some-comic-name\n"
+ " or https://www.comicextra.com/some-comic-name/chapter-001 got " + url
+ " instead");
}
@Override
protected Document getFirstPage() throws IOException {
Document doc = null;
switch (urlType) {
case COMIC:
// For COMIC type url we extract the urls of each chapters and store them in chapters.
chaptersList = new ArrayList<>();
Document comicPage = Http.url(url).get();
Elements elements = comicPage.select("div.episode-list a");
for (Element e : elements) {
chaptersList.add(getCompleteChapterUrl(e.attr("abs:href")));
}
// Set the first chapter from the chapterList as the doc.
chapterIndex = 0;
doc = Http.url(chaptersList.get(chapterIndex)).get();
break;
case CHAPTER:
doc = Http.url(url).get();
break;
case UNKNOWN:
default:
throw new IOException("Unknown url type encountered.");
}
return doc;
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
protected List<String> getURLsFromPage(Document page) {
List<String> urls = new ArrayList<>();
if (urlType == UrlType.COMIC || urlType == UrlType.CHAPTER) {
Elements images = page.select("img.chapter_img");
for (Element img : images) {
urls.add(img.attr("src"));
}
}
return urls;
}
@Override
protected void downloadURL(URL url, int index) {
String subdirectory = getSubDirectoryName();
String prefix = getPrefix(++imageIndex);
addURLToDownload(url, prefix, subdirectory, null, null, FILE_NAME, null, Boolean.TRUE);
}
/*
* This function appends /full at the end of the chapters url to get all the images for the
* chapter in the same Document.
*/
private String getCompleteChapterUrl(String chapterUrl) {
if (!chapterUrl.endsWith("/full")) {
chapterUrl = chapterUrl + "/full";
}
return chapterUrl;
}
/*
* This functions returns sub folder name for the current chapter.
*/
private String getSubDirectoryName() {
String subDirectory = "";
if (urlType == UrlType.COMIC) {
Matcher m = p2.matcher(chaptersList.get(chapterIndex));
if (m.matches()) {
subDirectory = m.group(2);
}
}
if (urlType == UrlType.CHAPTER) {
Matcher m = p2.matcher(url.toExternalForm());
if (m.matches()) {
subDirectory = m.group(2);
}
}
return subDirectory;
}
/*
* Enum to classify different types of urls.
*/
private enum UrlType {
COMIC, CHAPTER, UNKNOWN
}
}
|
if (urlType == UrlType.COMIC) {
++chapterIndex;
imageIndex = 0; // Resetting the imagesIndex so that images prefix within each chapter starts from '001_'.
if (chapterIndex < chaptersList.size()) {
return Http.url(chaptersList.get(chapterIndex)).get();
}
}
return super.getNextPage(doc);
| 1,511
| 116
| 1,627
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/CyberdropRipper.java
|
CyberdropRipper
|
getURLsFromPage
|
class CyberdropRipper extends AbstractHTMLRipper {
public CyberdropRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "cyberdrop";
}
@Override
protected Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public String getDomain() {
return "cyberdrop.me";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://cyberdrop\\.me/a/([a-zA-Z0-9]+).*?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected cyberdrop.me URL format: " +
"https://cyberdrop.me/a/xxxxxxxx - got " + url + "instead");
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
@Override
protected List<String> getURLsFromPage(Document page) {<FILL_FUNCTION_BODY>}
}
|
ArrayList<String> urls = new ArrayList<>();
for (Element element: page.getElementsByClass("image")) {
urls.add(element.attr("href"));
}
return urls;
| 380
| 61
| 441
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/DerpiRipper.java
|
DerpiRipper
|
sanitizeURL
|
class DerpiRipper extends AbstractJSONRipper {
private URL currUrl;
private Integer currPage;
public DerpiRipper(URL url) throws IOException {
super(url);
}
private String apiUrl;
@Override
public String getHost() {
return "DerpiBooru";
}
@Override
public String getDomain() {
return "derpibooru.org";
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public String getGID(URL url) throws MalformedURLException {
currUrl = url;
currPage = 1;
// search
Pattern p = Pattern.compile("^https?://derpibooru\\.org/search\\.json\\?q=([^&]+).*?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return "search_" + m.group(1);
}
// tags
p = Pattern.compile("^https?://derpibooru\\.org/tags/([^.]+)\\.json.*?$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return "tags_" + m.group(1);
}
// galleries
p = Pattern.compile("^https?://derpibooru\\.org/galleries/([^/]+)/(\\d+)\\.json.*?$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return "galleries_" + m.group(1) + "_" + m.group(2);
}
// single image
p = Pattern.compile("^https?://derpibooru\\.org/(\\d+)\\.json.*?$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return "image_" + m.group(1);
}
throw new MalformedURLException("Unable to find image in " + url);
}
@Override
public JSONObject getFirstPage() throws IOException {
return Http.url(url).getJSON();
}
@Override
public JSONObject getNextPage(JSONObject doc) throws IOException {
currPage++;
String u = currUrl.toExternalForm() + "&page=" + Integer.toString(currPage);
JSONObject json = Http.url(new URL(u)).getJSON();
JSONArray arr;
if (json.has("images")) {
arr = json.getJSONArray("images");
} else if (json.has("search")) {
arr = json.getJSONArray("search");
} else {
throw new IOException("No more images");
}
if (arr.length() == 0) {
throw new IOException("No more images");
}
return json;
}
private String getImageUrlFromJson(JSONObject json) {
return "https:" + json.getJSONObject("representations").getString("full");
}
@Override
public List<String> getURLsFromJSON(JSONObject json) {
List<String> imageURLs = new ArrayList<>();
JSONArray arr = null;
if (json.has("images")) {
arr = json.getJSONArray("images");
} else if (json.has("search")) {
arr = json.getJSONArray("search");
}
if (arr != null) {
for (int i = 0; i < arr.length(); i++){
imageURLs.add(this.getImageUrlFromJson(arr.getJSONObject(i)));
}
} else {
imageURLs.add(this.getImageUrlFromJson(json));
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
// we don't set an index prefix here as derpibooru already prefixes their images with their unique IDs
addURLToDownload(url, "");
}
}
|
String u = url.toExternalForm();
String[] uu = u.split("\\?", 2);
String newU = uu[0];
if (newU.substring(newU.length() - 1).equals("/")) {
newU = newU.substring(0, newU.length() - 1);
}
newU += ".json?";
if (uu.length > 1) {
newU += uu[1];
}
String key = Utils.getConfigString("derpi.key", "");
if (!key.equals("")) {
newU += "&key=" + key;
}
return new URL(newU);
| 1,066
| 179
| 1,245
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/DeviantartRipper.java
|
DeviantartImageThread
|
getFullSizeURL
|
class DeviantartImageThread extends Thread {
private URL url;
public DeviantartImageThread(URL url) {
this.url = url;
}
@Override
public void run() {
getFullSizeURL();
}
/**
* Get URL to Artwork and return fullsize URL with file ending.
*
* @param page Like
* https://www.deviantart.com/apofiss/art/warmest-of-the-days-455668450
* @return URL like
* https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/intermediary/f/07f7a6bb-2d35-4630-93fc-be249af22b3e/d7jak0y-d20e5932-df72-4d13-b002-5e122037b373.jpg
*
*
*/
private void getFullSizeURL() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Searching max. Resolution for " + url);
sendUpdate(STATUS.LOADING_RESOURCE, "Searching max. resolution for " + url);
try {
Response re = Http.url(url).connection().referrer(referer).userAgent(userAgent).cookies(getDACookie())
.execute();
Document doc = re.parse();
// Artwork Title
String title = doc.select("a.title").first().html();
title = title.replaceAll("[^a-zA-Z0-9\\.\\-]", "_").toLowerCase();
int counter = 1; // For images with same name add _X (X = number)
if (names.contains(title)) {
while (names.contains(title + "_" + counter)) {
counter++;
}
title = title + "_" + counter;
}
names.add(title);
// Check for download button
Element downloadButton = null;
downloadButton = doc.select("a.dev-page-download").first();
// Download Button
if (downloadButton != null) {
LOGGER.info("Download Button found for "+ url +" : " + downloadButton.attr("href"));
Response download = Http.url(downloadButton.attr("href")).connection().cookies(getDACookie())
.method(Method.GET).referrer(referer).userAgent(userAgent).ignoreContentType(true)
.followRedirects(true).execute();
URL location = download.url();
String[] filetypePart = download.header("Content-Disposition").split("\\.");
LOGGER.info("Found Image URL");
LOGGER.info(url);
LOGGER.info(location);
addURLToDownload(location, "", "", "", getDACookie(),
title + "." + filetypePart[filetypePart.length - 1]);
return;
}
// No Download Button
LOGGER.info("No Download Button for: "+ url);
Element div = doc.select("div.dev-view-deviation").first();
Element image = div.getElementsByTag("img").first();
String scaledImage = "";
if (image == null) {
LOGGER.error("ERROR on " + url);
LOGGER.error("Cookies: " + getDACookie() + " ");
LOGGER.error(div);
sendUpdate(STATUS.DOWNLOAD_ERRORED, "ERROR at\n" + url);
return;
}
// When it is text art (e.g. story) the only image is the profile
// picture
if (image.hasClass("avatar")) {
LOGGER.error("No Image found, probably text art: " + url);
return;
}
scaledImage = image.attr("src").split("\\?")[0];
String[] parts = scaledImage.split("/v1/"); // Image page uses scaled down version. Split at /v1/ to receive max size.
if (parts.length > 2) {
LOGGER.error("Unexpected URL Format");
sendUpdate(STATUS.DOWNLOAD_ERRORED, "Unexpected URL Format");
return;
}
String originalImage = parts[0]; // URL to original image without scaling (works not alwys. weird 404 errors.)
String downloadString = originalImage; // this works always
try {
Http.url(downloadString).connection().cookies(getDACookie()).method(Method.GET).referrer(referer).userAgent(userAgent).ignoreContentType(true).followRedirects(true).execute().statusCode(); //Error on 404
}catch (HttpStatusException e) {
downloadString = scaledImage; //revert back to save url because of error
}
String[] tmpParts = downloadString.split("\\."); //split to get file ending
addURLToDownload(new URL(downloadString), "", "", "", new HashMap<String, String>(),
title + "." + tmpParts[tmpParts.length - 1]);
return;
} catch (IOException e) {
e.printStackTrace();
}
LOGGER.error("No Full Size URL for: " + url);
sendUpdate(STATUS.DOWNLOAD_ERRORED, "No image found for " + url);
return;
| 301
| 1,146
| 1,447
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/DribbbleRipper.java
|
DribbbleRipper
|
getURLsFromPage
|
class DribbbleRipper extends AbstractHTMLRipper {
public DribbbleRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "dribbble";
}
@Override
public String getDomain() {
return "dribbble.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://[wm.]*dribbble\\.com/([a-zA-Z0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected dribbble.com URL format: " +
"dribbble.com/albumid - got " + url + "instead");
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
// Find next page
Elements hrefs = doc.select("a.next_page");
if (hrefs.isEmpty()) {
throw new IOException("No more pages");
}
String nextUrl = "https://www.dribbble.com" + hrefs.first().attr("href");
sleep(500);
return Http.url(nextUrl).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> imageURLs = new ArrayList<>();
for (Element thumb : doc.select("a.dribbble-link > picture > source")) {
// nl skips thumbnails
if ( thumb.attr("srcset").contains("teaser")) continue;
String image = thumb.attr("srcset").replace("_1x", "");
imageURLs.add(image);
}
return imageURLs;
| 460
| 110
| 570
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/DuckmoviesRipper.java
|
DuckmoviesRipper
|
getURLsFromPage
|
class DuckmoviesRipper extends AbstractSingleFileRipper {
public DuckmoviesRipper(URL url) throws IOException {
super(url);
}
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {
Pattern pa = Pattern.compile("https?://[a-zA-Z0-9]+.[a-zA-Z]+/(models|category)/([a-zA-Z0-9_-])+/?");
Matcher ma = pa.matcher(url.toExternalForm());
if (ma.matches()) {
return true;
}
pa = Pattern.compile("https?://[a-zA-Z0-9]+.[a-zA-Z]+/(models|category)/([a-zA-Z0-9_-])+/page/\\d+/?");
ma = pa.matcher(url.toExternalForm());
if (ma.matches()) {
return true;
}
return false;
}
@Override
public List<String> getAlbumsToQueue(Document doc) {
List<String> urlsToAddToQueue = new ArrayList<>();
for (Element elem : doc.select(".post > li > div > div > a")) {
urlsToAddToQueue.add(elem.attr("href"));
}
return urlsToAddToQueue;
}
private static List<String> explicit_domains = Arrays.asList(
"vidporntube.fun",
"pornbj.fun",
"iwantporn.fun",
"neoporn.fun",
"yayporn.fun",
"freshporn.co",
"palapaja.stream",
"freshporn.co",
"pornvidx.fun",
"palapaja.com"
);
@Override
public String getHost() {
return url.toExternalForm().split("/")[2];
}
@Override
public String getDomain() {
return url.toExternalForm().split("/")[2];
}
@Override
public boolean canRip(URL url) {
String url_name = url.toExternalForm();
return explicit_domains.contains(url_name.split("/")[2]);
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(this.url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https://[a-zA-Z0-9]+\\.[a-zA-Z]+/([a-zA-Z0-9\\-_]+)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
p = Pattern.compile("https?://[a-zA-Z0-9]+.[a-zA-Z]+/(category|models)/([a-zA-Z0-9_-])+/?");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
p = Pattern.compile("https?://[a-zA-Z0-9]+.[a-zA-Z]+/(category|models)/([a-zA-Z0-9_-])+/page/\\d+");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected duckmovies format:"
+ "domain.tld/Video-title"
+ " Got: " + url);
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, "", "", null, null, AbstractRipper.getFileName(url, null, null).replaceAll("%20", "_"));
}
@Override
public boolean tryResumeDownload() {return true;}
}
|
List<String> results = new ArrayList<>();
String duckMoviesUrl = doc.select("iframe").attr("src");
try {
Document duckDoc = Http.url(new URL(duckMoviesUrl)).get();
String videoURL = duckDoc.select("source").attr("src");
// remove any white spaces so we can download the movie without a 400 error
videoURL = videoURL.replaceAll(" ", "%20");
results.add(videoURL);
} catch (MalformedURLException e) {
LOGGER.error(duckMoviesUrl + " is not a valid url");
} catch (IOException e) {
LOGGER.error("Unable to load page " + duckMoviesUrl);
e.printStackTrace();
}
return results;
| 1,100
| 201
| 1,301
|
<methods>public int getCompletionPercentage() ,public java.lang.String getStatusText() ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public boolean useByteProgessBar() <variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/DynastyscansRipper.java
|
DynastyscansRipper
|
getURLsFromPage
|
class DynastyscansRipper extends AbstractHTMLRipper {
public DynastyscansRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "dynasty-scans";
}
@Override
public String getDomain() {
return "dynasty-scans.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://dynasty-scans.com/chapters/([\\S]+)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected dynasty-scans URL format: " +
"dynasty-scans.com/chapters/ID - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
Element elem = doc.select("a[id=next_link]").first();
if (elem == null || elem.attr("href").equals("#")) {
throw new IOException("No more pages");
}
return Http.url("https://dynasty-scans.com" + elem.attr("href")).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
String jsonText = null;
for (Element script : doc.select("script")) {
if (script.data().contains("var pages")) {
jsonText = script.data().replaceAll("var pages = ", "");
jsonText = jsonText.replaceAll("//<!\\[CDATA\\[", "");
jsonText = jsonText.replaceAll("//]]>", "");
}
}
JSONArray imageArray = new JSONArray(jsonText);
for (int i = 0; i < imageArray.length(); i++) {
result.add("https://dynasty-scans.com" + imageArray.getJSONObject(i).getString("image"));
}
return result;
| 466
| 189
| 655
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/E621Ripper.java
|
E621FileThread
|
getFullSizedImage
|
class E621FileThread extends Thread {
private URL url;
private String index;
public E621FileThread(URL url, String index) {
this.url = url;
this.index = index;
}
@Override
public void run() {
try {
String fullSizedImage = getFullSizedImage(url);
if (fullSizedImage != null && !fullSizedImage.equals("")) {
addURLToDownload(new URL(fullSizedImage), index);
}
} catch (IOException e) {
logger.error("Unable to get full sized image from " + url);
}
}
private String getFullSizedImage(URL imageURL) throws IOException {<FILL_FUNCTION_BODY>}
}
|
Document page = getDocument(imageURL.toExternalForm(), 3);
/*Elements video = page.select("video > source");
Elements flash = page.select("embed");
Elements image = page.select("a#highres");
if (video.size() > 0) {
return video.attr("src");
} else if (flash.size() > 0) {
return flash.attr("src");
} else if (image.size() > 0) {
return image.attr("href");
} else {
throw new IOException();
}*/
if (!page.select("div#image-download-link > a").isEmpty()) {
return page.select("div#image-download-link > a").attr("abs:href");
} else {
if(!page.select("#blacklist-box").isEmpty())
sendUpdate(RipStatusMessage.STATUS.RIP_ERRORED, "Cannot download image - blocked by blacklist. Consider logging in. Search for \"e621\" in this wiki page: https://github.com/RipMeApp/ripme/wiki/Config-options");
throw new IOException();
}
| 202
| 284
| 486
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/EightmusesRipper.java
|
EightmusesRipper
|
getGID
|
class EightmusesRipper extends AbstractHTMLRipper {
private Document albumDoc = null;
private Map<String,String> cookies = new HashMap<>();
// TODO put up a wiki page on using maps to store titles
// the map for storing the title of each album when downloading sub albums
private Map<URL,String> urlTitles = new HashMap<>();
private Boolean rippingSubalbums = false;
public EightmusesRipper(URL url) throws IOException {
super(url);
}
@Override
public boolean hasASAPRipping() {
return true;
}
@Override
public String getHost() {
return "8muses";
}
@Override
public String getDomain() {
return "8muses.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
try {
// Attempt to use album title as GID
Element titleElement = getFirstPage().select("meta[name=description]").first();
String title = titleElement.attr("content");
title = title.replace("A huge collection of free porn comics for adults. Read", "");
title = title.replace("online for free at 8muses.com", "");
return getHost() + "_" + title.trim();
} catch (IOException e) {
// Fall back to default album naming convention
LOGGER.info("Unable to find title at " + url);
}
return super.getAlbumTitle(url);
}
@Override
public Document getFirstPage() throws IOException {
if (albumDoc == null) {
Response resp = Http.url(url).response();
cookies.putAll(resp.cookies());
albumDoc = resp.parse();
}
return albumDoc;
}
@Override
public List<String> getURLsFromPage(Document page) {
List<String> imageURLs = new ArrayList<>();
int x = 1;
// This contains the thumbnails of all images on the page
Elements pageImages = page.getElementsByClass("c-tile");
for (Element thumb : pageImages) {
// If true this link is a sub album
if (thumb.attr("href").contains("/comics/album/")) {
String subUrl = "https://www.8muses.com" + thumb.attr("href");
try {
LOGGER.info("Retrieving " + subUrl);
sendUpdate(STATUS.LOADING_RESOURCE, subUrl);
Document subPage = Http.url(subUrl).get();
// If the page below this one has images this line will download them
List<String> subalbumImages = getURLsFromPage(subPage);
LOGGER.info("Found " + subalbumImages.size() + " images in subalbum");
} catch (IOException e) {
LOGGER.warn("Error while loading subalbum " + subUrl, e);
}
} else if (thumb.attr("href").contains("/comics/picture/")) {
LOGGER.info("This page is a album");
LOGGER.info("Ripping image");
if (super.isStopped()) break;
// Find thumbnail image source
String image = null;
if (thumb.hasAttr("data-cfsrc")) {
image = thumb.attr("data-cfsrc");
} else {
// Deobfustace the json data
String rawJson = deobfuscateJSON(page.select("script#ractive-public").html()
.replaceAll(">", ">").replaceAll("<", "<").replace("&", "&"));
JSONObject json = new JSONObject(rawJson);
try {
for (int i = 0; i != json.getJSONArray("pictures").length(); i++) {
image = "https://www.8muses.com/image/fl/" + json.getJSONArray("pictures").getJSONObject(i).getString("publicUri");
URL imageUrl = new URL(image);
addURLToDownload(imageUrl, getPrefixShort(x), getSubdir(page.select("title").text()), this.url.toExternalForm(), cookies, "", null, true);
// X is our page index
x++;
if (isThisATest()) {
break;
}
}
return imageURLs;
} catch (MalformedURLException e) {
LOGGER.error("\"" + image + "\" is malformed");
}
}
if (!image.contains("8muses.com")) {
// Not hosted on 8muses.
continue;
}
imageURLs.add(image);
if (isThisATest()) break;
}
}
return imageURLs;
}
public String getSubdir(String rawHref) {
LOGGER.info("Raw title: " + rawHref);
String title = rawHref;
title = title.replaceAll("8muses - Sex and Porn Comics", "");
title = title.replaceAll("\\s+", " ");
title = title.replaceAll("\n", "");
title = title.replaceAll("\\| ", "");
title = title.replace(" - ", "-");
title = title.replace(" ", "-");
LOGGER.info(title);
return title;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), cookies);
}
public String getPrefixLong(int index) {
return String.format("%03d_", index);
}
public String getPrefixShort(int index) {
return String.format("%03d", index);
}
private String deobfuscateJSON(String obfuscatedString) {
StringBuilder deobfuscatedString = new StringBuilder();
// The first char in one of 8muses obfuscated strings is always ! so we replace it
for (char ch : obfuscatedString.replaceFirst("!", "").toCharArray()){
deobfuscatedString.append(deobfuscateChar(ch));
}
return deobfuscatedString.toString();
}
private String deobfuscateChar(char c) {
if ((int) c == 32) {
return fromCharCode(32);
}
return fromCharCode(33 + (c + 14) % 94);
}
private static String fromCharCode(int... codePoints) {
return new String(codePoints, 0, codePoints.length);
}
}
|
Pattern p = Pattern.compile("^https?://(www\\.)?8muses\\.com/(comix|comics)/album/([a-zA-Z0-9\\-_]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (!m.matches()) {
throw new MalformedURLException("Expected URL format: http://www.8muses.com/index/category/albumname, got: " + url);
}
return m.group(m.groupCount());
| 1,725
| 137
| 1,862
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ErofusRipper.java
|
ErofusRipper
|
getURLsFromPage
|
class ErofusRipper extends AbstractHTMLRipper {
public ErofusRipper(URL url) throws IOException {
super(url);
}
@Override
public boolean hasASAPRipping() {
return true;
}
@Override
public String getHost() {
return "erofus";
}
@Override
public String getDomain() {
return "erofus.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https://www.erofus.com/comics/([a-zA-Z0-9\\-_]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (!m.matches()) {
throw new MalformedURLException("Expected URL format: http://www.8muses.com/index/category/albumname, got: " + url);
}
return m.group(m.groupCount());
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document page) {<FILL_FUNCTION_BODY>}
public void ripAlbum(Document page) {
int x = 1;
Elements thumbs = page.select("a.a-click > div.thumbnail > img");
for (Element thumb : thumbs) {
String image = "https://www.erofus.com" + thumb.attr("src").replaceAll("thumb", "medium");
try {
Map<String,String> opts = new HashMap<String, String>();
opts.put("subdirectory", page.title().replaceAll(" \\| Erofus - Sex and Porn Comics", "").replaceAll(" ", "_"));
opts.put("prefix", getPrefix(x));
addURLToDownload(new URL(image), opts);
} catch (MalformedURLException e) {
LOGGER.info(e.getMessage());
}
x++;
}
}
private boolean pageContainsImages(Document page) {
Elements pageImages = page.select("a.a-click");
for (Element pageLink : pageImages) {
if (pageLink.attr("href").contains("/pic/")) {
return true;
}
}
return false;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
LOGGER.info(page);
List<String> imageURLs = new ArrayList<>();
int x = 1;
if (pageContainsImages(page)) {
LOGGER.info("Page contains images");
ripAlbum(page);
} else {
// This contains the thumbnails of all images on the page
Elements pageImages = page.select("a.a-click");
for (Element pageLink : pageImages) {
if (super.isStopped()) break;
if (pageLink.attr("href").contains("comics")) {
String subUrl = "https://erofus.com" + pageLink.attr("href");
try {
LOGGER.info("Retrieving " + subUrl);
sendUpdate(RipStatusMessage.STATUS.LOADING_RESOURCE, subUrl);
Document subPage = Http.url(subUrl).get();
List<String> subalbumImages = getURLsFromPage(subPage);
} catch (IOException e) {
LOGGER.warn("Error while loading subalbum " + subUrl, e);
}
}
if (isThisATest()) break;
}
}
return imageURLs;
| 658
| 301
| 959
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/EromeRipper.java
|
EromeRipper
|
getGID
|
class EromeRipper extends AbstractHTMLRipper {
private static final String EROME_REFERER = "https://www.erome.com/";
boolean rippingProfile;
public EromeRipper (URL url) throws IOException {
super(url);
}
@Override
public String getDomain() {
return "erome.com";
}
@Override
public String getHost() {
return "erome";
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", EROME_REFERER, null, null);
}
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {
Pattern pa = Pattern.compile("https?://www.erome.com/([a-zA-Z0-9_\\-?=]*)/?");
Matcher ma = pa.matcher(url.toExternalForm());
return ma.matches();
}
@Override
public List<String> getAlbumsToQueue(Document doc) {
List<String> urlsToAddToQueue = new ArrayList<>();
for (Element elem : doc.select("div#albums > div.album > a")) {
urlsToAddToQueue.add(elem.attr("href"));
}
return urlsToAddToQueue;
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
try {
// Attempt to use album title as GID
Element titleElement = getFirstPage().select("meta[property=og:title]").first();
String title = titleElement.attr("content");
title = title.substring(title.lastIndexOf('/') + 1);
return getHost() + "_" + getGID(url) + "_" + title.trim();
} catch (IOException e) {
// Fall back to default album naming convention
LOGGER.info("Unable to find title at " + url);
} catch (NullPointerException e) {
return getHost() + "_" + getGID(url);
}
return super.getAlbumTitle(url);
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return new URL(url.toExternalForm().replaceAll("https?://erome.com", "https://www.erome.com"));
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> URLs = new ArrayList<>();
return getMediaFromPage(doc);
}
@Override
public Document getFirstPage() throws IOException {
Response resp = Http.url(this.url)
.ignoreContentType()
.response();
return resp.parse();
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
private List<String> getMediaFromPage(Document doc) {
List<String> results = new ArrayList<>();
for (Element el : doc.select("img.img-front")) {
if (el.hasAttr("src")) {
if (el.attr("src").startsWith("https:")) {
results.add(el.attr("src"));
} else {
results.add("https:" + el.attr("src"));
}
} else if (el.hasAttr("data-src")) {
//to add images that are not loaded( as all images are lasyloaded as we scroll).
results.add(el.attr("data-src"));
}
}
for (Element el : doc.select("source[label=HD]")) {
if (el.attr("src").startsWith("https:")) {
results.add(el.attr("src"));
}
else {
results.add("https:" + el.attr("src"));
}
}
for (Element el : doc.select("source[label=SD]")) {
if (el.attr("src").startsWith("https:")) {
results.add(el.attr("src"));
}
else {
results.add("https:" + el.attr("src"));
}
}
return results;
}
}
|
Pattern p = Pattern.compile("^https?://www.erome.com/[ai]/([a-zA-Z0-9]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
p = Pattern.compile("^https?://www.erome.com/([a-zA-Z0-9_\\-?=]+)/?$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("erome album not found in " + url + ", expected https://www.erome.com/album");
| 1,110
| 197
| 1,307
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ErotivRipper.java
|
ErotivRipper
|
getURLsFromPage
|
class ErotivRipper extends AbstractHTMLRipper {
boolean rippingProfile;
public ErotivRipper(URL url) throws IOException {
super(url);
}
@Override
public String getDomain() {
return "erotiv.io";
}
@Override
public String getHost() {
return "erotiv";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://(?:www.)?erotiv.io/e/([0-9]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("erotiv video not found in " + url + ", expected https://erotiv.io/e/id");
}
@Override
public Document getFirstPage() throws IOException {
Response resp = Http.url(this.url).ignoreContentType().response();
return resp.parse();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return new URL(url.toExternalForm().replaceAll("https?://www.erotiv.io", "https://erotiv.io"));
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
@Override
public boolean hasQueueSupport() {
return true;
}
}
|
List<String> results = new ArrayList<>();
for (Element el : doc.select("video[id=\"video-id\"] > source")) {
if (el.hasAttr("src")) {
Pattern p = Pattern.compile("/uploads/[0-9]*\\.mp4");
Matcher m = p.matcher(el.attr("src"));
if (m.matches()) {
results.add("https://erotiv.io" + el.attr("src"));
}
}
}
return results;
| 438
| 141
| 579
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/FemjoyhunterRipper.java
|
FemjoyhunterRipper
|
getGID
|
class FemjoyhunterRipper extends AbstractHTMLRipper {
public FemjoyhunterRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "femjoyhunter";
}
@Override
public String getDomain() {
return "femjoyhunter.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select("img")) {
result.add(el.attr("src"));
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", "https://a2h6m3w6.ssl.hwcdn.net/", null);
}
}
|
Pattern p = Pattern.compile("https?://www.femjoyhunter.com/([a-zA-Z0-9_-]+)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected femjoyhunter URL format: " +
"femjoyhunter.com/ID - got " + url + " instead");
| 310
| 122
| 432
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/FitnakedgirlsRipper.java
|
FitnakedgirlsRipper
|
getGID
|
class FitnakedgirlsRipper extends AbstractHTMLRipper {
public FitnakedgirlsRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "fitnakedgirls";
}
@Override
public String getDomain() {
return "fitnakedgirls.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
Elements imgs = doc.select("div[class*=wp-tiles-tile-bg] > img");
for (Element img : imgs) {
String imgSrc = img.attr("src");
imageURLs.add(imgSrc);
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
// Send referrer when downloading images
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), null);
}
}
|
Pattern p;
Matcher m;
p = Pattern.compile("^.*fitnakedgirls\\.com/gallery/(.+)$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected fitnakedgirls.com gallery format: " + "fitnakedgirls.com/gallery/####" + " Got: " + url);
| 379
| 141
| 520
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/FolioRipper.java
|
FolioRipper
|
getFirstPage
|
class FolioRipper extends AbstractJSONRipper {
public FolioRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "folio";
}
@Override
public String getDomain() {
return "folio.ink";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://(?:www.)?folio.ink/([a-zA-Z0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected folio.ink URL format: " +
"folio.ink/albumid (e.g: folio.ink/DmBe6i) - got " + url + " instead");
}
@Override
public JSONObject getFirstPage() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromJSON(JSONObject json) {
List<String> result = new ArrayList<String>();
JSONArray imagesArray = json.getJSONArray("images");
for (int i = 0; i < imagesArray.length(); i++) {
JSONObject image = imagesArray.getJSONObject(i);
result.add(image.getString("image_url"));
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
String jsonArrayString = Http.url("https://folio.ink/getimages/" + getGID(url)).ignoreContentType().response().body();
JSONArray imagesArray = new JSONArray(jsonArrayString);
JSONObject imagesObject = new JSONObject();
imagesObject.put("images", imagesArray);
return imagesObject;
| 423
| 83
| 506
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/FooktubeRipper.java
|
FooktubeRipper
|
getGID
|
class FooktubeRipper extends AbstractSingleFileRipper {
private static final String HOST = "mulemax";
public FooktubeRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "mulemax";
}
@Override
public String getDomain() {
return "mulemax.com";
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://.*fooktube\\.com/video/(.*)/.*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
result.add(doc.select(".video-js > source").attr("src"));
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", "mulemax.com", null);
}
}
|
Pattern p = Pattern.compile("^https?://.*fooktube\\.com/video/(.*)/(.*)$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(2);
}
throw new MalformedURLException(
"Expected fooktube format:"
+ "fooktube.com/video/####"
+ " Got: " + url);
| 388
| 116
| 504
|
<methods>public int getCompletionPercentage() ,public java.lang.String getStatusText() ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public boolean useByteProgessBar() <variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/FreeComicOnlineRipper.java
|
FreeComicOnlineRipper
|
getGID
|
class FreeComicOnlineRipper extends AbstractHTMLRipper {
public FreeComicOnlineRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "freecomiconline";
}
@Override
public String getDomain() {
return "freecomiconline.me";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
String nextPage = doc.select("div.select-pagination a").get(1).attr("href");
String nextUrl = "";
Pattern p = Pattern.compile("https://freecomiconline.me/comic/([a-zA-Z0-9_\\-]+)/([a-zA-Z0-9_\\-]+)/?$");
Matcher m = p.matcher(nextPage);
if(m.matches()){
nextUrl = m.group(0);
}
if(nextUrl.equals("")) throw new IOException("No more pages");
sleep(500);
return Http.url(nextUrl).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select(".wp-manga-chapter-img")) {
result.add(el.attr("src"));
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("https://freecomiconline.me/comic/([a-zA-Z0-9_\\-]+)/([a-zA-Z0-9_\\-]+)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1) + "_" + m.group(2);
}
p = Pattern.compile("^https://freecomiconline.me/comic/([a-zA-Z0-9_\\-]+)/?$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected freecomiconline URL format: " +
"freecomiconline.me/TITLE/CHAPTER - got " + url + " instead");
| 474
| 228
| 702
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/FuskatorRipper.java
|
FuskatorRipper
|
getXAuthToken
|
class FuskatorRipper extends AbstractHTMLRipper {
private String jsonurl = "https://fuskator.com/ajax/gal.aspx";
private String xAuthUrl = "https://fuskator.com/ajax/auth.aspx";
private String xAuthToken;
private Map<String, String> cookies;
public FuskatorRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "fuskator";
}
@Override
public String getDomain() {
return "fuskator.com";
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
String u = url.toExternalForm();
if (u.contains("/thumbs/")) {
u = u.replace("/thumbs/", "/full/");
}
if (u.contains("/expanded/")) {
u = u.replaceAll("/expanded/", "/full/");
}
return new URL(u);
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^.*fuskator.com/full/([a-zA-Z0-9\\-~]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected fuskator.com gallery formats: " + "fuskator.com/full/id/..." + " Got: " + url);
}
@Override
public Document getFirstPage() throws IOException {
// return Http.url(url).get();
Response res = Http.url(url).response();
cookies = res.cookies();
return res.parse();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
JSONObject json;
try {
getXAuthToken();
if (xAuthToken == null || xAuthToken.isEmpty()) {
throw new IOException("No xAuthToken found.");
}
// All good. Fetch JSON data from jsonUrl.
json = Http.url(jsonurl).cookies(cookies).data("X-Auth", xAuthToken).data("hash", getGID(url))
.data("_", Long.toString(System.currentTimeMillis())).getJSON();
} catch (IOException e) {
LOGGER.error("Couldnt fetch images.", e.getCause());
return imageURLs;
}
JSONArray imageArray = json.getJSONArray("images");
for (int i = 0; i < imageArray.length(); i++) {
imageURLs.add("https:" + imageArray.getJSONObject(i).getString("imageUrl"));
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
private void getXAuthToken() throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (cookies == null || cookies.isEmpty()) {
throw new IOException("Null cookies or no cookies found.");
}
Response res = Http.url(xAuthUrl).cookies(cookies).method(Method.POST).response();
xAuthToken = res.body();
| 812
| 70
| 882
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/GfycatRipper.java
|
GfycatRipper
|
getNextPage
|
class GfycatRipper extends AbstractHTMLRipper {
private static final String HOST = "gfycat.com";
String username = "";
String cursor = "";
String count = "30";
String REFERRER = "www.reddit.com";
public GfycatRipper(URL url) throws IOException {
super(new URL(url.toExternalForm().split("-")[0].replace("thumbs.", "")));
}
@Override
public String getDomain() {
return "gfycat.com";
}
@Override
public String getHost() {
return "gfycat";
}
@Override
public boolean canRip(URL url) {
return url.getHost().endsWith(HOST);
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
String sUrl = url.toExternalForm();
sUrl = sUrl.replace("/gifs/detail", "");
sUrl = sUrl.replace("/amp", "");
return new URL(sUrl);
}
public boolean isProfile() {
Pattern p = Pattern.compile("^https?://[wm.]*gfycat\\.com/@([a-zA-Z0-9\\.\\-\\_]+).*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public Document getFirstPage() throws IOException {
if (!isProfile()) {
return Http.url(url).referrer(REFERRER).get();
} else {
username = getGID(url);
return Http.url(new URL("https://api.gfycat.com/v1/users/" + username + "/gfycats")).referrer((REFERRER)).ignoreContentType().get();
}
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://(?:thumbs\\.|[wm\\.]*)gfycat\\.com/@?([a-zA-Z0-9\\.\\-\\_]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches())
return m.group(1);
throw new MalformedURLException(
"Expected gfycat.com format: "
+ "gfycat.com/id or "
+ "thumbs.gfycat.com/id.gif"
+ " Got: " + url);
}
private String stripHTMLTags(String t) {
t = t.replaceAll("<html>\n" +
" <head></head>\n" +
" <body>", "");
t = t.replaceAll("</body>\n" +
"</html>", "");
t = t.replaceAll("\n", "");
t = t.replaceAll("=\"\"", "");
return t;
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
if (isProfile()) {
JSONObject page = new JSONObject(stripHTMLTags(doc.html()));
JSONArray content = page.getJSONArray("gfycats");
for (int i = 0; i < content.length(); i++) {
result.add(content.getJSONObject(i).getString("mp4Url"));
}
cursor = page.getString("cursor");
} else {
Elements videos = doc.select("script");
for (Element el : videos) {
String json = el.html();
if (json.startsWith("{")) {
JSONObject page = new JSONObject(json);
result.add(page.getJSONObject("video").getString("contentUrl"));
}
}
}
return result;
}
/**
* Helper method for retrieving video URLs.
* @param url URL to gfycat page
* @return URL to video
* @throws IOException
*/
public static String getVideoURL(URL url) throws IOException {
LOGGER.info("Retrieving " + url.toExternalForm());
//Sanitize the URL first
url = new URL(url.toExternalForm().replace("/gifs/detail", ""));
Document doc = Http.url(url).get();
Elements videos = doc.select("script");
for (Element el : videos) {
String json = el.html();
if (json.startsWith("{")) {
JSONObject page = new JSONObject(json);
return page.getJSONObject("video").getString("contentUrl");
}
}
throw new IOException();
}
}
|
if (cursor.equals("")) {
throw new IOException("No more pages");
}
return Http.url(new URL("https://api.gfycat.com/v1/users/" + username + "/gfycats?count=" + count + "&cursor=" + cursor)).ignoreContentType().get();
| 1,286
| 80
| 1,366
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/GfycatporntubeRipper.java
|
GfycatporntubeRipper
|
getGID
|
class GfycatporntubeRipper extends AbstractSingleFileRipper {
public GfycatporntubeRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "gfycatporntube";
}
@Override
public String getDomain() {
return "gfycatporntube.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
result.add(doc.select("source[id=mp4Source]").attr("src"));
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("https?://gfycatporntube.com/([a-zA-Z1-9_-]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected gfycatporntube URL format: " +
"gfycatporntube.com/NAME - got " + url + " instead");
| 285
| 125
| 410
|
<methods>public int getCompletionPercentage() ,public java.lang.String getStatusText() ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public boolean useByteProgessBar() <variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/GirlsOfDesireRipper.java
|
GirlsOfDesireRipper
|
getAlbumTitle
|
class GirlsOfDesireRipper extends AbstractHTMLRipper {
// Current HTML document
private Document albumDoc = null;
public GirlsOfDesireRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "GirlsOfDesire";
}
@Override
public String getDomain() {
return "girlsofdesire.org";
}
public String getAlbumTitle(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p;
Matcher m;
p = Pattern.compile("^www\\.girlsofdesire\\.org/galleries/([\\w\\d-]+)/$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected girlsofdesire.org gallery format: "
+ "http://www.girlsofdesire.org/galleries/<name>/"
+ " Got: " + url);
}
@Override
public Document getFirstPage() throws IOException {
if (albumDoc == null) {
albumDoc = Http.url(url).get();
}
return albumDoc;
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
for (Element thumb : doc.select("td.vtop > a > img")) {
String imgSrc = thumb.attr("src");
imgSrc = imgSrc.replaceAll("_thumb\\.", ".");
if (imgSrc.startsWith("/")) {
imgSrc = "http://www.girlsofdesire.org" + imgSrc;
}
imageURLs.add(imgSrc);
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
// Send referrer when downloading images
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), null);
}
}
|
try {
// Attempt to use album title as GID
Document doc = getFirstPage();
Elements elems = doc.select(".albumName");
return getHost() + "_" + elems.first().text();
} catch (Exception e) {
// Fall back to default album naming convention
LOGGER.warn("Failed to get album title from " + url, e);
}
return super.getAlbumTitle(url);
| 577
| 114
| 691
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/HbrowseRipper.java
|
HbrowseRipper
|
getGID
|
class HbrowseRipper extends AbstractHTMLRipper {
public HbrowseRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "hbrowse";
}
@Override
public String getDomain() {
return "hbrowse.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
Document tempDoc = Http.url(url).get();
return Http.url("https://www.hbrowse.com" + tempDoc.select("td[id=pageTopHome] > a[title=view thumbnails (top)]").attr("href")).get();
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
try {
Document doc = getFirstPage();
String title = doc.select("div[id=main] > table.listTable > tbody > tr > td.listLong").first().text();
return getHost() + "_" + title + "_" + getGID(url);
} catch (Exception e) {
// Fall back to default album naming convention
LOGGER.warn("Failed to get album title from " + url, e);
}
return super.getAlbumTitle(url);
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<String>();
for (Element el : doc.select("table > tbody > tr > td > a > img")) {
String imageURL = el.attr("src").replace("/zzz", "");
result.add("https://www.hbrowse.com" + imageURL);
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("https?://www.hbrowse.com/(\\d+)/[a-zA-Z0-9]*");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected hbrowse.com URL format: " +
"hbrowse.com/ID/COMICID - got " + url + " instead");
| 522
| 125
| 647
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/Hentai2readRipper.java
|
Hentai2readRipper
|
getAlbumTitle
|
class Hentai2readRipper extends AbstractHTMLRipper {
String lastPage;
public Hentai2readRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "hentai2read";
}
@Override
public String getDomain() {
return "hentai2read.com";
}
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {
LOGGER.info("Page contains albums");
Pattern pat = Pattern.compile("https?://hentai2read\\.com/([a-zA-Z0-9_-]*)/?");
Matcher mat = pat.matcher(url.toExternalForm());
if (mat.matches()) {
return true;
}
return false;
}
@Override
public List<String> getAlbumsToQueue(Document doc) {
List<String> urlsToAddToQueue = new ArrayList<>();
for (Element elem : doc.select(".nav-chapters > li > div.media > a")) {
urlsToAddToQueue.add(elem.attr("href"));
}
return urlsToAddToQueue;
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://hentai2read\\.com/([a-zA-Z0-9_-]*)/(\\d+)?/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1) + "_" + m.group(2);
}
throw new MalformedURLException("Expected hentai2read.com URL format: " +
"hentai2read.com/COMICID - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
String thumbnailLink;
try {
// If the page contains albums we want to load the main page
if (pageContainsAlbums(url)) {
return Http.url(url).get();
}
Document tempDoc;
tempDoc = Http.url(url).get();
// Get the thumbnail page so we can rip all images without loading every page in the comic
thumbnailLink = tempDoc.select("div.col-xs-12 > div.reader-controls > div.controls-block > button > a").attr("href");
if (!thumbnailLink.equals("")) {
return Http.url(thumbnailLink).get();
} else {
return Http.url(tempDoc.select("a[data-original-title=Thumbnails").attr("href")).get();
}
} catch (IOException e) {
throw new IOException("Unable to get first page");
}
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<String>();
for (Element el : doc.select("div.block-content > div > div.img-container > a > img.img-responsive")) {
String imageURL = "https:" + el.attr("src");
imageURL = imageURL.replace("hentaicdn.com", "static.hentaicdn.com");
imageURL = imageURL.replace("thumbnails/", "");
imageURL = imageURL.replace("tmb", "");
result.add(imageURL);
}
return result;
}
@Override
public Document getNextPage(Document doc) throws IOException {
// Find next page
String nextUrl = "";
Element elem = doc.select("div.bg-white > ul.pagination > li > a").last();
if (elem == null) {
throw new IOException("No more pages");
}
nextUrl = elem.attr("href");
// We use the global lastPage to check if we've already ripped this page
// and is so we quit as there are no more pages
if (nextUrl.equals(lastPage)) {
throw new IOException("No more pages");
}
lastPage = nextUrl;
// Sleep for half a sec to avoid getting IP banned
sleep(500);
return Http.url(nextUrl).get();
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
try {
return getHost() + "_" + getGID(url);
} catch (Exception e) {
// Fall back to default album naming convention
LOGGER.warn("Failed to get album title from " + url, e);
}
return super.getAlbumTitle(url);
| 1,185
| 77
| 1,262
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/HentaiCafeRipper.java
|
HentaiCafeRipper
|
getURLsFromPage
|
class HentaiCafeRipper extends AbstractHTMLRipper {
public HentaiCafeRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "hentai";
}
@Override
public String getDomain() {
return "hentai.cafe";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://hentai\\.cafe/([a-zA-Z0-9_\\-%]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected hentai.cafe URL format: " +
"hentai.cafe/COMIC - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
Document tempDoc = Http.url(url).get();
String firstPageUrl = tempDoc.select("div.last > p > a.x-btn").attr("href");
// workaround for https://github.com/RipMeApp/ripme/issues/1083
if (firstPageUrl.contains("<br />")) {
firstPageUrl = firstPageUrl.replaceAll("<br />", "");
}
return Http.url(firstPageUrl).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
String nextPageURL = doc.select("div[id=page] > div.inner > a").attr("href");
int totalPages = Integer.parseInt(doc.select("div.panel > div.topbar > div > div.topbar_right > div.tbtitle > div.text").text().replace(" ⤵", ""));
String[] nextPageURLSplite = nextPageURL.split("/");
// This checks if the next page number is greater than the total number of pages
if (totalPages >= Integer.parseInt(nextPageURLSplite[nextPageURLSplite.length -1])) {
return Http.url(nextPageURL).get();
}
throw new IOException("No more pages");
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
result.add(doc.select("div[id=page] > div.inner > a > img.open").attr("src"));
return result;
| 665
| 51
| 716
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/HentaiNexusRipper.java
|
HentaiNexusRipper
|
decodeJsonString
|
class HentaiNexusRipper extends AbstractJSONRipper {
public HentaiNexusRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "hentainexus";
}
@Override
public String getDomain() {
return "hentainexus.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
/*
Valid URLs are /view/id, /read/id and those 2 with #pagenumber
https://hentainexus.com/view/9202
https://hentainexus.com/read/9202
https://hentainexus.com/view/9202#001
https://hentainexus.com/read/9202#001
*/
Pattern p = Pattern.compile("^https?://hentainexus\\.com/(?:view|read)/([0-9]+)(?:\\#[0-9]+)*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected hentainexus.com URL format: " +
"hentainexus.com/view/id OR hentainexus.com/read/id - got " + url + "instead");
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
@Override
protected List<String> getURLsFromJSON(JSONObject json) throws JSONException {
List<String> urlList = new ArrayList<>();
JSONArray imagesList = json.getJSONArray("f");
String host = json.getString("b");
String folder = json.getString("r");
String id = json.getString("i");
for (Object singleImage : imagesList) {
String hashTMP = ((JSONObject) singleImage).getString("h");
String fileNameTMP = ((JSONObject) singleImage).getString("p");
String imageUrlTMP = String.format("%s%s%s/%s/%s",host,folder,hashTMP,id,fileNameTMP);
urlList.add(imageUrlTMP);
}
return urlList;
}
@Override
protected JSONObject getFirstPage() throws IOException {
String jsonEncodedString = getJsonEncodedStringFromPage();
String jsonDecodedString = decodeJsonString(jsonEncodedString);
return new JSONObject(jsonDecodedString);
}
public String getJsonEncodedStringFromPage() throws MalformedURLException, IOException
{
// Image data only appears on the /read/ page and not on the /view/ one.
URL readUrl = new URL(String.format("http://hentainexus.com/read/%s",getGID(url)));
Document document = Http.url(readUrl).response().parse();
for (Element scripts : document.getElementsByTag("script")) {
for (DataNode dataNode : scripts.dataNodes()) {
if (dataNode.getWholeData().contains("initReader")) {
// Extract JSON encoded string from the JavaScript initReader() call.
String data = dataNode.getWholeData().trim().replaceAll("\\r|\\n|\\t","");
Pattern p = Pattern.compile(".*?initReader\\(\"(.*?)\",.*?\\).*?");
Matcher m = p.matcher(data);
if (m.matches()) {
return m.group(1);
}
}
}
}
return "";
}
public String decodeJsonString(String jsonEncodedString)
{<FILL_FUNCTION_BODY>}
private static long signedToUnsigned(int signed) {
return (byte) signed & 0xFF;
}
}
|
/*
The initReader() JavaScript function accepts 2 parameters: a weird string and the window title (we can ignore this).
The weird string is a JSON string with some bytes shifted and swapped around and then encoded in base64.
The following code is a Java adaptation of the initRender() JavaScript function after manual deobfuscation.
*/
byte[] jsonBytes = Base64.getDecoder().decode(jsonEncodedString);
ArrayList unknownArray = new ArrayList();
ArrayList<Integer> indexesToUse = new ArrayList<>();
for (int i = 0x2; unknownArray.size() < 0x10; ++i) {
if (!indexesToUse.contains(i)) {
unknownArray.add(i);
for (int j = i << 0x1; j <= 0x100; j += i) {
if (!indexesToUse.contains(j)) {
indexesToUse.add(j);
}
}
}
}
byte magicByte = 0x0;
for (int i = 0x0; i < 0x40; i++) {
magicByte = (byte) (signedToUnsigned(magicByte) ^ signedToUnsigned(jsonBytes[i]));
for (int j = 0x0; j < 0x8; j++) {
long unsignedMagicByteTMP = signedToUnsigned(magicByte);
magicByte = (byte) ((unsignedMagicByteTMP & 0x1) == 1 ? unsignedMagicByteTMP >>> 0x1 ^ 0xc : unsignedMagicByteTMP >>> 0x1);
}
}
magicByte = (byte) (magicByte & 0x7);
ArrayList<Integer> newArray = new ArrayList();
for (int i = 0x0; i < 0x100; i++) {
newArray.add(i);
}
int newIndex = 0, backup = 0;
for (int i = 0x0; i < 0x100; i++) {
newIndex = (newIndex + newArray.get(i) + (int) signedToUnsigned(jsonBytes[i % 0x40])) % 0x100;
backup = newArray.get(i);
newArray.set(i, newArray.get(newIndex));
newArray.set(newIndex, backup);
}
int magicByteTranslated = (int) unknownArray.get(magicByte);
int index1 = 0x0, index2 = 0x0, index3 = 0x0, swap1 = 0x0, xorNumber = 0x0;
String decodedJsonString = "";
for (int i = 0x0; i + 0x40 < jsonBytes.length; i++) {
index1 = (index1 + magicByteTranslated) % 0x100;
index2 = (index3 + newArray.get((index2 + newArray.get(index1)) % 0x100)) % 0x100;
index3 = (index3 + index1 + newArray.get(index1)) % 0x100;
swap1 = newArray.get(index1);
newArray.set(index1, newArray.get(index2));
newArray.set(index2,swap1);
xorNumber = newArray.get((index2 + newArray.get((index1 + newArray.get((xorNumber + index3) % 0x100)) % 0x100)) % 0x100);
decodedJsonString += Character.toString((char) signedToUnsigned((jsonBytes[i + 0x40] ^ xorNumber)));
}
return decodedJsonString;
| 1,019
| 936
| 1,955
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/HentaidudeRipper.java
|
HentaidudeDownloadThread
|
getVideoUrl
|
class HentaidudeDownloadThread extends Thread {
private URL url;
public HentaidudeDownloadThread(URL url, int index) {
this.url = url;
// this.index = index;
}
@Override
public void run() {
try {
Document doc = Http.url(url).get();
URL videoSourceUrl = new URL(getVideoUrl(doc));
addURLToDownload(videoSourceUrl, "", "", "", null, getVideoName(), "mp4");
} catch (Exception e) {
LOGGER.error("Could not get video url for " + getVideoName(), e);
}
}
private String getVideoName() {
try {
return getGID(url);
} catch (MalformedURLException e) {
LOGGER.error("Unable to get video title from " + url.toExternalForm());
e.printStackTrace();
}
return "unknown";
}
/*
* TO find data object: $.ajax({ url:
* 'https://hentaidude.com/wp-admin/admin-ajax.php', type: 'post', data: {
* action: 'msv-get-sources', id: '48227', nonce: '907f1bd45c' }
*/
public String getVideoUrl(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
}
|
String jsonString = null;
Matcher m = p2.matcher(doc.html());
while (m.find()) {
jsonString = m.group(1);
if (jsonString.contains("msv-get-sources"))
break;
}
if (jsonString != null) {
// send POST request to https://hentaidude.com/wp-admin/admin-ajax.php with the
// data object parameters.
JSONObject dataObject = new JSONObject(jsonString);
Map<String, String> dataMap = new HashMap<>();
for (String key : JSONObject.getNames(dataObject)) {
dataMap.put(key, dataObject.getString(key));
}
JSONObject jsonResopnse = Http.url("https://hentaidude.com/wp-admin/admin-ajax.php").data(dataMap)
.method(Method.POST).getJSON();
// return source url from below JSON.
/*
* success true sources { video-source-0
* https://cdn1.hentaidude.com/index.php?data=
* 2f4a576957694872754d6736466f6c585579704b4d584e4a434372546c51346d4f4c697a6c734f6678307a59324c5458624f4675664863323768397a3371452f41384b62375246643243466f744447536b2b6250565a3859306a41506d366942713066336c6659386d78513d
* video-source-1 <iframe src="https://openload.co/embed/iaJ_zDCTW0M/"
* scrolling="no" frameborder="0" width="100%" height="430"
* allowfullscreen="true" webkitallowfullscreen="true"
* mozallowfullscreen="true"></iframe> }
*/
if (jsonResopnse.getBoolean("success")) {
// get the hentaidude video source
for (String key : JSONObject.getNames(jsonResopnse.getJSONObject("sources"))) {
if (jsonResopnse.getJSONObject("sources").getString(key).contains("hentaidude.com")) {
return jsonResopnse.getJSONObject("sources").getString(key);
}
}
} else {
throw new IOException("Could not get video url from JSON response.");
}
}
throw new IOException("Could not get video download url.");
| 356
| 752
| 1,108
|
<methods>public int getCompletionPercentage() ,public java.lang.String getStatusText() ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public boolean useByteProgessBar() <variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/HentaifoxRipper.java
|
HentaifoxRipper
|
getGID
|
class HentaifoxRipper extends AbstractHTMLRipper {
public HentaifoxRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "hentaifox";
}
@Override
public String getDomain() {
return "hentaifox.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
LOGGER.info(doc);
List<String> result = new ArrayList<>();
for (Element el : doc.select("div.preview_thumb > a > img")) {
String imageSource = "https:" + el.attr("data-src").replaceAll("t\\.jpg", ".jpg");
result.add(imageSource);
}
return result;
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
try {
Document doc = getFirstPage();
String title = doc.select("div.info > h1").first().text();
return getHost() + "_" + title + "_" + getGID(url);
} catch (Exception e) {
// Fall back to default album naming convention
LOGGER.warn("Failed to get album title from " + url, e);
}
return super.getAlbumTitle(url);
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("https://hentaifox.com/gallery/([\\d]+)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected hentaifox URL format: " +
"https://hentaifox.com/gallery/ID - got " + url + " instead");
| 462
| 120
| 582
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/HentaiimageRipper.java
|
HentaiimageRipper
|
getGID
|
class HentaiimageRipper extends AbstractHTMLRipper {
public HentaiimageRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return url.toExternalForm().split("/")[2];
}
@Override
public String getDomain() {
return url.toExternalForm().split("/")[2];
}
@Override
public boolean canRip(URL url) {
try {
getGID(url);
return true;
} catch (MalformedURLException e) {
return false;
}
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select("div.icon-overlay > a > img")) {
result.add(el.attr("src"));
}
return result;
}
@Override
public Document getNextPage(Document doc) throws IOException {
for (Element el : doc.select("div[id=paginator] > span")) {
if (el.select("a").text().equals("next>")) {
return Http.url("https://" + getDomain() + el.select("a").attr("href")).get();
}
}
throw new IOException("No more pages");
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("https://(?:\\w\\w\\.)?hentai-(image|comic).com/image/([a-zA-Z0-9_-]+)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected hitomi URL format: " +
"https://hentai-image.com/image/ID - got " + url + " instead");
| 469
| 135
| 604
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/HitomiRipper.java
|
HitomiRipper
|
getAlbumTitle
|
class HitomiRipper extends AbstractHTMLRipper {
private String galleryId = "";
public HitomiRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "hitomi";
}
@Override
public String getDomain() {
return "hitomi.la";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https://hitomi.la/galleries/([\\d]+).html");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
galleryId = m.group(1);
return m.group(1);
}
throw new MalformedURLException("Expected hitomi URL format: " +
"https://hitomi.la/galleries/ID.html - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// if we go to /GALLERYID.js we get a nice json array of all images in the gallery
return Http.url(new URL(url.toExternalForm().replaceAll("hitomi", "ltn.hitomi").replaceAll(".html", ".js"))).ignoreContentType().get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
String json = doc.text().replaceAll("var galleryinfo =", "");
JSONArray json_data = new JSONArray(json);
for (int i = 0; i < json_data.length(); i++) {
result.add("https://ba.hitomi.la/galleries/" + galleryId + "/" + json_data.getJSONObject(i).getString("name"));
}
return result;
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
try {
// Attempt to use album title and username as GID
Document doc = Http.url(url).get();
return getHost() + "_" + getGID(url) + "_" +
doc.select("title").text().replaceAll(" - Read Online - hentai artistcg \\| Hitomi.la", "");
} catch (IOException e) {
LOGGER.info("Falling back");
}
return super.getAlbumTitle(url);
| 551
| 121
| 672
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/HqpornerRipper.java
|
HqpornerDownloadThread
|
fetchVideo
|
class HqpornerDownloadThread extends Thread {
private URL hqpornerVideoPageUrl;
//private int index;
private String subdirectory;
public HqpornerDownloadThread(URL url, int index, String subdirectory) {
this.hqpornerVideoPageUrl = url;
//this.index = index;
this.subdirectory = subdirectory;
}
@Override
public void run() {
fetchVideo();
}
public void fetchVideo() {<FILL_FUNCTION_BODY>}
private String getVideoFromMyDaddycc(String videoPageUrl) {
Pattern p = Pattern.compile("(//[a-zA-Z0-9\\.]+/pub/cid/[a-z0-9]+/1080.mp4)");
try {
logger.info("Downloading from mydaddy " + videoPageUrl);
Document page = Http.url(videoPageUrl).referrer(hqpornerVideoPageUrl).get();
Matcher m = p.matcher(page.html());
logger.info(page.html());
if (m.find()) {
return "https:" + m.group(0);
}
} catch (IOException e) {
logger.error("Unable to get page with video");
}
return null;
}
private String getVideoFromFlyFlv(String videoPageUrl) {
try {
logger.info("Downloading from flyflv " + videoPageUrl);
Document page = Http.url(videoPageUrl).referrer(hqpornerVideoPageUrl).get();
String[] videoSizes = { "1080p", "720p", "360p" };
for (String videoSize : videoSizes) {
String urlToReturn = page.select("video > source[label=" + videoSize).attr("src");
if (urlToReturn != null && !urlToReturn.equals("")) {
return "https:" + urlToReturn;
}
}
} catch (IOException e) {
logger.error("Unable to get page with video");
}
return null;
}
private String getVideoFromUnknown(String videoPageurl) {
// If video host is neither daddycc or flyflv TRY generic way.
// 1. Search any src$=.mp4
// 2. Pattern match http(s)://.../../abcd.mp4
// 3. GET all src link with same host and run 2.
try {
logger.info("Trying to download from unknown video host " + videoPageurl);
URL url = new URL(videoPageurl);
Response response = Http.url(url).referrer(hqpornerVideoPageUrl).response();
Document doc = response.parse();
// 1. Search for src$=.mp4
Elements endingWithMp4 = doc.select("[src$=.mp4]");
if (!endingWithMp4.isEmpty()) {
List<String> list = new ArrayList<>();
endingWithMp4.forEach((e) -> list.add(e.attr("src")));
return getBestQualityLink(list);
}
// 2. Pattern match https?://somehost.cc/example123/abcd.mp4
String link = matchUrlByPattern(p3, doc.html());
if (link != null) {
return link;
}
// 3. GET all src link with same host and run 2.
link = null;
Elements allElementsWithSrc = doc.select("[src*=" + url.getHost() + "]"); //all urls from same host.
allElementsWithSrc = allElementsWithSrc.select("[src~=/[A-Za-z0-9_-]+$]"); // remove links with extensions( .js).
for (Element e : allElementsWithSrc) {
Document d = Http.url(e.attr("src")).referrer(url.getHost()).get();
link = matchUrlByPattern(p3, d.html());
if (link != null) {
return link;
}
}
} catch (IOException e) {
logger.error("Unable to get video url using generic methods.");
}
// RIP unknown ripper.
logger.error("Unable to get video url using generic methods.");
return null;
}
private String matchUrlByPattern(Pattern pattern, String html) {
// Step 2. function
Matcher m = pattern.matcher(html);
List<String> list = new ArrayList<>();
while (m.find()) {
list.add(m.group());
}
if (!list.isEmpty()) {
return getBestQualityLink(list);
}
return null;
}
private String getVideoName() {
try {
String filename = getGID(hqpornerVideoPageUrl);
return filename;
} catch (MalformedURLException e) {
return "1080";
}
}
}
|
try {
Document doc = Http.url(hqpornerVideoPageUrl).retries(3).get();
String downloadUrl = null;
String videoPageUrl = "https:" + doc.select("div.videoWrapper > iframe").attr("src");
if (videoPageUrl.contains("mydaddy")) {
downloadUrl = getVideoFromMyDaddycc(videoPageUrl);
} else if (videoPageUrl.contains("flyflv")) {
downloadUrl = getVideoFromFlyFlv(videoPageUrl);
} else {
//trying a generic selector to grab video url.
downloadUrl = getVideoFromUnknown(videoPageUrl);
}
if (downloadUrl != null) {
addURLToDownload(new URL(downloadUrl), "", subdirectory, "", null, getVideoName(), "mp4");
}
} catch (IOException e) {
LOGGER.error("[!] Exception while downloading video.", e);
}
| 1,319
| 248
| 1,567
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/HypnohubRipper.java
|
HypnohubRipper
|
getURLsFromPage
|
class HypnohubRipper extends AbstractHTMLRipper {
public HypnohubRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "hypnohub";
}
@Override
public String getDomain() {
return "hypnohub.net";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://hypnohub.net/\\S+/show/([\\d]+)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
p = Pattern.compile("https?://hypnohub.net/\\S+/show/([\\d]+)/([\\S]+)/?$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1) + "_" + m.group(2);
}
throw new MalformedURLException("Expected cfake URL format: " +
"hypnohub.net/pool/show/ID - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
private String ripPost(String url) throws IOException {
LOGGER.info(url);
Document doc = Http.url(url).get();
return "https:" + doc.select("img.image").attr("src");
}
private String ripPost(Document doc) {
LOGGER.info(url);
return "https:" + doc.select("img.image").attr("src");
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
if (url.toExternalForm().contains("/pool")) {
for (Element el : doc.select("ul[id=post-list-posts] > li > div > a.thumb")) {
try {
result.add(ripPost("https://hypnohub.net" + el.attr("href")));
} catch (IOException e) {
return result;
}
}
} else if (url.toExternalForm().contains("/post")) {
result.add(ripPost(doc));
}
return result;
| 544
| 147
| 691
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ImagearnRipper.java
|
ImagearnRipper
|
getAlbumTitle
|
class ImagearnRipper extends AbstractHTMLRipper {
public ImagearnRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "imagearn";
}
@Override
public String getDomain() {
return "imagearn.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^.*imagearn.com/+gallery.php\\?id=([0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected imagearn.com gallery formats: "
+ "imagearn.com/gallery.php?id=####..."
+ " Got: " + url);
}
public URL sanitizeURL(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^.*imagearn.com/+image.php\\?id=[0-9]+.*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
// URL points to imagearn *image*, not gallery
try {
url = getGalleryFromImage(url);
} catch (Exception e) {
LOGGER.error("[!] " + e.getMessage(), e);
}
}
return url;
}
private URL getGalleryFromImage(URL url) throws IOException {
Document doc = Http.url(url).get();
for (Element link : doc.select("a[href~=^gallery\\.php.*$]")) {
LOGGER.info("LINK: " + link.toString());
if (link.hasAttr("href")
&& link.attr("href").contains("gallery.php")) {
url = new URL("http://imagearn.com/" + link.attr("href"));
LOGGER.info("[!] Found gallery from given link: " + url);
return url;
}
}
throw new IOException("Failed to find gallery at URL " + url);
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
for (Element thumb : doc.select("div#gallery > div > a")) {
String imageURL = thumb.attr("href");
try {
Document imagedoc = new Http("http://imagearn.com/" + imageURL).get();
String image = imagedoc.select("a.thickbox").first().attr("href");
imageURLs.add(image);
} catch (IOException e) {
LOGGER.warn("Was unable to download page: " + imageURL);
}
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
sleep(1000);
}
}
|
try {
Document doc = getFirstPage();
String title = doc.select("h3 > strong").first().text(); // profile name
return getHost() + "_" + title + "_" + getGID(url);
} catch (Exception e) {
// Fall back to default album naming convention
LOGGER.warn("Failed to get album title from " + url, e);
}
return super.getAlbumTitle(url);
| 842
| 112
| 954
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ImagebamRipper.java
|
ImagebamRipper
|
getAlbumTitle
|
class ImagebamRipper extends AbstractHTMLRipper {
// Current HTML document
private Document albumDoc = null;
// Thread pool for finding direct image links from "image" pages (html)
private DownloadThreadPool imagebamThreadPool = new DownloadThreadPool("imagebam");
@Override
public DownloadThreadPool getThreadPool() {
return imagebamThreadPool;
}
public ImagebamRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "imagebam";
}
@Override
public String getDomain() {
return "imagebam.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p;
Matcher m;
p = Pattern.compile("^https?://[wm.]*imagebam.com/gallery/([a-zA-Z0-9]+).*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected imagebam gallery format: "
+ "http://www.imagebam.com/gallery/galleryid"
+ " Got: " + url);
}
@Override
public Document getFirstPage() throws IOException {
if (albumDoc == null) {
albumDoc = Http.url(url).get();
}
return albumDoc;
}
@Override
public Document getNextPage(Document doc) throws IOException {
// Find next page
Elements hrefs = doc.select("a.pagination_current + a.pagination_link");
if (hrefs.isEmpty()) {
throw new IOException("No more pages");
}
String nextUrl = "http://www.imagebam.com" + hrefs.first().attr("href");
sleep(500);
return Http.url(nextUrl).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
for (Element thumb : doc.select("div > a[target=_blank]:not(.footera)")) {
imageURLs.add(thumb.attr("href"));
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
ImagebamImageThread t = new ImagebamImageThread(url, index);
imagebamThreadPool.addThread(t);
sleep(500);
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
/**
* Helper class to find and download images found on "image" pages
*
* Handles case when site has IP-banned the user.
*/
private class ImagebamImageThread extends Thread {
private URL url; //link to "image page"
private int index; //index in album
ImagebamImageThread(URL url, int index) {
super();
this.url = url;
this.index = index;
}
@Override
public void run() {
fetchImage();
}
/**
* Rips useful image from "image page"
*/
private void fetchImage() {
try {
Document doc = Http.url(url).get();
// Find image
Elements metaTags = doc.getElementsByTag("meta");
String imgsrc = "";//initialize, so no NullPointerExceptions should ever happen.
for (Element metaTag: metaTags) {
//the direct link to the image seems to always be linked in the <meta> part of the html.
if (metaTag.attr("property").equals("og:image")) {
imgsrc = metaTag.attr("content");
LOGGER.info("Found URL " + imgsrc);
break;//only one (useful) image possible for an "image page".
}
}
//for debug, or something goes wrong.
if (imgsrc.isEmpty()) {
LOGGER.warn("Image not found at " + this.url);
return;
}
// Provide prefix and let the AbstractRipper "guess" the filename
String prefix = "";
if (Utils.getConfigBoolean("download.save_order", true)) {
prefix = String.format("%03d_", index);
}
addURLToDownload(new URL(imgsrc), prefix);
} catch (IOException e) {
LOGGER.error("[!] Exception while loading/parsing " + this.url, e);
}
}
}
}
|
try {
// Attempt to use album title as GID
Elements elems = getFirstPage().select("legend");
String title = elems.first().text();
LOGGER.info("Title text: '" + title + "'");
Pattern p = Pattern.compile("^(.*)\\s\\d* image.*$");
Matcher m = p.matcher(title);
if (m.matches()) {
return getHost() + "_" + getGID(url) + " (" + m.group(1).trim() + ")";
}
LOGGER.info("Doesn't match " + p.pattern());
} catch (Exception e) {
// Fall back to default album naming convention
LOGGER.warn("Failed to get album title from " + url, e);
}
return super.getAlbumTitle(url);
| 1,215
| 215
| 1,430
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ImagevenueRipper.java
|
ImagevenueImageThread
|
fetchImage
|
class ImagevenueImageThread extends Thread {
private URL url;
private int index;
ImagevenueImageThread(URL url, int index) {
super();
this.url = url;
this.index = index;
}
@Override
public void run() {
fetchImage();
}
private void fetchImage() {<FILL_FUNCTION_BODY>}
}
|
try {
Document doc = Http.url(url)
.retries(3)
.get();
// Find image
Elements images = doc.select("a > img");
if (images.isEmpty()) {
LOGGER.warn("Image not found at " + this.url);
return;
}
Element image = images.first();
String imgsrc = image.attr("src");
imgsrc = "http://" + this.url.getHost() + "/" + imgsrc;
// Provide prefix and let the AbstractRipper "guess" the filename
String prefix = "";
if (Utils.getConfigBoolean("download.save_order", true)) {
prefix = String.format("%03d_", index);
}
addURLToDownload(new URL(imgsrc), prefix);
} catch (IOException e) {
LOGGER.error("[!] Exception while loading/parsing " + this.url, e);
}
| 103
| 244
| 347
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ImgboxRipper.java
|
ImgboxRipper
|
getGID
|
class ImgboxRipper extends AbstractHTMLRipper {
public ImgboxRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "imgbox";
}
@Override
public String getDomain() {
return "imgbox.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
for (Element thumb : doc.select("div.boxed-content > a > img")) {
String image = thumb.attr("src").replaceAll("thumbs", "images");
image = image.replace("_b", "_o");
image = image.replaceAll("\\d-s", "i");
imageURLs.add(image);
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("^https?://[wm.]*imgbox\\.com/g/([a-zA-Z0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected imgbox.com URL format: " +
"imgbox.com/g/albumid - got " + url + "instead");
| 322
| 127
| 449
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/JabArchivesRipper.java
|
JabArchivesRipper
|
getNextPage
|
class JabArchivesRipper extends AbstractHTMLRipper {
private static final Pattern NONLATIN = Pattern.compile("[^\\w-]");
private static final Pattern WHITESPACE = Pattern.compile("[\\s]");
private Map<String, String> itemPrefixes = Collections.synchronizedMap(new HashMap<String, String>());
public JabArchivesRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "jabarchives";
}
@Override
public String getDomain() {
return "jabarchives.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://(?:www\\.)?jabarchives.com/main/view/([a-zA-Z0-9_]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
// Return the text contained between () in the regex
return m.group(1);
}
throw new MalformedURLException(
"Expected javarchives.com URL format: " +
"jabarchives.com/main/view/albumname - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
protected String getSlug(String input) {
// Get a URL/file-safe version of a string
String nowhitespace = WHITESPACE.matcher(input).replaceAll("-");
String normalized = Normalizer.normalize(nowhitespace, Form.NFD);
String slug = NONLATIN.matcher(normalized).replaceAll("");
return slug.toLowerCase(Locale.ENGLISH);
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<String>();
for (Element el : doc.select("#contentMain img")) {
String url = "https://jabarchives.com" + el.attr("src").replace("thumb", "large");
result.add(url);
String title = el.parent().attr("title");
itemPrefixes.put(url, getSlug(title) + "_");
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, itemPrefixes.get(url.toString()));
}
}
|
// Find next page
Elements hrefs = doc.select("a[title=\"Next page\"]");
if (hrefs.isEmpty()) {
throw new IOException("No more pages");
}
String nextUrl = "https://jabarchives.com" + hrefs.first().attr("href");
sleep(500);
return Http.url(nextUrl).get();
| 714
| 99
| 813
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/JagodibujaRipper.java
|
JagodibujaRipper
|
getURLsFromPage
|
class JagodibujaRipper extends AbstractHTMLRipper {
public JagodibujaRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "jagodibuja";
}
@Override
public String getDomain() {
return "jagodibuja.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://www.jagodibuja.com/([a-zA-Z0-9_-]*)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected jagodibuja.com gallery formats hwww.jagodibuja.com/Comic name/ got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
// sleep(500);
// addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
for (Element comicPageUrl : doc.select("div.gallery-icon > a")) {
// Check if the ripper has been stopped
try {
stopCheck();
} catch (IOException e) {
return result;
}
try {
sleep(500);
Document comicPage = Http.url(comicPageUrl.attr("href")).get();
Element elem = comicPage.select("span.full-size-link > a").first();
LOGGER.info("Got link " + elem.attr("href"));
try {
addURLToDownload(new URL(elem.attr("href")), "");
} catch (MalformedURLException e) {
LOGGER.warn("Malformed URL");
e.printStackTrace();
}
result.add(elem.attr("href"));
} catch (IOException e) {
LOGGER.info("Error loading " + comicPageUrl);
}
}
return result;
| 373
| 253
| 626
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/KingcomixRipper.java
|
KingcomixRipper
|
getURLsFromPage
|
class KingcomixRipper extends AbstractHTMLRipper {
public KingcomixRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "kingcomix";
}
@Override
public String getDomain() {
return "kingcomix.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https://kingcomix.com/([a-zA-Z1-9_-]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected kingcomix URL format: " +
"kingcomix.com/COMIX - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
for (Element el : doc.select("div.entry-content > p > img")) {
result.add(el.attr("src"));
}
return result;
| 347
| 57
| 404
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/LusciousRipper.java
|
LusciousRipper
|
sanitizeURL
|
class LusciousRipper extends AbstractHTMLRipper {
private static final int RETRY_COUNT = 5; // Keeping it high for read timeout exception.
private static final Pattern P = Pattern.compile("^https?:\\/\\/(?:members\\.|old\\.|www\\.)?luscious.net\\/albums\\/([-_.0-9a-zA-Z]+)\\/?");
private DownloadThreadPool lusciousThreadPool = new DownloadThreadPool("lusciousThreadPool");
public LusciousRipper(URL url) throws IOException {
super(url);
}
@Override
public String getDomain() {
return "luscious.net";
}
@Override
public String getHost() {
return "luscious";
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
Document page = Http.url(url).get();
LOGGER.info("First page is " + url);
return page;
}
@Override
public List<String> getURLsFromPage(Document page) {
List<String> urls = new ArrayList<>();
Elements urlElements = page.select("div.item.thumbnail.ic_container > a");
for (Element e : urlElements) {
urls.add(e.attr("abs:href"));
}
return urls;
}
@Override
public Document getNextPage(Document doc) throws IOException {
// luscious sends xhr requests to nextPageUrl and appends new set of images to the current page while in browser.
// Simply GET the nextPageUrl also works. Therefore, we do this...
Element nextPageElement = doc.select("div#next_page > div > a").first();
if (nextPageElement == null) {
throw new IOException("No next page found.");
}
return Http.url(nextPageElement.attr("abs:href")).get();
}
@Override
public String getGID(URL url) throws MalformedURLException {
Matcher m = P.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected luscious.net URL format: "
+ "luscious.net/albums/albumname \n members.luscious.net/albums/albumname - got " + url + " instead.");
}
@Override
public void downloadURL(URL url, int index) {
lusciousThreadPool.addThread(new LusciousDownloadThread(url, index));
}
@Override
public DownloadThreadPool getThreadPool() {
return lusciousThreadPool;
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public String normalizeUrl(String url) {
try {
return url.toString().replaceFirst(
"^https?:\\/\\/(?:members\\.|old\\.)?luscious.net", "https://www.luscious.net");
} catch (Exception e) {
LOGGER.info("Error normalizing the url.");
LOGGER.error(e);
return super.normalizeUrl(url);
}
}
public class LusciousDownloadThread extends Thread {
private URL url;
private int index;
public LusciousDownloadThread(URL url, int index) {
this.url = url;
this.index = index;
}
@Override
public void run() {
try {
Document page = Http.url(url).retries(RETRY_COUNT).get();
String downloadUrl = page.select(".icon-download").attr("abs:href");
if (downloadUrl.equals("")) {
// This is here for pages with mp4s instead of images.
downloadUrl = page.select("div > video > source").attr("src");
if (!downloadUrl.equals("")) {
throw new IOException("Could not find download url for image or video.");
}
}
//If a valid download url was found.
addURLToDownload(new URL(downloadUrl), getPrefix(index));
} catch (IOException e) {
LOGGER.error("Error downloadiong url " + url, e);
}
}
}
}
|
// Sanitizes the url removing GET parameters and convert to old api url.
// "https://old.luscious.net/albums/albumname"
try {
Matcher m = P.matcher(url.toString());
if (m.matches()) {
String sanitizedUrl = m.group();
sanitizedUrl = sanitizedUrl.replaceFirst(
"^https?:\\/\\/(?:members\\.|old\\.|www\\.)?luscious.net",
"https://old.luscious.net");
return new URL(sanitizedUrl);
}
throw new Exception("ERROR: Unable to sanitize url.");
} catch (Exception e) {
LOGGER.info("Error sanitizing the url.");
LOGGER.error(e);
return super.sanitizeURL(url);
}
| 1,122
| 220
| 1,342
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/MangadexRipper.java
|
MangadexRipper
|
getURLsFromJSON
|
class MangadexRipper extends AbstractJSONRipper {
private String chapterApiEndPoint = "https://mangadex.org/api/chapter/";
private String mangaApiEndPoint = "https://mangadex.org/api/manga/";
private boolean isSingleChapter;
private String getImageUrl(String chapterHash, String imageName, String server) {
return server + chapterHash + "/" + imageName;
}
public MangadexRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "mangadex";
}
@Override
public String getDomain() {
return "mangadex.org";
}
@Override
public boolean canRip(URL url) {
return (url.getHost().endsWith("mangadex.org"));
}
@Override
public String getGID(URL url) throws MalformedURLException {
String capID = getChapterID(url.toExternalForm());
String mangaID = getMangaID(url.toExternalForm());
if (capID != null) {
isSingleChapter=true;
return capID;
}
else
if(mangaID!=null){
isSingleChapter=false;
return mangaID;
}
throw new MalformedURLException("Unable to get chapter ID from" + url);
}
private String getChapterID(String url) {
Pattern p = Pattern.compile("https://mangadex.org/chapter/([\\d]+)/([\\d+]?)");
Matcher m = p.matcher(url);
if (m.matches()) {
return m.group(1);
}
return null;
}
private String getMangaID(String url){
Pattern p = Pattern.compile("https://mangadex.org/title/([\\d]+)/(.+)");
Matcher m = p.matcher(url);
if(m.matches()){
return m.group(1);
}
return null;
}
@Override
public JSONObject getFirstPage() throws IOException {
// Get the chapter ID
String chapterID = getChapterID(url.toExternalForm());
String mangaID = getMangaID(url.toExternalForm());
if(mangaID!=null){
return Http.url(new URL(mangaApiEndPoint+mangaID)).getJSON();
}
else
return Http.url(new URL(chapterApiEndPoint + chapterID)).getJSON();
}
@Override
protected List<String> getURLsFromJSON(JSONObject json) {<FILL_FUNCTION_BODY>}
@Override
protected void downloadURL(URL url, int index) {
// mangadex does not like rippers one bit, so we wait a good long while between requests
sleep(1000);
addURLToDownload(url, getPrefix(index));
}
}
|
if(isSingleChapter){
List<String> assetURLs = new ArrayList<>();
JSONArray currentObject;
String chapterHash;
// Server is the cdn hosting the images.
String server;
chapterHash = json.getString("hash");
server = json.getString("server");
for (int i = 0; i < json.getJSONArray("page_array").length(); i++) {
currentObject = json.getJSONArray("page_array");
assetURLs.add(getImageUrl(chapterHash, currentObject.getString(i), server));
}
return assetURLs;
}
JSONObject chaptersJSON = (JSONObject) json.get("chapter");
JSONObject temp;
Iterator<String> keys = chaptersJSON.keys();
HashMap<Double,String> chapterIDs = new HashMap<>();
while (keys.hasNext()) {
String keyValue = (String) keys.next();
temp=(JSONObject)chaptersJSON.get(keyValue);
if(temp.getString("lang_name").equals("English")) {
chapterIDs.put(temp.getDouble("chapter"),keyValue);
}
}
List<String> assetURLs = new ArrayList<>();
JSONArray currentObject;
String chapterHash;
// Server is the cdn hosting the images.
String server;
JSONObject chapterJSON=null;
TreeMap<Double,String> treeMap = new TreeMap<>(chapterIDs);
Iterator it = treeMap.keySet().iterator();
while(it.hasNext()) {
double key =(double) it.next();
try {
chapterJSON = Http.url(new URL(chapterApiEndPoint + treeMap.get(key))).getJSON();
} catch (IOException e) {
e.printStackTrace();
}
sendUpdate(RipStatusMessage.STATUS.LOADING_RESOURCE,"chapter "+key);
chapterHash = chapterJSON.getString("hash");
server = chapterJSON.getString("server");
for (int i = 0; i < chapterJSON.getJSONArray("page_array").length(); i++) {
currentObject = chapterJSON.getJSONArray("page_array");
assetURLs.add(getImageUrl(chapterHash, currentObject.getString(i), server));
}
}
return assetURLs;
| 779
| 594
| 1,373
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ManganeloRipper.java
|
ManganeloRipper
|
getURLsFromPage
|
class ManganeloRipper extends AbstractHTMLRipper {
public ManganeloRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "manganelo";
}
@Override
public String getDomain() {
return "manganelo.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://manganelo.com/manga/([\\S]+)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
p = Pattern.compile("https?://manganelo.com/chapter/([\\S]+)/([\\S_\\-]+)/?$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected manganelo URL format: " +
"/manganelo.com/manga/ID - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
Element elem = doc.select("div.btn-navigation-chap > a.back").first();
if (elem == null) {
throw new IOException("No more pages");
} else {
return Http.url(elem.attr("href")).get();
}
}
private List<String> getURLsFromChap(String url) {
List<String> result = new ArrayList<>();
try {
Document doc = Http.url(url).get();
return getURLsFromChap(doc);
} catch (IOException e) {
return null;
}
}
private List<String> getURLsFromChap(Document doc) {
LOGGER.debug("Getting urls from " + doc.location());
List<String> result = new ArrayList<>();
for (Element el : doc.select(".vung-doc > img")) {
result.add(el.attr("src"));
}
return result;
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
List<String> urlsToGrab = new ArrayList<>();
if (url.toExternalForm().contains("/manga/")) {
for (Element el : doc.select("div.chapter-list > div.row > span > a")) {
urlsToGrab.add(el.attr("href"));
}
Collections.reverse(urlsToGrab);
for (String url : urlsToGrab) {
result.addAll(getURLsFromChap(url));
}
} else if (url.toExternalForm().contains("/chapter/")) {
result.addAll(getURLsFromChap(doc));
}
return result;
| 688
| 185
| 873
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/MastodonRipper.java
|
MastodonRipper
|
getURLsFromPage
|
class MastodonRipper extends AbstractHTMLRipper {
private Map<String, String> itemIDs = Collections.synchronizedMap(new HashMap<String, String>());
public MastodonRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "mastodon";
}
@Override
public String getDomain() {
return "mastodon.social";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://(" + getDomain() + ")/@([a-zA-Z0-9_-]+)(/media/?)?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
// Return the text contained between () in the regex
return m.group(1) + "@" + m.group(2);
}
throw new MalformedURLException(
"Expected " + getDomain() + " URL format: " +
getDomain() + "/@username - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
Pattern p = Pattern.compile("^/@[a-zA-Z0-9_-]+/media/?$");
Matcher m = p.matcher(url.getPath());
if (m.matches()) {
return Http.url(url).get();
}
return Http.url(url.toExternalForm().replaceAll("/$", "") + "/media").get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
Elements hrefs = doc.select(".h-entry + .entry > a.load-more.load-gap");
if (hrefs.isEmpty()) {
throw new IOException("No more pages");
}
String nextUrl = hrefs.last().attr("href");
sleep(500);
return Http.url(nextUrl).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, itemIDs.get(url.toString()) + "_");
}
}
|
List<String> result = new ArrayList<String>();
for (Element el : doc.select("[data-component=\"MediaGallery\"]")) {
String props = el.attr("data-props");
JSONObject obj = new JSONObject(props);
JSONArray arr = obj.getJSONArray("media");
for (int i = 0; i < arr.length(); i++) {
String url = arr.getJSONObject(i).getString("url");
result.add(url);
String id = arr.getJSONObject(i).getString("id");
itemIDs.put(url, id);
}
}
return result;
| 606
| 165
| 771
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/MeituriRipper.java
|
MeituriRipper
|
getURLsFromPage
|
class MeituriRipper extends AbstractHTMLRipper {
public MeituriRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "meituri";
}
@Override
public String getDomain() {
return "meituri.com";
}
// To use in getting URLs
String albumID = "";
@Override
public String getGID(URL url) throws MalformedURLException {
// without escape
// ^https?://[w.]*meituri\.com/a/([0-9]+)/([0-9]+\.html)*$
// https://www.meituri.com/a/14449/
// also matches https://www.meituri.com/a/14449/3.html etc.
// group 1 is 14449
Pattern p = Pattern.compile("^https?://[w.]*meituri\\.com/a/([0-9]+)/([0-9]+\\.html)*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
albumID = m.group(1);
return m.group(1);
}
throw new MalformedURLException(
"Expected meituri.com URL format: " + "meituri.com/a/albumid/ - got " + url + "instead");
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> imageURLs = new ArrayList<>();
// Get number of images from the page
// Then generate links according to that
int numOfImages = 1;
Pattern p = Pattern.compile("^<p>图片数量: ([0-9]+)P</p>$");
for (Element para : doc.select("div.tuji > p")) {
// <p>图片数量: 55P</p>
Matcher m = p.matcher(para.toString());
if (m.matches()) {
// 55
numOfImages = Integer.parseInt(m.group(1));
}
}
// Base URL: http://ii.hywly.com/a/1/albumid/imgnum.jpg
String baseURL = "http://ii.hywly.com/a/1/" + albumID + "/";
// Loop through and add images to the URL list
for (int i = 1; i <= numOfImages; i++) {
imageURLs.add(baseURL + i + ".jpg");
}
return imageURLs;
| 481
| 285
| 766
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ModelmayhemRipper.java
|
ModelmayhemRipper
|
getGID
|
class ModelmayhemRipper extends AbstractHTMLRipper {
private Map<String,String> cookies = new HashMap<>();
public ModelmayhemRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "modelmayhem";
}
@Override
public String getDomain() {
return "modelmayhem.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
// Bypass NSFW filter
cookies.put("worksafe", "0");
// "url" is an instance field of the superclass
return Http.url(url).cookies(cookies).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select("tr.a_pics > td > div > a")) {
String image_URL = el.select("img").attr("src").replaceAll("_m", "");
if (image_URL.contains("http")) {
result.add(image_URL);
}
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("https?://www\\.modelmayhem\\.com/portfolio/(\\d+)/viewall");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected modelmayhem URL format: " +
"modelmayhem.com/portfolio/ID/viewall - got " + url + " instead");
| 372
| 120
| 492
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ModelxRipper.java
|
ModelxRipper
|
getGID
|
class ModelxRipper extends AbstractHTMLRipper {
public ModelxRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "modelx";
}
@Override
public String getDomain() {
return "modelx.org";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document page) {
List<String> result = new ArrayList<>();
for (Element el : page.select(".gallery-icon > a")) {
result.add(el.attr("href"));
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("^.*modelx.org/.*/(.+)$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected URL format: http://www.modelx.org/[category (one or more)]/xxxxx got: " + url);
| 267
| 106
| 373
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/MotherlessRipper.java
|
MotherlessRipper
|
getGID
|
class MotherlessRipper extends AbstractHTMLRipper {
// All sleep times are in milliseconds
private static final int IMAGE_SLEEP_TIME = 1000;
private static final String DOMAIN = "motherless.com",
HOST = "motherless";
private DownloadThreadPool motherlessThreadPool;
public MotherlessRipper(URL url) throws IOException {
super(url);
motherlessThreadPool = new DownloadThreadPool();
}
@Override
public boolean canRip(URL url) {
try {
getGID(url);
} catch (Exception e) {
return false;
}
return url.getHost().endsWith(DOMAIN);
}
@Override
protected String getDomain() {
return DOMAIN;
}
@Override
protected Document getFirstPage() throws IOException {
URL firstURL = this.url;
String path = this.url.getPath();
// Check if "All Uploads" (/GMxxxx), Image (/GIxxxx) or Video (/GVxxxx) gallery since there's no "next" after the homepage (/Gxxxx)
Pattern p = Pattern.compile("[MIV]");
Matcher m = p.matcher(String.valueOf(path.charAt(2)));
boolean notHome = m.matches();
// If it's the homepage go to the "All Uploads" gallery (/Gxxxxx -> /GMxxxxx)
if (!notHome) {
StringBuilder newPath = new StringBuilder(path);
newPath.insert(2, "M");
firstURL = new URL(this.url, "https://" + DOMAIN + newPath);
LOGGER.info("Changed URL to " + firstURL);
}
return Http.url(firstURL).referrer("https://motherless.com").get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
Elements nextPageLink = doc.head().select("link[rel=next]");
if (nextPageLink.isEmpty()) {
throw new IOException("Last page reached");
} else {
String referrerLink = doc.head().select("link[rel=canonical]").first().attr("href");
URL nextURL = new URL(this.url, nextPageLink.first().attr("href"));
return Http.url(nextURL).referrer(referrerLink).get();
}
}
@Override
protected List<String> getURLsFromPage(Document page) {
List<String> pageURLs = new ArrayList<>();
for (Element thumb : page.select("div.thumb-container a.img-container")) {
if (isStopped()) {
break;
}
String thumbURL = thumb.attr("href");
if (thumbURL.contains("pornmd.com")) {
continue;
}
String url;
if (!thumbURL.startsWith("http")) {
url = "https://" + DOMAIN + thumbURL;
} else {
url = thumbURL;
}
pageURLs.add(url);
if (isThisATest()) {
break;
}
}
return pageURLs;
}
@Override
protected void downloadURL(URL url, int index) {
// Create thread for finding image at "url" page
MotherlessImageThread mit = new MotherlessImageThread(url, index);
motherlessThreadPool.addThread(mit);
try {
Thread.sleep(IMAGE_SLEEP_TIME);
} catch (InterruptedException e) {
LOGGER.warn("Interrupted while waiting to load next image", e);
}
}
@Override
public String getHost() {
return HOST;
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
/**
* Helper class to find and download images found on "image" pages
*/
private class MotherlessImageThread extends Thread {
private URL url;
private int index;
MotherlessImageThread(URL url, int index) {
super();
this.url = url;
this.index = index;
}
@Override
public void run() {
try {
if (isStopped() && !isThisATest()) {
return;
}
String u = this.url.toExternalForm();
Document doc = Http.url(u)
.referrer(u)
.get();
Pattern p = Pattern.compile("^.*__fileurl = '([^']+)';.*$", Pattern.DOTALL);
Matcher m = p.matcher(doc.outerHtml());
if (m.matches()) {
String file = m.group(1);
String prefix = "";
if (Utils.getConfigBoolean("download.save_order", true)) {
prefix = String.format("%03d_", index);
}
addURLToDownload(new URL(file), prefix);
} else {
LOGGER.warn("[!] could not find '__fileurl' at " + url);
}
} catch (IOException e) {
LOGGER.error("[!] Exception while loading/parsing " + this.url, e);
}
}
}
}
|
Pattern p = Pattern.compile("^https?://(www\\.)?motherless\\.com/G([MVI]?[A-F0-9]{6,8}).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(m.groupCount());
}
p = Pattern.compile("^https?://(www\\.)?motherless\\.com/term/(images/|videos/)([a-zA-Z0-9%]+)$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(m.groupCount());
}
p = Pattern.compile("^https?://(www\\.)?motherless\\.com/g[iv]/([a-zA-Z0-9%\\-_]+)$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(m.groupCount());
}
throw new MalformedURLException("Expected URL format: https://motherless.com/GIXXXXXXX, got: " + url);
| 1,383
| 301
| 1,684
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/MyhentaicomicsRipper.java
|
MyhentaicomicsRipper
|
getNextPage
|
class MyhentaicomicsRipper extends AbstractHTMLRipper {
private static boolean isTag;
public MyhentaicomicsRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "myhentaicomics";
}
@Override
public String getDomain() {
return "myhentaicomics.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://myhentaicomics.com/index.php/([a-zA-Z0-9-]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
Pattern pa = Pattern.compile("^https?://myhentaicomics.com/index.php/search\\?q=([a-zA-Z0-9-]*)([a-zA-Z0-9=&]*)?$");
Matcher ma = pa.matcher(url.toExternalForm());
if (ma.matches()) {
return ma.group(1);
}
Pattern pat = Pattern.compile("^https?://myhentaicomics.com/index.php/tag/([0-9]*)/?([a-zA-Z%0-9+?=:]*)?$");
Matcher mat = pat.matcher(url.toExternalForm());
if (mat.matches()) {
return mat.group(1);
}
throw new MalformedURLException("Expected myhentaicomics.com URL format: " +
"myhentaicomics.com/index.php/albumName - got " + url + " instead");
}
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {
Pattern pa = Pattern.compile("^https?://myhentaicomics.com/index.php/search\\?q=([a-zA-Z0-9-]*)([a-zA-Z0-9=&]*)?$");
Matcher ma = pa.matcher(url.toExternalForm());
if (ma.matches()) {
return true;
}
Pattern pat = Pattern.compile("^https?://myhentaicomics.com/index.php/tag/([0-9]*)/?([a-zA-Z%0-9+?=:]*)?$");
Matcher mat = pat.matcher(url.toExternalForm());
if (mat.matches()) {
isTag = true;
return true;
}
return false;
}
@Override
public List<String> getAlbumsToQueue(Document doc) {
List<String> urlsToAddToQueue = new ArrayList<>();
for (Element elem : doc.select(".g-album > a")) {
urlsToAddToQueue.add(getDomain() + elem.attr("href"));
}
return urlsToAddToQueue;
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select("img")) {
String imageSource = el.attr("src");
// This bool is here so we don't try and download the site logo
if (!imageSource.startsWith("http://") && !imageSource.startsWith("https://")) {
// We replace thumbs with resizes so we can the full sized images
imageSource = imageSource.replace("thumbs", "resizes");
result.add("https://myhentaicomics.com" + imageSource);
}
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
// Find next page
String nextUrl = "";
Element elem = doc.select("a.ui-icon-right").first();
String nextPage = elem.attr("href");
Pattern p = Pattern.compile("/index.php/[a-zA-Z0-9_-]*\\?page=\\d");
Matcher m = p.matcher(nextPage);
if (m.matches()) {
nextUrl = "https://myhentaicomics.com" + m.group(0);
}
if (nextUrl.equals("")) {
throw new IOException("No more pages");
}
// Sleep for half a sec to avoid getting IP banned
sleep(500);
return Http.url(nextUrl).get();
| 1,122
| 192
| 1,314
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/MyhentaigalleryRipper.java
|
MyhentaigalleryRipper
|
getURLsFromPage
|
class MyhentaigalleryRipper extends AbstractHTMLRipper {
public MyhentaigalleryRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "myhentaigallery";
}
@Override
public String getDomain() {
return "myhentaigallery.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https://myhentaigallery.com/gallery/thumbnails/([0-9]+)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected myhentaicomics.com URL format: "
+ "myhentaigallery.com/gallery/thumbnails/ID - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
for (Element el : doc.select(".comic-thumb > img")) {
String imageSource = el.attr("src");
// We replace thumbs with resizes so we can the full sized images
imageSource = imageSource.replace("thumbnail", "original");
result.add(imageSource);
}
return result;
| 383
| 97
| 480
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.