file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
TripsController.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/controller/TripsController.java | package com.code.rts.controller;
import com.code.rts.Result.Result;
import com.code.rts.entity.Trips;
import com.code.rts.entity.User;
import com.code.rts.service.TripsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 查询车票
* */
@RestController
@CrossOrigin
public class TripsController {
/**
*
*/
@Resource
private TripsService tripsService;
@PostMapping("/getAimtrips")
@ResponseBody
public Result getAimtrips(@RequestBody Trips trips){
Result result = tripsService.getAimtrips(trips);
return result;
}
@PostMapping("/getalltrips")
@ResponseBody
public Result getAlltrips(@RequestBody Trips trips){
Result result = tripsService.getAlltrips(trips);
return result;
}
/**
* 得到分页用户
* @param pn
* @return
*/
@GetMapping("/getalltripsforadmin")
public Map<String, Object> getAllTripsForAdmin(@RequestParam(defaultValue="1",required=true,value="pn") Integer pn){
//每页显示记录数
Integer pageSize=5;
//分页查询,注意顺序,startPage()方法放前面
PageHelper.startPage(pn, pageSize);
//获取所用用户信息
List<Trips> allTrip = tripsService.getAllTripsForAdmin();
//使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行了。封装了详细的分页信息,传入连续显示的页数
PageInfo<Trips> pageInfo=new PageInfo(allTrip);
Map<String, Object> modelMap = new HashMap<>();
if (pageInfo != null){
modelMap.put("code", 200);
modelMap.put("data", pageInfo);
}else {
modelMap.put("code", 200);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("message", "获取model列表失败");
dataMap.put("entity", null);
modelMap.put("data", dataMap);
}
return modelMap;
}
/**
* 保存车次信息
* @param trips
* @return
*/
@Transactional
@RequestMapping(value = "/saveTrip",method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> saveUser(@RequestBody Trips trips){
int i = tripsService.saveTrip(trips);
Map<String, Object> modelMap = new HashMap<>();
if (i == 1){
modelMap.put("code", 200);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("message", "success");
dataMap.put("entity", null);
modelMap.put("data", dataMap);
}else {
modelMap.put("code", 200);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("message", "添加车次失败");
dataMap.put("entity", null);
modelMap.put("data", dataMap);
}
return modelMap;
}
/**
* 修改用户信息
*/
@RequestMapping(value = "/updateTripForAdmin",method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> updateTripForAdmin(@RequestBody Trips trips){
int i = tripsService.updateTripForAdmin(trips);
Map<String, Object> modelMap = new HashMap<>();
if (i == 1){
modelMap.put("code", 200);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("message", "success");
dataMap.put("entity", null);
modelMap.put("data", dataMap);
}else {
modelMap.put("code", 200);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("message", "更新车次信息失败");
dataMap.put("entity", null);
modelMap.put("data", dataMap);
}
return modelMap;
}
/**
* 根据id删除车次
*/
@Transactional
@RequestMapping(value = "/deleteTrip/{id}",method = RequestMethod.DELETE)
@ResponseBody
public Map<String, Object> deleteTrip(@PathVariable("id")Integer id){
Map<String, Object> modelMap = new HashMap<>();
try {
int i = tripsService.delTrip(id);
if (i == 1){
modelMap.put("code", 200);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("message", "success");
dataMap.put("entity", null);
modelMap.put("data", dataMap);
}else {
modelMap.put("code", 200);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("message", "删除失败");
dataMap.put("entity", null);
modelMap.put("data", dataMap);
}
}catch (Exception e){
modelMap.put("code", 500);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("message", "删除失败");
dataMap.put("entity", null);
modelMap.put("data", dataMap);
}
return modelMap;
}
}
| 5,229 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
Result.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/Result/Result.java | package com.code.rts.Result;
/**
* 数据传输类
*/
public class Result {
private int stateCode;
private Object data;
private String msg;
public Result(){
}
public int getStateCode() {
return stateCode;
}
public void setStateCode(int stateCode) {
this.stateCode = stateCode;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
| 595 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
Admin.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/entity/Admin.java | package com.code.rts.entity;
import lombok.Getter;
import lombok.Setter;
/**
*
* 用于存储管理员账号信息
*/
@Getter
@Setter
public class Admin {
private int id;
private String username;
private String password;
}
| 242 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
Trips.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/entity/Trips.java | package com.code.rts.entity;
import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;
/**
* 用于查询车票信息
* */
@Getter
@Setter
public class Trips {
private int id;
private String orginLocation;
private String destinationLocation;
@DateTimeFormat(pattern="hh:mm:ss")
private String startTime;
@DateTimeFormat(pattern="hh:mm:ss")
private String reachTime;
private String spanDays;
private String carNum;
private Double ticketPrice;
private int ticketNum;
}
| 563 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
OrderReturn.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/entity/OrderReturn.java | package com.code.rts.entity;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class OrderReturn {
private Integer id;
private String orginLocation;
private String destinationLocation;
// @DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss")
private String startTime;
// @DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss")
private String reachTime;
private String carNum;
private int ticketPrice;
private int ticketNum;
private String trueName;
private String idCardNum;
private String phoneNum;
private String status;
}
| 592 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
User.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/entity/User.java | package com.code.rts.entity;
import lombok.Getter;
import lombok.Setter;
/**
* 用户注册信息pojo
* 用于存储用户账号信息
*/
@Getter
@Setter
public class User {
private int id;
private String username;
private String password;
private String trueName;
private String idCardNum;
private String phoneNum;
private int age;
private String sex;
}
| 393 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
Order.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/entity/Order.java | package com.code.rts.entity;
import lombok.Getter;
import lombok.Setter;
/**
*查询订单信息
* */
@Getter
@Setter
public class Order {
private int id;
private int carInfoId;
private int personId;
private int changeTimes;
//0是预定未付款, 1是已经支付, 2是退票
private int status;
private String stautsMsg;
}
| 364 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
Message.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/entity/Message.java | package com.code.rts.entity;
import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* 用于存储分享信息
*/
@Getter
@Setter
public class Message {
private Integer id;
private Integer fromUser;
private Integer toUser;
private String content;
//@DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss")
private String sendTime;
private Integer isRead;
}
| 458 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
TripsVia.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/entity/TripsVia.java | package com.code.rts.entity;
import lombok.Getter;
import lombok.Setter;
/**
* 途经站信息
* */
@Getter
@Setter
public class TripsVia {
private Integer id;
private String carNum;
private String stationName;
// @DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss")
private String startTime;
// @DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss")
private String reachTime;
private Integer orderNum;
}
| 435 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
Friends.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/entity/Friends.java | package com.code.rts.entity;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
/**
* 用于存储好友关系信息
*/
@Getter
@Setter
public class Friends {
private Integer id;
private Integer userA;
private Integer userB;
private Integer relaA;
private Integer relaB;
}
| 315 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
MessageService.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/service/MessageService.java | package com.code.rts.service;
import com.code.rts.Result.Result;
import com.code.rts.dao.MessageDao;
import com.code.rts.dao.UserDao;
import com.code.rts.entity.Message;
import com.code.rts.entity.User;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Service
public class MessageService {
@Resource
private MessageDao messageDao;
public int sendMessage(Message message){
return messageDao.sendMessage(message);
}
public List<Message> getReceiveMsg(Integer toUser){
return messageDao.getReceiveMsg(toUser);
}
public Message getReceiveMsgDetail(Integer id){
return messageDao.getReceiveMsgDetail(id);
}
public Integer setMsgStatus(Integer id){
return messageDao.setMsgStatus(id);
}
public Page<Message> getAllMsg(){
return messageDao.getAllMsgs();
}
public Integer updateMsg(Message message){
return messageDao.updateMsg(message);
}
public Integer deleteMsg(Integer id){
return messageDao.deleteMsg(id);
}
}
| 1,195 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
AdminService.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/service/AdminService.java | package com.code.rts.service;
import com.code.rts.Result.Result;
import com.code.rts.dao.AdminDao;
import com.code.rts.entity.Admin;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service
public class AdminService {
@Resource
private AdminDao adminDao;
public Page<Admin> getAllAdmins() {
return adminDao.getAllAdmins();
}
public int getAdminsCount() {
return adminDao.getAdminsCount();
}
public Integer deleteAdmin(Integer id) {
return adminDao.deleteAdmin(id);
}
/**
* 校验用户名
* @param username
* @return
*/
public Admin checkAdminName(String username) {
return adminDao.getAdminByUsername(username);
}
/**
* 保存用户
* @param admin
* @return
*/
public int saveAdmin(Admin admin) {
int i = adminDao.saveAdmin(admin);
return i;
}
}
| 1,035 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
LoginService.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/service/LoginService.java | package com.code.rts.service;
import com.code.rts.Result.Result;
import com.code.rts.dao.*;
import com.code.rts.entity.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service
public class LoginService {
@Resource
private UserDao userDao;
@Resource
private AdminDao adminDao;
public Result loginIn(User userData) {
Result result = new Result();
User user = userDao.getUserByUsername(userData.getUsername());
if (user == null){
result.setData(null);
result.setMsg("用户名/密码错误");
result.setStateCode(404);
return result;
}
if (!user.getPassword().equals(userData.getPassword())){
result.setMsg("用户名/密码错误");
result.setStateCode(404);
return result;
}
result.setStateCode(200);
result.setMsg("success");
result.setData(user);
return result;
}
public Result loginAdminIn(Admin adminData) {
Result result = new Result();
Admin admin = adminDao.getAdminByUsername(adminData.getUsername());
if (admin == null){
result.setData(null);
result.setMsg("用户名/密码错误");
result.setStateCode(404);
return result;
}
if (!admin.getPassword().equals(admin.getPassword())){
result.setMsg("用户名/密码错误");
result.setStateCode(404);
return result;
}
result.setStateCode(200);
result.setMsg("success");
result.setData(admin);
return result;
}
@Transactional
public Result updateUser(User userData, String newPassword) {
Result result = new Result();
User user = userDao.getUserByUsername(userData.getUsername());
if (user != null){
String oldPassword = user.getPassword();
if (userData.getPassword().equals(oldPassword)){
userData.setPassword(newPassword);
if (userDao.updateUserRegisterInfo(userData) == 1){
result.setMsg("密码修改成功");
result.setStateCode(200);
result.setData(true);
}else {
result.setData(false);
result.setStateCode(400);
result.setMsg("密码修改失败,请重新操作");
}
} else {
result.setData(false);
result.setStateCode(200);
result.setMsg("修改密码失败,旧密码错误");
}
} else {
result.setData(false);
result.setStateCode(400);
result.setMsg("密码修改失败,不存在该用户");
}
return result;
}
@Transactional
public Result registUser(User userData) {
Result result = new Result();
if (userDao.insertUserRegisterInfo(userData) == 1){
result.setMsg("regist success");
result.setStateCode(200);
result.setData(userData.getUsername());
}else {
result.setData(false);
result.setMsg("regist fail, username is exist");
result.setStateCode(200);
}
return result;
}
}
| 3,425 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
OrderService.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/service/OrderService.java | package com.code.rts.service;
import com.code.rts.Result.Result;
import com.code.rts.dao.*;
import com.code.rts.entity.*;
import com.github.pagehelper.Page;
import org.aspectj.weaver.ast.Or;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class OrderService {
@Resource
private OrderDao orderDao;
@Resource
private TripsDao tripsDao;
/**
* 得到订单状态
* @return
*/
public Page<OrderReturn> getAllOrders(){
return orderDao.getAllOrders();
}
/**
* 得到订单
* @param username
* @return
*/
public Page<OrderReturn> getOrder(String username){
return orderDao.getOrder(username);
}
// public Result getOrder(String username) {
// Result result = new Result();
// User user = new User();
// List<OrderReturn> orderReturnList = new ArrayList<OrderReturn>();
// Trips trips = new Trips();
//
// //获取订单列表
// List<Order> orderdata= orderDao.getOrder(username);
//
// if(orderdata!=null){
//
// for(Order i:orderdata){
// OrderReturn orderReturn = new OrderReturn();
// user = orderDao.getUserinfo(i.getPersonId());
// trips = tripsDao.gettrips(i.getCarInfoId());
// orderReturn.setTrueName(user.getTrueName());
// orderReturn.setIdCardNum(user.getIdCardNum());
// orderReturn.setPhoneNum(user.getPhoneNum());
// orderReturn.setCarNum(trips.getCarNum());
// orderReturn.setDestinationLocation(trips.getDestinationLocation());
// orderReturn.setOrginLocation(trips.getOrginLocation());
// orderReturn.setTicketPrice(trips.getTicketPrice());
// orderReturn.setTicketNum(trips.getTicketNum());
// orderReturn.setStartTime(trips.getStartTime());
// orderReturn.setReachTime(trips.getReachTime());
// if (i.getStatus() == 1){
// orderReturn.setStatus("已支付");
// }else if (i.getStatus() == 2){
// orderReturn.setStatus("等待支付");
// }else if (i.getStatus() == 3){
// orderReturn.setStatus("已退票");
// }
//// orderReturn.setStartTime(orderReturn.getStartTime());
//// orderReturn.setStartTime(trips.getStartTime());
// orderReturnList.add(orderReturn);
//
// }
// result.setStateCode(200);
// result.setMsg("Query succeed");
// result.setData(orderReturnList);
// }
// else{
//// result.setStateCode();
// result.setStateCode(404);
// result.setData(false);
// result.setMsg("Query failed,no order");
// }
// return result;
// }
public Result changeOrder(int orderId, int tripsId) {
Result result = null;
Order order = orderDao.getAimOrder(orderId);
Trips trips = tripsDao.gettrips(tripsId);
if(trips.getTicketNum()>0){
tripsDao.changeOldtrips(order.getCarInfoId());
tripsDao.changeNewtrips(tripsId);
orderDao.changeOrder(orderId,tripsId);
result.setStateCode(200);
result.setMsg("change order succeed");
}
else{
result.setStateCode(404);
result.setMsg("change order failed");
}
return result;
}
public int updateOrderStatus(Order order){
return orderDao.updateOrderStatus(order);
}
public Integer deleteOrder(Integer id){
return orderDao.deleteOrder(id);
}
public int saveOrderPaying(Order order){
return orderDao.saveOrderPaying(order);
}
public int saveOrderPayed(int orderId){
return orderDao.saveOrderPayed(orderId);
}
}
| 4,011 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
TripsService.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/service/TripsService.java | package com.code.rts.service;
import com.code.rts.Result.Result;
import com.code.rts.dao.OrderDao;
import com.code.rts.dao.TripsDao;
import com.code.rts.dao.UserDao;
import com.code.rts.entity.Order;
import com.code.rts.entity.Trips;
import com.code.rts.entity.User;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class TripsService {
@Resource
private OrderDao orderDao;
@Resource
private UserDao userDao;
@Resource
private TripsDao tripsDao;
public Result getAlltrips(Trips trips) {
Result result = new Result();
List<Trips> tripsdata = tripsDao.getAlltrips(trips);
if(tripsdata != null){
result.setMsg("Query all succeed");
result.setData(tripsdata);
result.setStateCode(200);
}
else{
result.setMsg("Query failes,no tickets");
result.setStateCode(404);
}
return result;
}
public Page<Trips> getAllTripsForAdmin() {
return tripsDao.getAllTripsForAdmin();
}
public Result getAimtrips(Trips trips) {
Result result = new Result();
Trips tripsdata = tripsDao.getAimtrips(trips);
if(tripsdata != null){
result.setMsg("Query all succeed");
result.setData(trips);
result.setStateCode(200);
}
else{
result.setMsg("Query failes,no tickets");
result.setStateCode(404);
}
return result;
}
@Transactional
public Result buyTicket(String username, int carInfoId, String carNum) {
Result result = new Result();
//获取用户个人信息的id
User customer = userDao.getUserByUsername(username);
if (customer.getTrueName() == null || customer.getIdCardNum() == null || customer.getPhoneNum() == null){
result.setStateCode(400);
result.setMsg("购票前请完善用户个人信息");
result.setData(false);
return result;
}
Trips trips = new Trips();
trips.setCarNum(carNum);
trips.setId(carInfoId);
//获取车票详细信息
Trips tripsInfoData = tripsDao.getTripsInfoByCarInfoIdAndId(trips);
//判断车票是否卖光了
Order order = new Order();
order.setCarInfoId(carInfoId);
order.setPersonId(customer.getId());
order.setChangeTimes(0);
order.setStatus(0);
if (tripsInfoData.getTicketNum() >= 1){
orderDao.buyTicket(order);
trips.setTicketNum(tripsInfoData.getTicketNum() - 1);
trips.setCarNum(null);
int i = tripsDao.updateTrips(trips);
Map<String, Object> detailData = new HashMap<>();
if (order.getId() > 0 && i == 1){
//还有车票,购买成功
result.setMsg("购票成功");
result.setStateCode(200);
detailData.put("customer", customer);
detailData.put("changeTimes",3 - order.getChangeTimes());
detailData.put("order", order);
result.setData(detailData);
}
return result;
}
else {
//车票卖光了,购买失败
result.setMsg(" 购买失败,车票已经卖光");
result.setStateCode(400);
result.setData(false);
return result;
}
}
@Transactional
public Result ticketRetund(int personId , String carNum, String startTime, String reachTime){
Result result = new Result();
//票数+1
int i = tripsDao.refundTrips(personId, carNum, startTime, reachTime);
//把订单状态改为退票
int j = orderDao.updateOrder1(personId, carNum, startTime, reachTime);
if (i > 0 && j > 0){
result.setData(true);
result.setMsg("退票成功");
result.setStateCode(200);
}else {
result.setData(false);
result.setMsg("退票失败");
result.setStateCode(400);
}
return result;
}
@Transactional
public Result payMoney(int orderId) {
Result result = new Result();
if(orderDao.updateOrder(orderId) == 1){
result.setStateCode(200);
result.setMsg("支付成功");
result.setData(true);
}else {
result.setData(false);
result.setMsg("支付失败,请重新支付");
result.setStateCode(400);
}
return result;
}
/**
* 保存车次
* @param trips
* @return
*/
public int saveTrip(Trips trips) {
return tripsDao.saveTrip(trips);
}
public int updateTripForAdmin(Trips trips){
return tripsDao.updateTripForAdmin(trips);
}
public int delTrip(Integer id){
return tripsDao.deleteTrip(id);
}
}
| 5,155 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
UserService.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/service/UserService.java | package com.code.rts.service;
import com.code.rts.Result.Result;
import com.code.rts.dao.*;
import com.code.rts.entity.*;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service
public class UserService {
@Resource
private UserDao userDao;
// @Transactional
// @Override
// public Result insertUserInfo(String username, Person person) {
// Result result = new Result();
// int i = personDao.insertUserInfo(person);
// result.setMsg("update fail, please update again");
// result.setStateCode(404);
// result.setData(false);
// if (i < 1){
//
// } else {
// User user = new User();
// user.setUsername(username);
// user.setPersonId(person.getId());
// int j = userDao.updateUserRegisterInfo(user);
// if (j == 1){
// result.setMsg("update success");
// result.setStateCode(200);
// result.setData(true);
// }
// }
// return result;
// }
@Transactional
public boolean updateUser(User user) {
int i = userDao.updateUser(user);
if (i == 1){
return true;
}else {
return false;
}
}
public Result getPersonInfo(String username) {
Result result = new Result();
User user = userDao.getUserByUsername(username);
if (user == null) {
result.setStateCode(400);
result.setMsg("未填写个人信息,请前往个人信息页面完善个人信息");
result.setData(null);
} else {
result.setStateCode(200);
// result.setStateCode();
result.setMsg("查询成功,已填写个人信息");
result.setData(user);
}
return result;
}
public Page<User> getAllUsers() {
return userDao.getAllUsers();
}
public int getUsersCount() {
return userDao.getUsersCount();
}
public Integer deleteUser(Integer id) {
return userDao.deleteUser(id);
}
/**
* 校验用户名
* @param username
* @return
*/
public User checkUserName(String username) {
return userDao.getUserByUsername(username);
}
/**
* 保存用户
* @param user
* @return
*/
public int saveUser(User user) {
int i = userDao.saveUser(user);
return i;
}
}
| 2,575 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
TripsViaService.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/src/main/java/com/code/rts/service/TripsViaService.java | package com.code.rts.service;
import com.code.rts.dao.TripsViaDao;
import com.code.rts.entity.TripsVia;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class TripsViaService {
@Resource
private TripsViaDao tripsViaDao;
public List<TripsVia> getAimTripsVia(String carNum) {
return tripsViaDao.getAimTripsVia(carNum);
}
public int updateTripVia(TripsVia tripsVia){
return tripsViaDao.updateTripsVia(tripsVia);
}
public int saveTripVia(TripsVia tripsVia){
return tripsViaDao.saveOneTripVia(tripsVia);
}
public int delTripVia(Integer id){
return tripsViaDao.deleteTripVia(id);
}
}
| 729 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
MavenWrapperDownloader.java | /FileExtraction/Java_unseen/zjy-ag_rail-ticketing-system/.mvn/wrapper/MavenWrapperDownloader.java | /*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| 4,951 | null | .java | zjy-ag/rail-ticketing-system | 8 | 7 | 0 | 2021-02-28T04:58:27Z | 2020-05-20T11:12:25Z |
UrlResponseInfo.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/org/chromium/net/UrlResponseInfo.java | package org.chromium.net;
//dummy class
public abstract class UrlResponseInfo {
public abstract String getUrl();
public abstract int getHttpStatusCode();
// Add additional existing methods, if needed.
}
| 220 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
CronetUrlRequest.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/org/chromium/net/impl/CronetUrlRequest.java | package org.chromium.net.impl;
import org.chromium.net.UrlRequest;
public abstract class CronetUrlRequest extends UrlRequest {
/**
* Method is added by patch.
*/
public abstract String getHookedUrl();
}
| 224 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
TimelineObject.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/com/tumblr/rumblr/model/TimelineObject.java | package com.tumblr.rumblr.model;
public class TimelineObject<T extends Timelineable> {
public final T getData() {
throw new UnsupportedOperationException("Stub");
}
}
| 185 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
PivotBar.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/com/google/android/libraries/youtube/rendering/ui/pivotbar/PivotBar.java | package com.google.android.libraries.youtube.rendering.ui.pivotbar;
import android.content.Context;
import android.widget.HorizontalScrollView;
public class PivotBar extends HorizontalScrollView {
public PivotBar(Context context) {
super(context);
}
}
| 270 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SlimMetadataScrollableButtonContainerLayout.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/com/google/android/apps/youtube/app/ui/SlimMetadataScrollableButtonContainerLayout.java | package com.google.android.apps.youtube.app.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
public class SlimMetadataScrollableButtonContainerLayout extends ViewGroup {
public SlimMetadataScrollableButtonContainerLayout(Context context) {
super(context);
}
public SlimMetadataScrollableButtonContainerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SlimMetadataScrollableButtonContainerLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
}
}
| 721 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
AwemeStatistics.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/com/ss/android/ugc/aweme/feed/model/AwemeStatistics.java | package com.ss.android.ugc.aweme.feed.model;
public class AwemeStatistics {
public long getPlayCount() {
throw new UnsupportedOperationException("Stub");
}
public long getDiggCount() {
throw new UnsupportedOperationException("Stub");
}
}
| 271 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
Aweme.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/com/ss/android/ugc/aweme/feed/model/Aweme.java | package com.ss.android.ugc.aweme.feed.model;
//Dummy class
public class Aweme {
public boolean isAd() {
throw new UnsupportedOperationException("Stub");
}
public boolean isLive() {
throw new UnsupportedOperationException("Stub");
}
public boolean isLiveReplay() {
throw new UnsupportedOperationException("Stub");
}
public boolean isWithPromotionalMusic() {
throw new UnsupportedOperationException("Stub");
}
public boolean getIsTikTokStory() {
throw new UnsupportedOperationException("Stub");
}
public boolean isImage() {
throw new UnsupportedOperationException("Stub");
}
public boolean isPhotoMode() {
throw new UnsupportedOperationException("Stub");
}
public AwemeStatistics getStatistics() {
throw new UnsupportedOperationException("Stub");
}
}
| 885 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
FeedItemList.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/com/ss/android/ugc/aweme/feed/model/FeedItemList.java | package com.ss.android.ugc.aweme.feed.model;
import java.util.List;
//Dummy class
public class FeedItemList {
public List<Aweme> items;
}
| 144 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
AdPersonalizationActivity.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/com/bytedance/ies/ugc/aweme/commercialize/compliance/personalization/AdPersonalizationActivity.java | package com.bytedance.ies.ugc.aweme.commercialize.compliance.personalization;
import android.app.Activity;
//Dummy class
public class AdPersonalizationActivity extends Activity { }
| 183 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ILink.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/com/reddit/domain/model/ILink.java | package com.reddit.domain.model;
public class ILink {
public boolean getPromoted() {
throw new UnsupportedOperationException("Stub");
}
}
| 155 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SettingsMenuGroup.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/tv/twitch/android/feature/settings/menu/SettingsMenuGroup.java | package tv.twitch.android.feature.settings.menu;
import java.util.List;
// Dummy
public final class SettingsMenuGroup {
public SettingsMenuGroup(List<Object> settingsMenuItems) {
throw new UnsupportedOperationException("Stub");
}
public List<Object> getSettingsMenuItems() {
throw new UnsupportedOperationException("Stub");
}
} | 362 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SettingsActivity.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/tv/twitch/android/settings/SettingsActivity.java | package tv.twitch.android.settings;
import android.app.Activity;
public class SettingsActivity extends Activity {}
| 117 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ClickableUsernameSpan.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/tv/twitch/android/shared/chat/util/ClickableUsernameSpan.java | package tv.twitch.android.shared.chat.util;
import android.text.style.ClickableSpan;
import android.view.View;
public final class ClickableUsernameSpan extends ClickableSpan {
@Override
public void onClick(View widget) {}
} | 233 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ConstraintLayout.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/android/support/constraint/ConstraintLayout.java | package android.support.constraint;
import android.content.Context;
import android.view.ViewGroup;
/**
* "CompileOnly" class
* because android.support.android.support.constraint.ConstraintLayout is deprecated
* in favour of androidx.constraintlayout.widget.ConstraintLayout.
*
* This class will not be included and "replaced" by the real package's class.
*/
public class ConstraintLayout extends ViewGroup {
public ConstraintLayout(Context context) {
super(context);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) { }
}
| 587 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
RecyclerView.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/stub/src/main/java/android/support/v7/widget/RecyclerView.java | package android.support.v7.widget;
import android.content.Context;
import android.view.View;
public class RecyclerView extends View {
public RecyclerView(Context context) {
super(context);
}
public View getChildAt(@SuppressWarnings("unused") final int index) {
return null;
}
public int getChildCount() {
return 0;
}
}
| 372 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ShowOnLockscreenPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tudortmund/lockscreen/ShowOnLockscreenPatch.java | package app.revanced.integrations.tudortmund.lockscreen;
import android.content.Context;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.view.Display;
import android.view.Window;
import androidx.appcompat.app.AppCompatActivity;
import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
public class ShowOnLockscreenPatch {
/**
* @noinspection deprecation
*/
public static Window getWindow(AppCompatActivity activity, float brightness) {
Window window = activity.getWindow();
if (brightness >= 0) {
// High brightness set, therefore show on lockscreen.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) activity.setShowWhenLocked(true);
else window.addFlags(FLAG_SHOW_WHEN_LOCKED | FLAG_DISMISS_KEYGUARD);
} else {
// Ignore brightness reset when the screen is turned off.
DisplayManager displayManager = (DisplayManager) activity.getSystemService(Context.DISPLAY_SERVICE);
boolean isScreenOn = false;
for (Display display : displayManager.getDisplays()) {
if (display.getState() == Display.STATE_OFF) continue;
isScreenOn = true;
break;
}
if (isScreenOn) {
// Hide on lockscreen.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) activity.setShowWhenLocked(false);
else window.clearFlags(FLAG_SHOW_WHEN_LOCKED | FLAG_DISMISS_KEYGUARD);
}
}
return window;
}
}
| 1,694 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ByteTrieSearch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/ByteTrieSearch.java | package app.revanced.integrations.youtube;
import androidx.annotation.NonNull;
import java.nio.charset.StandardCharsets;
public final class ByteTrieSearch extends TrieSearch<byte[]> {
private static final class ByteTrieNode extends TrieNode<byte[]> {
ByteTrieNode() {
super();
}
ByteTrieNode(char nodeCharacterValue) {
super(nodeCharacterValue);
}
@Override
TrieNode<byte[]> createNode(char nodeCharacterValue) {
return new ByteTrieNode(nodeCharacterValue);
}
@Override
char getCharValue(byte[] text, int index) {
return (char) text[index];
}
@Override
int getTextLength(byte[] text) {
return text.length;
}
}
/**
* Helper method for the common usage of converting Strings to raw UTF-8 bytes.
*/
public static byte[][] convertStringsToBytes(String... strings) {
final int length = strings.length;
byte[][] replacement = new byte[length][];
for (int i = 0; i < length; i++) {
replacement[i] = strings[i].getBytes(StandardCharsets.UTF_8);
}
return replacement;
}
public ByteTrieSearch(@NonNull byte[]... patterns) {
super(new ByteTrieNode(), patterns);
}
}
| 1,323 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ThemeHelper.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/ThemeHelper.java | package app.revanced.integrations.youtube;
import android.app.Activity;
import android.graphics.Color;
import androidx.annotation.Nullable;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
public class ThemeHelper {
@Nullable
private static Integer darkThemeColor, lightThemeColor;
private static int themeValue;
/**
* Injection point.
*/
public static void setTheme(Enum<?> value) {
final int newOrdinalValue = value.ordinal();
if (themeValue != newOrdinalValue) {
themeValue = newOrdinalValue;
Logger.printDebug(() -> "Theme value: " + newOrdinalValue);
}
}
public static boolean isDarkTheme() {
return themeValue == 1;
}
public static void setActivityTheme(Activity activity) {
final var theme = isDarkTheme()
? "Theme.YouTube.Settings.Dark"
: "Theme.YouTube.Settings";
activity.setTheme(Utils.getResourceIdentifier(theme, "style"));
}
/**
* Injection point.
*/
private static String darkThemeResourceName() {
// Value is changed by Theme patch, if included.
return "@android:color/black";
}
/**
* @return The dark theme color as specified by the Theme patch (if included),
* or the Android color of black.
*/
public static int getDarkThemeColor() {
if (darkThemeColor == null) {
darkThemeColor = getColorInt(darkThemeResourceName());
}
return darkThemeColor;
}
/**
* Injection point.
*/
private static String lightThemeResourceName() {
// Value is changed by Theme patch, if included.
return "@android:color/white";
}
/**
* @return The light theme color as specified by the Theme patch (if included),
* or the Android color of white.
*/
public static int getLightThemeColor() {
if (lightThemeColor == null) {
lightThemeColor = getColorInt(lightThemeResourceName());
}
return lightThemeColor;
}
private static int getColorInt(String colorString) {
if (colorString.startsWith("#")) {
return Color.parseColor(colorString);
}
return Utils.getResourceColor(colorString);
}
}
| 2,348 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
StringTrieSearch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/StringTrieSearch.java | package app.revanced.integrations.youtube;
import androidx.annotation.NonNull;
/**
* Text pattern searching using a prefix tree (trie).
*/
public final class StringTrieSearch extends TrieSearch<String> {
private static final class StringTrieNode extends TrieNode<String> {
StringTrieNode() {
super();
}
StringTrieNode(char nodeCharacterValue) {
super(nodeCharacterValue);
}
@Override
TrieNode<String> createNode(char nodeValue) {
return new StringTrieNode(nodeValue);
}
@Override
char getCharValue(String text, int index) {
return text.charAt(index);
}
@Override
int getTextLength(String text) {
return text.length();
}
}
public StringTrieSearch(@NonNull String... patterns) {
super(new StringTrieNode(), patterns);
}
}
| 914 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
TrieSearch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/TrieSearch.java | package app.revanced.integrations.youtube;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* Searches for a group of different patterns using a trie (prefix tree).
* Can significantly speed up searching for multiple patterns.
*/
public abstract class TrieSearch<T> {
public interface TriePatternMatchedCallback<T> {
/**
* Called when a pattern is matched.
*
* @param textSearched Text that was searched.
* @param matchedStartIndex Start index of the search text, where the pattern was matched.
* @param matchedLength Length of the match.
* @param callbackParameter Optional parameter passed into {@link TrieSearch#matches(Object, Object)}.
* @return True, if the search should stop here.
* If false, searching will continue to look for other matches.
*/
boolean patternMatched(T textSearched, int matchedStartIndex, int matchedLength, Object callbackParameter);
}
/**
* Represents a compressed tree path for a single pattern that shares no sibling nodes.
*
* For example, if a tree contains the patterns: "foobar", "football", "feet",
* it would contain 3 compressed paths of: "bar", "tball", "eet".
*
* And the tree would contain children arrays only for the first level containing 'f',
* the second level containing 'o',
* and the third level containing 'o'.
*
* This is done to reduce memory usage, which can be substantial if many long patterns are used.
*/
private static final class TrieCompressedPath<T> {
final T pattern;
final int patternStartIndex;
final int patternLength;
final TriePatternMatchedCallback<T> callback;
TrieCompressedPath(T pattern, int patternStartIndex, int patternLength, TriePatternMatchedCallback<T> callback) {
this.pattern = pattern;
this.patternStartIndex = patternStartIndex;
this.patternLength = patternLength;
this.callback = callback;
}
boolean matches(TrieNode<T> enclosingNode, // Used only for the get character method.
T searchText, int searchTextLength, int searchTextIndex, Object callbackParameter) {
if (searchTextLength - searchTextIndex < patternLength - patternStartIndex) {
return false; // Remaining search text is shorter than the remaining leaf pattern and they cannot match.
}
for (int i = searchTextIndex, j = patternStartIndex; j < patternLength; i++, j++) {
if (enclosingNode.getCharValue(searchText, i) != enclosingNode.getCharValue(pattern, j)) {
return false;
}
}
return callback == null || callback.patternMatched(searchText,
searchTextIndex - patternStartIndex, patternLength, callbackParameter);
}
}
static abstract class TrieNode<T> {
/**
* Dummy value used for root node. Value can be anything as it's never referenced.
*/
private static final char ROOT_NODE_CHARACTER_VALUE = 0; // ASCII null character.
/**
* How much to expand the children array when resizing.
*/
private static final int CHILDREN_ARRAY_INCREASE_SIZE_INCREMENT = 2;
/**
* Character this node represents.
* This field is ignored for the root node (which does not represent any character).
*/
private final char nodeValue;
/**
* A compressed graph path that represents the remaining pattern characters of a single child node.
*
* If present then child array is always null, although callbacks for other
* end of patterns can also exist on this same node.
*/
@Nullable
private TrieCompressedPath<T> leaf;
/**
* All child nodes. Only present if no compressed leaf exist.
*
* Array is dynamically increased in size as needed,
* and uses perfect hashing for the elements it contains.
*
* So if the array contains a given character,
* the character will always map to the node with index: (character % arraySize).
*
* Elements not contained can collide with elements the array does contain,
* so must compare the nodes character value.
*
* Alternatively this array could be a sorted and densely packed array,
* and lookup is done using binary search.
* That would save a small amount of memory because there's no null children entries,
* but would give a worst case search of O(nlog(m)) where n is the number of
* characters in the searched text and m is the maximum size of the sorted character arrays.
* Using a hash table array always gives O(n) search time.
* The memory usage here is very small (all Litho filters use ~10KB of memory),
* so the more performant hash implementation is chosen.
*/
@Nullable
private TrieNode<T>[] children;
/**
* Callbacks for all patterns that end at this node.
*/
@Nullable
private List<TriePatternMatchedCallback<T>> endOfPatternCallback;
TrieNode() {
this.nodeValue = ROOT_NODE_CHARACTER_VALUE;
}
TrieNode(char nodeCharacterValue) {
this.nodeValue = nodeCharacterValue;
}
/**
* @param pattern Pattern to add.
* @param patternIndex Current recursive index of the pattern.
* @param patternLength Length of the pattern.
* @param callback Callback, where a value of NULL indicates to always accept a pattern match.
*/
private void addPattern(@NonNull T pattern, int patternIndex, int patternLength,
@Nullable TriePatternMatchedCallback<T> callback) {
if (patternIndex == patternLength) { // Reached the end of the pattern.
if (endOfPatternCallback == null) {
endOfPatternCallback = new ArrayList<>(1);
}
endOfPatternCallback.add(callback);
return;
}
if (leaf != null) {
// Reached end of the graph and a leaf exist.
// Recursively call back into this method and push the existing leaf down 1 level.
if (children != null) throw new IllegalStateException();
//noinspection unchecked
children = new TrieNode[1];
TrieCompressedPath<T> temp = leaf;
leaf = null;
addPattern(temp.pattern, temp.patternStartIndex, temp.patternLength, temp.callback);
// Continue onward and add the parameter pattern.
} else if (children == null) {
leaf = new TrieCompressedPath<>(pattern, patternIndex, patternLength, callback);
return;
}
final char character = getCharValue(pattern, patternIndex);
final int arrayIndex = hashIndexForTableSize(children.length, character);
TrieNode<T> child = children[arrayIndex];
if (child == null) {
child = createNode(character);
children[arrayIndex] = child;
} else if (child.nodeValue != character) {
// Hash collision. Resize the table until perfect hashing is found.
child = createNode(character);
expandChildArray(child);
}
child.addPattern(pattern, patternIndex + 1, patternLength, callback);
}
/**
* Resizes the children table until all nodes hash to exactly one array index.
*/
private void expandChildArray(TrieNode<T> child) {
int replacementArraySize = Objects.requireNonNull(children).length;
while (true) {
replacementArraySize += CHILDREN_ARRAY_INCREASE_SIZE_INCREMENT;
//noinspection unchecked
TrieNode<T>[] replacement = new TrieNode[replacementArraySize];
addNodeToArray(replacement, child);
boolean collision = false;
for (TrieNode<T> existingChild : children) {
if (existingChild != null) {
if (!addNodeToArray(replacement, existingChild)) {
collision = true;
break;
}
}
}
if (collision) {
continue;
}
children = replacement;
return;
}
}
private static <T> boolean addNodeToArray(TrieNode<T>[] array, TrieNode<T> childToAdd) {
final int insertIndex = hashIndexForTableSize(array.length, childToAdd.nodeValue);
if (array[insertIndex] != null ) {
return false; // Collision.
}
array[insertIndex] = childToAdd;
return true;
}
private static int hashIndexForTableSize(int arraySize, char nodeValue) {
return nodeValue % arraySize;
}
/**
* This method is static and uses a loop to avoid all recursion.
* This is done for performance since the JVM does not optimize tail recursion.
*
* @param startNode Node to start the search from.
* @param searchText Text to search for patterns in.
* @param searchTextIndex Start index, inclusive.
* @param searchTextEndIndex End index, exclusive.
* @return If any pattern matches, and it's associated callback halted the search.
*/
private static <T> boolean matches(final TrieNode<T> startNode, final T searchText,
int searchTextIndex, final int searchTextEndIndex,
final Object callbackParameter) {
TrieNode<T> node = startNode;
int currentMatchLength = 0;
while (true) {
TrieCompressedPath<T> leaf = node.leaf;
if (leaf != null && leaf.matches(startNode, searchText, searchTextEndIndex, searchTextIndex, callbackParameter)) {
return true; // Leaf exists and it matched the search text.
}
List<TriePatternMatchedCallback<T>> endOfPatternCallback = node.endOfPatternCallback;
if (endOfPatternCallback != null) {
final int matchStartIndex = searchTextIndex - currentMatchLength;
for (@Nullable TriePatternMatchedCallback<T> callback : endOfPatternCallback) {
if (callback == null) {
return true; // No callback and all matches are valid.
}
if (callback.patternMatched(searchText, matchStartIndex, currentMatchLength, callbackParameter)) {
return true; // Callback confirmed the match.
}
}
}
TrieNode<T>[] children = node.children;
if (children == null) {
return false; // Reached a graph end point and there's no further patterns to search.
}
if (searchTextIndex == searchTextEndIndex) {
return false; // Reached end of the search text and found no matches.
}
// Use the start node to reduce VM method lookup, since all nodes are the same class type.
final char character = startNode.getCharValue(searchText, searchTextIndex);
final int arrayIndex = hashIndexForTableSize(children.length, character);
TrieNode<T> child = children[arrayIndex];
if (child == null || child.nodeValue != character) {
return false;
}
node = child;
searchTextIndex++;
currentMatchLength++;
}
}
/**
* Gives an approximate memory usage.
*
* @return Estimated number of memory pointers used, starting from this node and including all children.
*/
private int estimatedNumberOfPointersUsed() {
int numberOfPointers = 4; // Number of fields in this class.
if (leaf != null) {
numberOfPointers += 4; // Number of fields in leaf node.
}
if (endOfPatternCallback != null) {
numberOfPointers += endOfPatternCallback.size();
}
if (children != null) {
numberOfPointers += children.length;
for (TrieNode<T> child : children) {
if (child != null) {
numberOfPointers += child.estimatedNumberOfPointersUsed();
}
}
}
return numberOfPointers;
}
abstract TrieNode<T> createNode(char nodeValue);
abstract char getCharValue(T text, int index);
abstract int getTextLength(T text);
}
/**
* Root node, and it's children represent the first pattern characters.
*/
private final TrieNode<T> root;
/**
* Patterns to match.
*/
private final List<T> patterns = new ArrayList<>();
@SafeVarargs
TrieSearch(@NonNull TrieNode<T> root, @NonNull T... patterns) {
this.root = Objects.requireNonNull(root);
addPatterns(patterns);
}
@SafeVarargs
public final void addPatterns(@NonNull T... patterns) {
for (T pattern : patterns) {
addPattern(pattern);
}
}
/**
* Adds a pattern that will always return a positive match if found.
*
* @param pattern Pattern to add. Calling this with a zero length pattern does nothing.
*/
public void addPattern(@NonNull T pattern) {
addPattern(pattern, root.getTextLength(pattern), null);
}
/**
* @param pattern Pattern to add. Calling this with a zero length pattern does nothing.
* @param callback Callback to determine if searching should halt when a match is found.
*/
public void addPattern(@NonNull T pattern, @NonNull TriePatternMatchedCallback<T> callback) {
addPattern(pattern, root.getTextLength(pattern), Objects.requireNonNull(callback));
}
void addPattern(@NonNull T pattern, int patternLength, @Nullable TriePatternMatchedCallback<T> callback) {
if (patternLength == 0) return; // Nothing to match
patterns.add(pattern);
root.addPattern(pattern, 0, patternLength, callback);
}
public final boolean matches(@NonNull T textToSearch) {
return matches(textToSearch, 0);
}
public boolean matches(@NonNull T textToSearch, @NonNull Object callbackParameter) {
return matches(textToSearch, 0, root.getTextLength(textToSearch),
Objects.requireNonNull(callbackParameter));
}
public boolean matches(@NonNull T textToSearch, int startIndex) {
return matches(textToSearch, startIndex, root.getTextLength(textToSearch));
}
public final boolean matches(@NonNull T textToSearch, int startIndex, int endIndex) {
return matches(textToSearch, startIndex, endIndex, null);
}
/**
* Searches through text, looking for any substring that matches any pattern in this tree.
*
* @param textToSearch Text to search through.
* @param startIndex Index to start searching, inclusive value.
* @param endIndex Index to stop matching, exclusive value.
* @param callbackParameter Optional parameter passed to the callbacks.
* @return If any pattern matched, and it's callback halted searching.
*/
public boolean matches(@NonNull T textToSearch, int startIndex, int endIndex, @Nullable Object callbackParameter) {
return matches(textToSearch, root.getTextLength(textToSearch), startIndex, endIndex, callbackParameter);
}
private boolean matches(@NonNull T textToSearch, int textToSearchLength, int startIndex, int endIndex,
@Nullable Object callbackParameter) {
if (endIndex > textToSearchLength) {
throw new IllegalArgumentException("endIndex: " + endIndex
+ " is greater than texToSearchLength: " + textToSearchLength);
}
if (patterns.size() == 0) {
return false; // No patterns were added.
}
for (int i = startIndex; i < endIndex; i++) {
if (TrieNode.matches(root, textToSearch, i, endIndex, callbackParameter)) return true;
}
return false;
}
/**
* @return Estimated memory size (in kilobytes) of this instance.
*/
public int getEstimatedMemorySize() {
if (patterns.size() == 0) {
return 0;
}
// Assume the device has less than 32GB of ram (and can use pointer compression),
// or the device is 32-bit.
final int numberOfBytesPerPointer = 4;
return (int) Math.ceil((numberOfBytesPerPointer * root.estimatedNumberOfPointersUsed()) / 1024.0);
}
public int numberOfPatterns() {
return patterns.size();
}
public List<T> getPatterns() {
return Collections.unmodifiableList(patterns);
}
}
| 17,743 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SegmentPlaybackController.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/SegmentPlaybackController.java | package app.revanced.integrations.youtube.sponsorblock;
import static app.revanced.integrations.shared.StringRef.str;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.TypedValue;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.youtube.patches.VideoInformation;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.shared.PlayerType;
import app.revanced.integrations.youtube.shared.VideoState;
import app.revanced.integrations.youtube.sponsorblock.objects.CategoryBehaviour;
import app.revanced.integrations.youtube.sponsorblock.objects.SegmentCategory;
import app.revanced.integrations.youtube.sponsorblock.objects.SponsorSegment;
import app.revanced.integrations.youtube.sponsorblock.requests.SBRequester;
import app.revanced.integrations.youtube.sponsorblock.ui.SponsorBlockViewController;
/**
* Handles showing, scheduling, and skipping of all {@link SponsorSegment} for the current video.
*
* Class is not thread safe. All methods must be called on the main thread unless otherwise specified.
*/
public class SegmentPlaybackController {
/**
* Length of time to show a skip button for a highlight segment,
* or a regular segment if {@link Settings#SB_AUTO_HIDE_SKIP_BUTTON} is enabled.
*
* Effectively this value is rounded up to the next second.
*/
private static final long DURATION_TO_SHOW_SKIP_BUTTON = 3800;
/*
* Highlight segments have zero length as they are a point in time.
* Draw them on screen using a fixed width bar.
* Value is independent of device dpi.
*/
private static final int HIGHLIGHT_SEGMENT_DRAW_BAR_WIDTH = 7;
@Nullable
private static String currentVideoId;
@Nullable
private static SponsorSegment[] segments;
/**
* Highlight segment, if one exists and the skip behavior is not set to {@link CategoryBehaviour#SHOW_IN_SEEKBAR}.
*/
@Nullable
private static SponsorSegment highlightSegment;
/**
* Because loading can take time, show the skip to highlight for a few seconds after the segments load.
* This is the system time (in milliseconds) to no longer show the initial display skip to highlight.
* Value will be zero if no highlight segment exists, or if the system time to show the highlight has passed.
*/
private static long highlightSegmentInitialShowEndTime;
/**
* Currently playing (non-highlight) segment that user can manually skip.
*/
@Nullable
private static SponsorSegment segmentCurrentlyPlaying;
/**
* Currently playing manual skip segment that is scheduled to hide.
* This will always be NULL or equal to {@link #segmentCurrentlyPlaying}.
*/
@Nullable
private static SponsorSegment scheduledHideSegment;
/**
* Upcoming segment that is scheduled to either autoskip or show the manual skip button.
*/
@Nullable
private static SponsorSegment scheduledUpcomingSegment;
/**
* Used to prevent re-showing a previously hidden skip button when exiting an embedded segment.
* Only used when {@link Settings#SB_AUTO_HIDE_SKIP_BUTTON} is enabled.
*
* A collection of segments that have automatically hidden the skip button for, and all segments in this list
* contain the current video time. Segment are removed when playback exits the segment.
*/
private static final List<SponsorSegment> hiddenSkipSegmentsForCurrentVideoTime = new ArrayList<>();
/**
* System time (in milliseconds) of when to hide the skip button of {@link #segmentCurrentlyPlaying}.
* Value is zero if playback is not inside a segment ({@link #segmentCurrentlyPlaying} is null),
* or if {@link Settings#SB_AUTO_HIDE_SKIP_BUTTON} is not enabled.
*/
private static long skipSegmentButtonEndTime;
@Nullable
private static String timeWithoutSegments;
private static int sponsorBarAbsoluteLeft;
private static int sponsorAbsoluteBarRight;
private static int sponsorBarThickness;
@Nullable
static SponsorSegment[] getSegments() {
return segments;
}
private static void setSegments(@NonNull SponsorSegment[] videoSegments) {
Arrays.sort(videoSegments);
segments = videoSegments;
calculateTimeWithoutSegments();
if (SegmentCategory.HIGHLIGHT.behaviour == CategoryBehaviour.SKIP_AUTOMATICALLY
|| SegmentCategory.HIGHLIGHT.behaviour == CategoryBehaviour.MANUAL_SKIP) {
for (SponsorSegment segment : videoSegments) {
if (segment.category == SegmentCategory.HIGHLIGHT) {
highlightSegment = segment;
return;
}
}
}
highlightSegment = null;
}
static void addUnsubmittedSegment(@NonNull SponsorSegment segment) {
Objects.requireNonNull(segment);
if (segments == null) {
segments = new SponsorSegment[1];
} else {
segments = Arrays.copyOf(segments, segments.length + 1);
}
segments[segments.length - 1] = segment;
setSegments(segments);
}
static void removeUnsubmittedSegments() {
if (segments == null || segments.length == 0) {
return;
}
List<SponsorSegment> replacement = new ArrayList<>();
for (SponsorSegment segment : segments) {
if (segment.category != SegmentCategory.UNSUBMITTED) {
replacement.add(segment);
}
}
if (replacement.size() != segments.length) {
setSegments(replacement.toArray(new SponsorSegment[0]));
}
}
public static boolean videoHasSegments() {
return segments != null && segments.length > 0;
}
/**
* Clears all downloaded data.
*/
private static void clearData() {
currentVideoId = null;
segments = null;
highlightSegment = null;
highlightSegmentInitialShowEndTime = 0;
timeWithoutSegments = null;
segmentCurrentlyPlaying = null;
scheduledUpcomingSegment = null;
scheduledHideSegment = null;
skipSegmentButtonEndTime = 0;
toastSegmentSkipped = null;
toastNumberOfSegmentsSkipped = 0;
hiddenSkipSegmentsForCurrentVideoTime.clear();
}
/**
* Injection point.
* Initializes SponsorBlock when the video player starts playing a new video.
*/
public static void initialize(Object ignoredPlayerController) {
try {
Utils.verifyOnMainThread();
SponsorBlockSettings.initialize();
clearData();
SponsorBlockViewController.hideAll();
SponsorBlockUtils.clearUnsubmittedSegmentTimes();
Logger.printDebug(() -> "Initialized SponsorBlock");
} catch (Exception ex) {
Logger.printException(() -> "Failed to initialize SponsorBlock", ex);
}
}
/**
* Injection point.
*/
public static void setCurrentVideoId(@Nullable String videoId) {
try {
if (Objects.equals(currentVideoId, videoId)) {
return;
}
clearData();
if (videoId == null || !Settings.SB_ENABLED.get()) {
return;
}
if (PlayerType.getCurrent().isNoneOrHidden()) {
Logger.printDebug(() -> "ignoring Short");
return;
}
if (!Utils.isNetworkConnected()) {
Logger.printDebug(() -> "Network not connected, ignoring video");
return;
}
currentVideoId = videoId;
Logger.printDebug(() -> "setCurrentVideoId: " + videoId);
Utils.runOnBackgroundThread(() -> {
try {
executeDownloadSegments(videoId);
} catch (Exception e) {
Logger.printException(() -> "Failed to download segments", e);
}
});
} catch (Exception ex) {
Logger.printException(() -> "setCurrentVideoId failure", ex);
}
}
/**
* Must be called off main thread
*/
static void executeDownloadSegments(@NonNull String videoId) {
Objects.requireNonNull(videoId);
try {
SponsorSegment[] segments = SBRequester.getSegments(videoId);
Utils.runOnMainThread(()-> {
if (!videoId.equals(currentVideoId)) {
// user changed videos before get segments network call could complete
Logger.printDebug(() -> "Ignoring segments for prior video: " + videoId);
return;
}
setSegments(segments);
final long videoTime = VideoInformation.getVideoTime();
if (highlightSegment != null) {
// If the current video time is before the highlight.
final long timeUntilHighlight = highlightSegment.start - videoTime;
if (timeUntilHighlight > 0) {
if (highlightSegment.shouldAutoSkip()) {
skipSegment(highlightSegment, false);
return;
}
highlightSegmentInitialShowEndTime = System.currentTimeMillis() + Math.min(
(long) (timeUntilHighlight / VideoInformation.getPlaybackSpeed()),
DURATION_TO_SHOW_SKIP_BUTTON);
}
}
// check for any skips now, instead of waiting for the next update to setVideoTime()
setVideoTime(videoTime);
});
} catch (Exception ex) {
Logger.printException(() -> "executeDownloadSegments failure", ex);
}
}
/**
* Injection point.
* Updates SponsorBlock every 1000ms.
* When changing videos, this is first called with value 0 and then the video is changed.
*/
public static void setVideoTime(long millis) {
try {
if (!Settings.SB_ENABLED.get()
|| PlayerType.getCurrent().isNoneOrHidden() // Shorts playback.
|| segments == null || segments.length == 0) {
return;
}
Logger.printDebug(() -> "setVideoTime: " + millis);
updateHiddenSegments(millis);
final float playbackSpeed = VideoInformation.getPlaybackSpeed();
// Amount of time to look ahead for the next segment,
// and the threshold to determine if a scheduled show/hide is at the correct video time when it's run.
//
// This value must be greater than largest time between calls to this method (1000ms),
// and must be adjusted for the video speed.
//
// To debug the stale skip logic, set this to a very large value (5000 or more)
// then try manually seeking just before playback reaches a segment skip.
final long speedAdjustedTimeThreshold = (long)(playbackSpeed * 1200);
final long startTimerLookAheadThreshold = millis + speedAdjustedTimeThreshold;
SponsorSegment foundSegmentCurrentlyPlaying = null;
SponsorSegment foundUpcomingSegment = null;
for (final SponsorSegment segment : segments) {
if (segment.category.behaviour == CategoryBehaviour.SHOW_IN_SEEKBAR
|| segment.category.behaviour == CategoryBehaviour.IGNORE
|| segment.category == SegmentCategory.HIGHLIGHT) {
continue;
}
if (segment.end <= millis) {
continue; // past this segment
}
if (segment.start <= millis) {
// we are in the segment!
if (segment.shouldAutoSkip()) {
skipSegment(segment, false);
return; // must return, as skipping causes a recursive call back into this method
}
// first found segment, or it's an embedded segment and fully inside the outer segment
if (foundSegmentCurrentlyPlaying == null || foundSegmentCurrentlyPlaying.containsSegment(segment)) {
// If the found segment is not currently displayed, then do not show if the segment is nearly over.
// This check prevents the skip button text from rapidly changing when multiple segments end at nearly the same time.
// Also prevents showing the skip button if user seeks into the last 800ms of the segment.
final long minMillisOfSegmentRemainingThreshold = 800;
if (segmentCurrentlyPlaying == segment
|| !segment.endIsNear(millis, minMillisOfSegmentRemainingThreshold)) {
foundSegmentCurrentlyPlaying = segment;
} else {
Logger.printDebug(() -> "Ignoring segment that ends very soon: " + segment);
}
}
// Keep iterating and looking. There may be an upcoming autoskip,
// or there may be another smaller segment nested inside this segment
continue;
}
// segment is upcoming
if (startTimerLookAheadThreshold < segment.start) {
break; // segment is not close enough to schedule, and no segments after this are of interest
}
if (segment.shouldAutoSkip()) { // upcoming autoskip
foundUpcomingSegment = segment;
break; // must stop here
}
// upcoming manual skip
// do not schedule upcoming segment, if it is not fully contained inside the current segment
if ((foundSegmentCurrentlyPlaying == null || foundSegmentCurrentlyPlaying.containsSegment(segment))
// use the most inner upcoming segment
&& (foundUpcomingSegment == null || foundUpcomingSegment.containsSegment(segment))) {
// Only schedule, if the segment start time is not near the end time of the current segment.
// This check is needed to prevent scheduled hide and show from clashing with each other.
// Instead the upcoming segment will be handled when the current segment scheduled hide calls back into this method.
final long minTimeBetweenStartEndOfSegments = 1000;
if (foundSegmentCurrentlyPlaying == null
|| !foundSegmentCurrentlyPlaying.endIsNear(segment.start, minTimeBetweenStartEndOfSegments)) {
foundUpcomingSegment = segment;
} else {
Logger.printDebug(() -> "Not scheduling segment (start time is near end of current segment): " + segment);
}
}
}
if (highlightSegment != null) {
if (millis < DURATION_TO_SHOW_SKIP_BUTTON || (highlightSegmentInitialShowEndTime != 0
&& System.currentTimeMillis() < highlightSegmentInitialShowEndTime)) {
SponsorBlockViewController.showSkipHighlightButton(highlightSegment);
} else {
highlightSegmentInitialShowEndTime = 0;
SponsorBlockViewController.hideSkipHighlightButton();
}
}
if (segmentCurrentlyPlaying != foundSegmentCurrentlyPlaying) {
setSegmentCurrentlyPlaying(foundSegmentCurrentlyPlaying);
} else if (foundSegmentCurrentlyPlaying != null
&& skipSegmentButtonEndTime != 0 && skipSegmentButtonEndTime <= System.currentTimeMillis()) {
Logger.printDebug(() -> "Auto hiding skip button for segment: " + segmentCurrentlyPlaying);
skipSegmentButtonEndTime = 0;
hiddenSkipSegmentsForCurrentVideoTime.add(foundSegmentCurrentlyPlaying);
SponsorBlockViewController.hideSkipSegmentButton();
}
// schedule a hide, only if the segment end is near
final SponsorSegment segmentToHide =
(foundSegmentCurrentlyPlaying != null && foundSegmentCurrentlyPlaying.endIsNear(millis, speedAdjustedTimeThreshold))
? foundSegmentCurrentlyPlaying
: null;
if (scheduledHideSegment != segmentToHide) {
if (segmentToHide == null) {
Logger.printDebug(() -> "Clearing scheduled hide: " + scheduledHideSegment);
scheduledHideSegment = null;
} else {
scheduledHideSegment = segmentToHide;
Logger.printDebug(() -> "Scheduling hide segment: " + segmentToHide + " playbackSpeed: " + playbackSpeed);
final long delayUntilHide = (long) ((segmentToHide.end - millis) / playbackSpeed);
Utils.runOnMainThreadDelayed(() -> {
if (scheduledHideSegment != segmentToHide) {
Logger.printDebug(() -> "Ignoring old scheduled hide segment: " + segmentToHide);
return;
}
scheduledHideSegment = null;
if (VideoState.getCurrent() != VideoState.PLAYING) {
Logger.printDebug(() -> "Ignoring scheduled hide segment as video is paused: " + segmentToHide);
return;
}
final long videoTime = VideoInformation.getVideoTime();
if (!segmentToHide.endIsNear(videoTime, speedAdjustedTimeThreshold)) {
// current video time is not what's expected. User paused playback
Logger.printDebug(() -> "Ignoring outdated scheduled hide: " + segmentToHide
+ " videoInformation time: " + videoTime);
return;
}
Logger.printDebug(() -> "Running scheduled hide segment: " + segmentToHide);
// Need more than just hide the skip button, as this may have been an embedded segment
// Instead call back into setVideoTime to check everything again.
// Should not use VideoInformation time as it is less accurate,
// but this scheduled handler was scheduled precisely so we can just use the segment end time
setSegmentCurrentlyPlaying(null);
setVideoTime(segmentToHide.end);
}, delayUntilHide);
}
}
if (scheduledUpcomingSegment != foundUpcomingSegment) {
if (foundUpcomingSegment == null) {
Logger.printDebug(() -> "Clearing scheduled segment: " + scheduledUpcomingSegment);
scheduledUpcomingSegment = null;
} else {
scheduledUpcomingSegment = foundUpcomingSegment;
final SponsorSegment segmentToSkip = foundUpcomingSegment;
Logger.printDebug(() -> "Scheduling segment: " + segmentToSkip + " playbackSpeed: " + playbackSpeed);
final long delayUntilSkip = (long) ((segmentToSkip.start - millis) / playbackSpeed);
Utils.runOnMainThreadDelayed(() -> {
if (scheduledUpcomingSegment != segmentToSkip) {
Logger.printDebug(() -> "Ignoring old scheduled segment: " + segmentToSkip);
return;
}
scheduledUpcomingSegment = null;
if (VideoState.getCurrent() != VideoState.PLAYING) {
Logger.printDebug(() -> "Ignoring scheduled hide segment as video is paused: " + segmentToSkip);
return;
}
final long videoTime = VideoInformation.getVideoTime();
if (!segmentToSkip.startIsNear(videoTime, speedAdjustedTimeThreshold)) {
// current video time is not what's expected. User paused playback
Logger.printDebug(() -> "Ignoring outdated scheduled segment: " + segmentToSkip
+ " videoInformation time: " + videoTime);
return;
}
if (segmentToSkip.shouldAutoSkip()) {
Logger.printDebug(() -> "Running scheduled skip segment: " + segmentToSkip);
skipSegment(segmentToSkip, false);
} else {
Logger.printDebug(() -> "Running scheduled show segment: " + segmentToSkip);
setSegmentCurrentlyPlaying(segmentToSkip);
}
}, delayUntilSkip);
}
}
} catch (Exception e) {
Logger.printException(() -> "setVideoTime failure", e);
}
}
/**
* Removes all previously hidden segments that are not longer contained in the given video time.
*/
private static void updateHiddenSegments(long currentVideoTime) {
Iterator<SponsorSegment> i = hiddenSkipSegmentsForCurrentVideoTime.iterator();
while (i.hasNext()) {
SponsorSegment hiddenSegment = i.next();
if (!hiddenSegment.containsTime(currentVideoTime)) {
Logger.printDebug(() -> "Resetting hide skip button: " + hiddenSegment);
i.remove();
}
}
}
private static void setSegmentCurrentlyPlaying(@Nullable SponsorSegment segment) {
if (segment == null) {
if (segmentCurrentlyPlaying != null) Logger.printDebug(() -> "Hiding segment: " + segmentCurrentlyPlaying);
segmentCurrentlyPlaying = null;
skipSegmentButtonEndTime = 0;
SponsorBlockViewController.hideSkipSegmentButton();
return;
}
segmentCurrentlyPlaying = segment;
skipSegmentButtonEndTime = 0;
if (Settings.SB_AUTO_HIDE_SKIP_BUTTON.get()) {
if (hiddenSkipSegmentsForCurrentVideoTime.contains(segment)) {
// Playback exited a nested segment and the outer segment skip button was previously hidden.
Logger.printDebug(() -> "Ignoring previously auto-hidden segment: " + segment);
SponsorBlockViewController.hideSkipSegmentButton();
return;
}
skipSegmentButtonEndTime = System.currentTimeMillis() + DURATION_TO_SHOW_SKIP_BUTTON;
}
Logger.printDebug(() -> "Showing segment: " + segment);
SponsorBlockViewController.showSkipSegmentButton(segment);
}
private static SponsorSegment lastSegmentSkipped;
private static long lastSegmentSkippedTime;
private static void skipSegment(@NonNull SponsorSegment segmentToSkip, boolean userManuallySkipped) {
try {
SponsorBlockViewController.hideSkipHighlightButton();
SponsorBlockViewController.hideSkipSegmentButton();
final long now = System.currentTimeMillis();
if (lastSegmentSkipped == segmentToSkip) {
// If trying to seek to end of the video, YouTube can seek just before of the actual end.
// (especially if the video does not end on a whole second boundary).
// This causes additional segment skip attempts, even though it cannot seek any closer to the desired time.
// Check for and ignore repeated skip attempts of the same segment over a small time period.
final long minTimeBetweenSkippingSameSegment = Math.max(500,
(long) (500 / VideoInformation.getPlaybackSpeed()));
if (now - lastSegmentSkippedTime < minTimeBetweenSkippingSameSegment) {
Logger.printDebug(() -> "Ignoring skip segment request (already skipped as close as possible): " + segmentToSkip);
return;
}
}
Logger.printDebug(() -> "Skipping segment: " + segmentToSkip);
lastSegmentSkipped = segmentToSkip;
lastSegmentSkippedTime = now;
setSegmentCurrentlyPlaying(null);
scheduledHideSegment = null;
scheduledUpcomingSegment = null;
if (segmentToSkip == highlightSegment) {
highlightSegmentInitialShowEndTime = 0;
}
// If the seek is successful, then the seek causes a recursive call back into this class.
final boolean seekSuccessful = VideoInformation.seekTo(segmentToSkip.end);
if (!seekSuccessful) {
// can happen when switching videos and is normal
Logger.printDebug(() -> "Could not skip segment (seek unsuccessful): " + segmentToSkip);
return;
}
final boolean videoIsPaused = VideoState.getCurrent() == VideoState.PAUSED;
if (!userManuallySkipped) {
// check for any smaller embedded segments, and count those as autoskipped
final boolean showSkipToast = Settings.SB_TOAST_ON_SKIP.get();
for (final SponsorSegment otherSegment : Objects.requireNonNull(segments)) {
if (segmentToSkip.end < otherSegment.start) {
break; // no other segments can be contained
}
if (otherSegment == segmentToSkip ||
(otherSegment.category != SegmentCategory.HIGHLIGHT && segmentToSkip.containsSegment(otherSegment))) {
otherSegment.didAutoSkipped = true;
// Do not show a toast if the user is scrubbing thru a paused video.
// Cannot do this video state check in setTime or earlier in this method, as the video state may not be up to date.
// So instead, only hide toasts because all other skip logic done while paused causes no harm.
if (showSkipToast && !videoIsPaused) {
showSkippedSegmentToast(otherSegment);
}
}
}
}
if (segmentToSkip.category == SegmentCategory.UNSUBMITTED) {
removeUnsubmittedSegments();
SponsorBlockUtils.setNewSponsorSegmentPreviewed();
} else if (!videoIsPaused) {
SponsorBlockUtils.sendViewRequestAsync(segmentToSkip);
}
} catch (Exception ex) {
Logger.printException(() -> "skipSegment failure", ex);
}
}
private static int toastNumberOfSegmentsSkipped;
@Nullable
private static SponsorSegment toastSegmentSkipped;
private static void showSkippedSegmentToast(@NonNull SponsorSegment segment) {
Utils.verifyOnMainThread();
toastNumberOfSegmentsSkipped++;
if (toastNumberOfSegmentsSkipped > 1) {
return; // toast already scheduled
}
toastSegmentSkipped = segment;
final long delayToToastMilliseconds = 250; // also the maximum time between skips to be considered skipping multiple segments
Utils.runOnMainThreadDelayed(() -> {
try {
if (toastSegmentSkipped == null) { // video was changed just after skipping segment
Logger.printDebug(() -> "Ignoring old scheduled show toast");
return;
}
Utils.showToastShort(toastNumberOfSegmentsSkipped == 1
? toastSegmentSkipped.getSkippedToastText()
: str("revanced_sb_skipped_multiple_segments"));
} catch (Exception ex) {
Logger.printException(() -> "showSkippedSegmentToast failure", ex);
} finally {
toastNumberOfSegmentsSkipped = 0;
toastSegmentSkipped = null;
}
}, delayToToastMilliseconds);
}
/**
* @param segment can be either a highlight or a regular manual skip segment.
*/
public static void onSkipSegmentClicked(@NonNull SponsorSegment segment) {
try {
if (segment != highlightSegment && segment != segmentCurrentlyPlaying) {
Logger.printException(() -> "error: segment not available to skip"); // should never happen
SponsorBlockViewController.hideSkipSegmentButton();
SponsorBlockViewController.hideSkipHighlightButton();
return;
}
skipSegment(segment, true);
} catch (Exception ex) {
Logger.printException(() -> "onSkipSegmentClicked failure", ex);
}
}
/**
* Injection point
*/
public static void setSponsorBarRect(final Object self) {
try {
Field field = self.getClass().getDeclaredField("replaceMeWithsetSponsorBarRect");
field.setAccessible(true);
Rect rect = (Rect) Objects.requireNonNull(field.get(self));
setSponsorBarAbsoluteLeft(rect);
setSponsorBarAbsoluteRight(rect);
} catch (Exception ex) {
Logger.printException(() -> "setSponsorBarRect failure", ex);
}
}
private static void setSponsorBarAbsoluteLeft(Rect rect) {
final int left = rect.left;
if (sponsorBarAbsoluteLeft != left) {
Logger.printDebug(() -> "setSponsorBarAbsoluteLeft: " + left);
sponsorBarAbsoluteLeft = left;
}
}
private static void setSponsorBarAbsoluteRight(Rect rect) {
final int right = rect.right;
if (sponsorAbsoluteBarRight != right) {
Logger.printDebug(() -> "setSponsorBarAbsoluteRight: " + right);
sponsorAbsoluteBarRight = right;
}
}
/**
* Injection point
*/
public static void setSponsorBarThickness(int thickness) {
if (sponsorBarThickness != thickness) {
Logger.printDebug(() -> "setSponsorBarThickness: " + thickness);
sponsorBarThickness = thickness;
}
}
/**
* Injection point.
*/
public static String appendTimeWithoutSegments(String totalTime) {
try {
if (Settings.SB_ENABLED.get() && Settings.SB_VIDEO_LENGTH_WITHOUT_SEGMENTS.get()
&& !TextUtils.isEmpty(totalTime) && !TextUtils.isEmpty(timeWithoutSegments)) {
// Force LTR layout, to match the same LTR video time/length layout YouTube uses for all languages
return "\u202D" + totalTime + timeWithoutSegments; // u202D = left to right override
}
} catch (Exception ex) {
Logger.printException(() -> "appendTimeWithoutSegments failure", ex);
}
return totalTime;
}
private static void calculateTimeWithoutSegments() {
final long currentVideoLength = VideoInformation.getVideoLength();
if (!Settings.SB_VIDEO_LENGTH_WITHOUT_SEGMENTS.get() || currentVideoLength <= 0
|| segments == null || segments.length == 0) {
timeWithoutSegments = null;
return;
}
boolean foundNonhighlightSegments = false;
long timeWithoutSegmentsValue = currentVideoLength;
for (int i = 0, length = segments.length; i < length; i++) {
SponsorSegment segment = segments[i];
if (segment.category == SegmentCategory.HIGHLIGHT) {
continue;
}
foundNonhighlightSegments = true;
long start = segment.start;
final long end = segment.end;
// To prevent nested segments from incorrectly counting additional time,
// check if the segment overlaps any earlier segments.
for (int j = 0; j < i; j++) {
start = Math.max(start, segments[j].end);
}
if (start < end) {
timeWithoutSegmentsValue -= (end - start);
}
}
if (!foundNonhighlightSegments) {
timeWithoutSegments = null;
return;
}
final long hours = timeWithoutSegmentsValue / 3600000;
final long minutes = (timeWithoutSegmentsValue / 60000) % 60;
final long seconds = (timeWithoutSegmentsValue / 1000) % 60;
if (hours > 0) {
timeWithoutSegments = String.format("\u2009(%d:%02d:%02d)", hours, minutes, seconds);
} else {
timeWithoutSegments = String.format("\u2009(%d:%02d)", minutes, seconds);
}
}
private static int highlightSegmentTimeBarScreenWidth = -1; // actual pixel width to use
private static int getHighlightSegmentTimeBarScreenWidth() {
if (highlightSegmentTimeBarScreenWidth == -1) {
highlightSegmentTimeBarScreenWidth = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, HIGHLIGHT_SEGMENT_DRAW_BAR_WIDTH,
Objects.requireNonNull(Utils.getContext()).getResources().getDisplayMetrics());
}
return highlightSegmentTimeBarScreenWidth;
}
/**
* Injection point.
*/
public static void drawSponsorTimeBars(final Canvas canvas, final float posY) {
try {
if (segments == null) return;
final long videoLength = VideoInformation.getVideoLength();
if (videoLength <= 0) return;
final int thicknessDiv2 = sponsorBarThickness / 2; // rounds down
final float top = posY - (sponsorBarThickness - thicknessDiv2);
final float bottom = posY + thicknessDiv2;
final float videoMillisecondsToPixels = (1f / videoLength) * (sponsorAbsoluteBarRight - sponsorBarAbsoluteLeft);
final float leftPadding = sponsorBarAbsoluteLeft;
for (SponsorSegment segment : segments) {
final float left = leftPadding + segment.start * videoMillisecondsToPixels;
final float right;
if (segment.category == SegmentCategory.HIGHLIGHT) {
right = left + getHighlightSegmentTimeBarScreenWidth();
} else {
right = leftPadding + segment.end * videoMillisecondsToPixels;
}
canvas.drawRect(left, top, right, bottom, segment.category.paint);
}
} catch (Exception ex) {
Logger.printException(() -> "drawSponsorTimeBars failure", ex);
}
}
}
| 35,569 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SponsorBlockUtils.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/SponsorBlockUtils.java | package app.revanced.integrations.youtube.sponsorblock;
import static app.revanced.integrations.shared.StringRef.str;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Html;
import android.widget.EditText;
import androidx.annotation.NonNull;
import java.lang.ref.WeakReference;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.Objects;
import java.util.TimeZone;
import app.revanced.integrations.youtube.patches.VideoInformation;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.sponsorblock.objects.CategoryBehaviour;
import app.revanced.integrations.youtube.sponsorblock.objects.SegmentCategory;
import app.revanced.integrations.youtube.sponsorblock.objects.SponsorSegment;
import app.revanced.integrations.youtube.sponsorblock.objects.SponsorSegment.SegmentVote;
import app.revanced.integrations.youtube.sponsorblock.requests.SBRequester;
import app.revanced.integrations.youtube.sponsorblock.ui.SponsorBlockViewController;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
/**
* Not thread safe. All fields/methods must be accessed from the main thread.
*/
public class SponsorBlockUtils {
private static final String MANUAL_EDIT_TIME_FORMAT = "HH:mm:ss.SSS";
@SuppressLint("SimpleDateFormat")
private static final SimpleDateFormat manualEditTimeFormatter = new SimpleDateFormat(MANUAL_EDIT_TIME_FORMAT);
@SuppressLint("SimpleDateFormat")
private static final SimpleDateFormat voteSegmentTimeFormatter = new SimpleDateFormat();
private static final NumberFormat statsNumberFormatter = NumberFormat.getNumberInstance();
static {
TimeZone utc = TimeZone.getTimeZone("UTC");
manualEditTimeFormatter.setTimeZone(utc);
voteSegmentTimeFormatter.setTimeZone(utc);
}
private static final String LOCKED_COLOR = "#FFC83D";
private static long newSponsorSegmentDialogShownMillis;
private static long newSponsorSegmentStartMillis = -1;
private static long newSponsorSegmentEndMillis = -1;
private static boolean newSponsorSegmentPreviewed;
private static final DialogInterface.OnClickListener newSponsorSegmentDialogListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
// start
newSponsorSegmentStartMillis = newSponsorSegmentDialogShownMillis;
break;
case DialogInterface.BUTTON_POSITIVE:
// end
newSponsorSegmentEndMillis = newSponsorSegmentDialogShownMillis;
break;
}
dialog.dismiss();
}
};
private static SegmentCategory newUserCreatedSegmentCategory;
private static final DialogInterface.OnClickListener segmentTypeListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
SegmentCategory category = SegmentCategory.categoriesWithoutHighlights()[which];
final boolean enableButton;
if (category.behaviour == CategoryBehaviour.IGNORE) {
Utils.showToastLong(str("revanced_sb_new_segment_disabled_category"));
enableButton = false;
} else {
newUserCreatedSegmentCategory = category;
enableButton = true;
}
((AlertDialog) dialog)
.getButton(DialogInterface.BUTTON_POSITIVE)
.setEnabled(enableButton);
} catch (Exception ex) {
Logger.printException(() -> "segmentTypeListener failure", ex);
}
}
};
private static final DialogInterface.OnClickListener segmentReadyDialogButtonListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
SponsorBlockViewController.hideNewSegmentLayout();
Context context = ((AlertDialog) dialog).getContext();
dialog.dismiss();
SegmentCategory[] categories = SegmentCategory.categoriesWithoutHighlights();
CharSequence[] titles = new CharSequence[categories.length];
for (int i = 0, length = categories.length; i < length; i++) {
titles[i] = categories[i].getTitleWithColorDot();
}
newUserCreatedSegmentCategory = null;
new AlertDialog.Builder(context)
.setTitle(str("revanced_sb_new_segment_choose_category"))
.setSingleChoiceItems(titles, -1, segmentTypeListener)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, segmentCategorySelectedDialogListener)
.show()
.getButton(DialogInterface.BUTTON_POSITIVE)
.setEnabled(false);
} catch (Exception ex) {
Logger.printException(() -> "segmentReadyDialogButtonListener failure", ex);
}
}
};
private static final DialogInterface.OnClickListener segmentCategorySelectedDialogListener = (dialog, which) -> {
dialog.dismiss();
submitNewSegment();
};
private static final EditByHandSaveDialogListener editByHandSaveDialogListener = new EditByHandSaveDialogListener();
private static final DialogInterface.OnClickListener editByHandDialogListener = (dialog, which) -> {
try {
Context context = ((AlertDialog) dialog).getContext();
final boolean isStart = DialogInterface.BUTTON_NEGATIVE == which;
final EditText textView = new EditText(context);
textView.setHint(MANUAL_EDIT_TIME_FORMAT);
if (isStart) {
if (newSponsorSegmentStartMillis >= 0)
textView.setText(manualEditTimeFormatter.format(new Date(newSponsorSegmentStartMillis)));
} else {
if (newSponsorSegmentEndMillis >= 0)
textView.setText(manualEditTimeFormatter.format(new Date(newSponsorSegmentEndMillis)));
}
editByHandSaveDialogListener.settingStart = isStart;
editByHandSaveDialogListener.editText = new WeakReference<>(textView);
new AlertDialog.Builder(context)
.setTitle(str(isStart ? "revanced_sb_new_segment_time_start" : "revanced_sb_new_segment_time_end"))
.setView(textView)
.setNegativeButton(android.R.string.cancel, null)
.setNeutralButton(str("revanced_sb_new_segment_now"), editByHandSaveDialogListener)
.setPositiveButton(android.R.string.ok, editByHandSaveDialogListener)
.show();
dialog.dismiss();
} catch (Exception ex) {
Logger.printException(() -> "editByHandDialogListener failure", ex);
}
};
private static final DialogInterface.OnClickListener segmentVoteClickListener = (dialog, which) -> {
try {
final Context context = ((AlertDialog) dialog).getContext();
SponsorSegment[] segments = SegmentPlaybackController.getSegments();
if (segments == null || segments.length == 0) {
// should never be reached
Logger.printException(() -> "Segment is no longer available on the client");
return;
}
SponsorSegment segment = segments[which];
SegmentVote[] voteOptions = (segment.category == SegmentCategory.HIGHLIGHT)
? SegmentVote.voteTypesWithoutCategoryChange // highlight segments cannot change category
: SegmentVote.values();
CharSequence[] items = new CharSequence[voteOptions.length];
for (int i = 0; i < voteOptions.length; i++) {
SegmentVote voteOption = voteOptions[i];
String title = voteOption.title.toString();
if (Settings.SB_USER_IS_VIP.get() && segment.isLocked && voteOption.shouldHighlight) {
items[i] = Html.fromHtml(String.format("<font color=\"%s\">%s</font>", LOCKED_COLOR, title));
} else {
items[i] = title;
}
}
new AlertDialog.Builder(context)
.setItems(items, (dialog1, which1) -> {
SegmentVote voteOption = voteOptions[which1];
switch (voteOption) {
case UPVOTE:
case DOWNVOTE:
SBRequester.voteForSegmentOnBackgroundThread(segment, voteOption);
break;
case CATEGORY_CHANGE:
onNewCategorySelect(segment, context);
break;
}
})
.show();
} catch (Exception ex) {
Logger.printException(() -> "segmentVoteClickListener failure", ex);
}
};
private SponsorBlockUtils() {
}
static void setNewSponsorSegmentPreviewed() {
newSponsorSegmentPreviewed = true;
}
static void clearUnsubmittedSegmentTimes() {
newSponsorSegmentDialogShownMillis = 0;
newSponsorSegmentEndMillis = newSponsorSegmentStartMillis = -1;
newSponsorSegmentPreviewed = false;
}
private static void submitNewSegment() {
try {
Utils.verifyOnMainThread();
final long start = newSponsorSegmentStartMillis;
final long end = newSponsorSegmentEndMillis;
final String videoId = VideoInformation.getVideoId();
final long videoLength = VideoInformation.getVideoLength();
final SegmentCategory segmentCategory = newUserCreatedSegmentCategory;
if (start < 0 || end < 0 || start >= end || videoLength <= 0 || videoId.isEmpty() || segmentCategory == null) {
Logger.printException(() -> "invalid parameters");
return;
}
clearUnsubmittedSegmentTimes();
Utils.runOnBackgroundThread(() -> {
SBRequester.submitSegments(videoId, segmentCategory.keyValue, start, end, videoLength);
SegmentPlaybackController.executeDownloadSegments(videoId);
});
} catch (Exception e) {
Logger.printException(() -> "Unable to submit segment", e);
}
}
public static void onMarkLocationClicked() {
try {
Utils.verifyOnMainThread();
newSponsorSegmentDialogShownMillis = VideoInformation.getVideoTime();
new AlertDialog.Builder(SponsorBlockViewController.getOverLaysViewGroupContext())
.setTitle(str("revanced_sb_new_segment_title"))
.setMessage(str("revanced_sb_new_segment_mark_time_as_question",
newSponsorSegmentDialogShownMillis / 60000,
newSponsorSegmentDialogShownMillis / 1000 % 60,
newSponsorSegmentDialogShownMillis % 1000))
.setNeutralButton(android.R.string.cancel, null)
.setNegativeButton(str("revanced_sb_new_segment_mark_start"), newSponsorSegmentDialogListener)
.setPositiveButton(str("revanced_sb_new_segment_mark_end"), newSponsorSegmentDialogListener)
.show();
} catch (Exception ex) {
Logger.printException(() -> "onMarkLocationClicked failure", ex);
}
}
public static void onPublishClicked() {
try {
Utils.verifyOnMainThread();
if (newSponsorSegmentStartMillis < 0 || newSponsorSegmentEndMillis < 0) {
Utils.showToastShort(str("revanced_sb_new_segment_mark_locations_first"));
} else if (newSponsorSegmentStartMillis >= newSponsorSegmentEndMillis) {
Utils.showToastShort(str("revanced_sb_new_segment_start_is_before_end"));
} else if (!newSponsorSegmentPreviewed && newSponsorSegmentStartMillis != 0) {
Utils.showToastLong(str("revanced_sb_new_segment_preview_segment_first"));
} else {
long length = (newSponsorSegmentEndMillis - newSponsorSegmentStartMillis) / 1000;
long start = (newSponsorSegmentStartMillis) / 1000;
long end = (newSponsorSegmentEndMillis) / 1000;
new AlertDialog.Builder(SponsorBlockViewController.getOverLaysViewGroupContext())
.setTitle(str("revanced_sb_new_segment_confirm_title"))
.setMessage(str("revanced_sb_new_segment_confirm_content",
start / 60, start % 60,
end / 60, end % 60,
length / 60, length % 60))
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, segmentReadyDialogButtonListener)
.show();
}
} catch (Exception ex) {
Logger.printException(() -> "onPublishClicked failure", ex);
}
}
public static void onVotingClicked(@NonNull Context context) {
try {
Utils.verifyOnMainThread();
SponsorSegment[] segments = SegmentPlaybackController.getSegments();
if (segments == null || segments.length == 0) {
// Button is hidden if no segments exist.
// But if prior video had segments, and current video does not,
// then the button persists until the overlay fades out (this is intentional, as abruptly hiding the button is jarring).
Utils.showToastShort(str("revanced_sb_vote_no_segments"));
return;
}
// use same time formatting as shown in the video player
final long videoLength = VideoInformation.getVideoLength();
final String formatPattern;
if (videoLength < (10 * 60 * 1000)) {
formatPattern = "m:ss.SSS"; // less than 10 minutes
} else if (videoLength < (60 * 60 * 1000)) {
formatPattern = "mm:ss.SSS"; // less than 1 hour
} else if (videoLength < (10 * 60 * 60 * 1000)) {
formatPattern = "H:mm:ss.SSS"; // less than 10 hours
} else {
formatPattern = "HH:mm:ss.SSS"; // why is this on YouTube
}
voteSegmentTimeFormatter.applyPattern(formatPattern);
final int numberOfSegments = segments.length;
CharSequence[] titles = new CharSequence[numberOfSegments];
for (int i = 0; i < numberOfSegments; i++) {
SponsorSegment segment = segments[i];
if (segment.category == SegmentCategory.UNSUBMITTED) {
continue;
}
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.append(String.format("<b><font color=\"#%06X\">⬤</font> %s<br>",
segment.category.color, segment.category.title));
htmlBuilder.append(voteSegmentTimeFormatter.format(new Date(segment.start)));
if (segment.category != SegmentCategory.HIGHLIGHT) {
htmlBuilder.append(" to ").append(voteSegmentTimeFormatter.format(new Date(segment.end)));
}
htmlBuilder.append("</b>");
if (i + 1 != numberOfSegments) // prevents trailing new line after last segment
htmlBuilder.append("<br>");
titles[i] = Html.fromHtml(htmlBuilder.toString());
}
new AlertDialog.Builder(context)
.setItems(titles, segmentVoteClickListener)
.show();
} catch (Exception ex) {
Logger.printException(() -> "onVotingClicked failure", ex);
}
}
private static void onNewCategorySelect(@NonNull SponsorSegment segment, @NonNull Context context) {
try {
Utils.verifyOnMainThread();
final SegmentCategory[] values = SegmentCategory.categoriesWithoutHighlights();
CharSequence[] titles = new CharSequence[values.length];
for (int i = 0; i < values.length; i++) {
titles[i] = values[i].getTitleWithColorDot();
}
new AlertDialog.Builder(context)
.setTitle(str("revanced_sb_new_segment_choose_category"))
.setItems(titles, (dialog, which) -> SBRequester.voteToChangeCategoryOnBackgroundThread(segment, values[which]))
.show();
} catch (Exception ex) {
Logger.printException(() -> "onNewCategorySelect failure", ex);
}
}
public static void onPreviewClicked() {
try {
Utils.verifyOnMainThread();
if (newSponsorSegmentStartMillis < 0 || newSponsorSegmentEndMillis < 0) {
Utils.showToastShort(str("revanced_sb_new_segment_mark_locations_first"));
} else if (newSponsorSegmentStartMillis >= newSponsorSegmentEndMillis) {
Utils.showToastShort(str("revanced_sb_new_segment_start_is_before_end"));
} else {
SegmentPlaybackController.removeUnsubmittedSegments(); // If user hits preview more than once before playing.
SegmentPlaybackController.addUnsubmittedSegment(
new SponsorSegment(SegmentCategory.UNSUBMITTED, null,
newSponsorSegmentStartMillis, newSponsorSegmentEndMillis, false));
VideoInformation.seekTo(newSponsorSegmentStartMillis - 2500);
}
} catch (Exception ex) {
Logger.printException(() -> "onPreviewClicked failure", ex);
}
}
static void sendViewRequestAsync(@NonNull SponsorSegment segment) {
if (segment.recordedAsSkipped || segment.category == SegmentCategory.UNSUBMITTED) {
return;
}
segment.recordedAsSkipped = true;
final long totalTimeSkipped = Settings.SB_LOCAL_TIME_SAVED_MILLISECONDS.get() + segment.length();
Settings.SB_LOCAL_TIME_SAVED_MILLISECONDS.save(totalTimeSkipped);
Settings.SB_LOCAL_TIME_SAVED_NUMBER_SEGMENTS.save(Settings.SB_LOCAL_TIME_SAVED_NUMBER_SEGMENTS.get() + 1);
if (Settings.SB_TRACK_SKIP_COUNT.get()) {
Utils.runOnBackgroundThread(() -> SBRequester.sendSegmentSkippedViewedRequest(segment));
}
}
public static void onEditByHandClicked() {
try {
Utils.verifyOnMainThread();
new AlertDialog.Builder(SponsorBlockViewController.getOverLaysViewGroupContext())
.setTitle(str("revanced_sb_new_segment_edit_by_hand_title"))
.setMessage(str("revanced_sb_new_segment_edit_by_hand_content"))
.setNeutralButton(android.R.string.cancel, null)
.setNegativeButton(str("revanced_sb_new_segment_mark_start"), editByHandDialogListener)
.setPositiveButton(str("revanced_sb_new_segment_mark_end"), editByHandDialogListener)
.show();
} catch (Exception ex) {
Logger.printException(() -> "onEditByHandClicked failure", ex);
}
}
public static String getNumberOfSkipsString(int viewCount) {
return statsNumberFormatter.format(viewCount);
}
public static String getTimeSavedString(long totalSecondsSaved) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Duration duration = Duration.ofSeconds(totalSecondsSaved);
final long hours = duration.toHours();
final long minutes = duration.toMinutes() % 60;
// Format all numbers so non-western numbers use a consistent appearance.
String minutesFormatted = statsNumberFormatter.format(minutes);
if (hours > 0) {
String hoursFormatted = statsNumberFormatter.format(hours);
return str("revanced_sb_stats_saved_hour_format", hoursFormatted, minutesFormatted);
}
final long seconds = duration.getSeconds() % 60;
String secondsFormatted = statsNumberFormatter.format(seconds);
if (minutes > 0) {
return str("revanced_sb_stats_saved_minute_format", minutesFormatted, secondsFormatted);
}
return str("revanced_sb_stats_saved_second_format", secondsFormatted);
}
return "error"; // will never be reached. YouTube requires Android O or greater
}
private static class EditByHandSaveDialogListener implements DialogInterface.OnClickListener {
boolean settingStart;
WeakReference<EditText> editText;
@Override
public void onClick(DialogInterface dialog, int which) {
try {
final EditText editText = this.editText.get();
if (editText == null) return;
long time = (which == DialogInterface.BUTTON_NEUTRAL) ?
VideoInformation.getVideoTime() :
(Objects.requireNonNull(manualEditTimeFormatter.parse(editText.getText().toString())).getTime());
if (settingStart)
newSponsorSegmentStartMillis = Math.max(time, 0);
else
newSponsorSegmentEndMillis = time;
if (which == DialogInterface.BUTTON_NEUTRAL)
editByHandDialogListener.onClick(dialog, settingStart ?
DialogInterface.BUTTON_NEGATIVE :
DialogInterface.BUTTON_POSITIVE);
} catch (ParseException e) {
Utils.showToastLong(str("revanced_sb_new_segment_edit_by_hand_parse_error"));
} catch (Exception ex) {
Logger.printException(() -> "EditByHandSaveDialogListener failure", ex);
}
}
}
}
| 22,768 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SponsorBlockSettings.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/SponsorBlockSettings.java | package app.revanced.integrations.youtube.sponsorblock;
import static app.revanced.integrations.shared.StringRef.str;
import android.app.AlertDialog;
import android.content.Context;
import android.util.Patterns;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.UUID;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.shared.settings.Setting;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.sponsorblock.objects.CategoryBehaviour;
import app.revanced.integrations.youtube.sponsorblock.objects.SegmentCategory;
public class SponsorBlockSettings {
/**
* Minimum length a SB user id must be, as set by SB API.
*/
private static final int SB_PRIVATE_USER_ID_MINIMUM_LENGTH = 30;
public static void importDesktopSettings(@NonNull String json) {
Utils.verifyOnMainThread();
try {
JSONObject settingsJson = new JSONObject(json);
JSONObject barTypesObject = settingsJson.getJSONObject("barTypes");
JSONArray categorySelectionsArray = settingsJson.getJSONArray("categorySelections");
for (SegmentCategory category : SegmentCategory.categoriesWithoutUnsubmitted()) {
// clear existing behavior, as browser plugin exports no behavior for ignored categories
category.setBehaviour(CategoryBehaviour.IGNORE);
if (barTypesObject.has(category.keyValue)) {
JSONObject categoryObject = barTypesObject.getJSONObject(category.keyValue);
category.setColor(categoryObject.getString("color"));
}
}
for (int i = 0; i < categorySelectionsArray.length(); i++) {
JSONObject categorySelectionObject = categorySelectionsArray.getJSONObject(i);
String categoryKey = categorySelectionObject.getString("name");
SegmentCategory category = SegmentCategory.byCategoryKey(categoryKey);
if (category == null) {
continue; // unsupported category, ignore
}
final int desktopValue = categorySelectionObject.getInt("option");
CategoryBehaviour behaviour = CategoryBehaviour.byDesktopKeyValue(desktopValue);
if (behaviour == null) {
Utils.showToastLong(categoryKey + " unknown behavior key: " + categoryKey);
} else if (category == SegmentCategory.HIGHLIGHT && behaviour == CategoryBehaviour.SKIP_AUTOMATICALLY_ONCE) {
Utils.showToastLong("Skip-once behavior not allowed for " + category.keyValue);
category.setBehaviour(CategoryBehaviour.SKIP_AUTOMATICALLY); // use closest match
} else {
category.setBehaviour(behaviour);
}
}
SegmentCategory.updateEnabledCategories();
if (settingsJson.has("userID")) {
// User id does not exist if user never voted or created any segments.
String userID = settingsJson.getString("userID");
if (isValidSBUserId(userID)) {
Settings.SB_PRIVATE_USER_ID.save(userID);
}
}
Settings.SB_USER_IS_VIP.save(settingsJson.getBoolean("isVip"));
Settings.SB_TOAST_ON_SKIP.save(!settingsJson.getBoolean("dontShowNotice"));
Settings.SB_TRACK_SKIP_COUNT.save(settingsJson.getBoolean("trackViewCount"));
Settings.SB_VIDEO_LENGTH_WITHOUT_SEGMENTS.save(settingsJson.getBoolean("showTimeWithSkips"));
String serverAddress = settingsJson.getString("serverAddress");
if (isValidSBServerAddress(serverAddress)) { // Old versions of ReVanced exported wrong url format
Settings.SB_API_URL.save(serverAddress);
}
final float minDuration = (float) settingsJson.getDouble("minDuration");
if (minDuration < 0) {
throw new IllegalArgumentException("invalid minDuration: " + minDuration);
}
Settings.SB_SEGMENT_MIN_DURATION.save(minDuration);
if (settingsJson.has("skipCount")) { // Value not exported in old versions of ReVanced
int skipCount = settingsJson.getInt("skipCount");
if (skipCount < 0) {
throw new IllegalArgumentException("invalid skipCount: " + skipCount);
}
Settings.SB_LOCAL_TIME_SAVED_NUMBER_SEGMENTS.save(skipCount);
}
if (settingsJson.has("minutesSaved")) {
final double minutesSaved = settingsJson.getDouble("minutesSaved");
if (minutesSaved < 0) {
throw new IllegalArgumentException("invalid minutesSaved: " + minutesSaved);
}
Settings.SB_LOCAL_TIME_SAVED_MILLISECONDS.save((long) (minutesSaved * 60 * 1000));
}
Utils.showToastLong(str("revanced_sb_settings_import_successful"));
} catch (Exception ex) {
Logger.printInfo(() -> "failed to import settings", ex); // use info level, as we are showing our own toast
Utils.showToastLong(str("revanced_sb_settings_import_failed", ex.getMessage()));
}
}
@NonNull
public static String exportDesktopSettings() {
Utils.verifyOnMainThread();
try {
Logger.printDebug(() -> "Creating SponsorBlock export settings string");
JSONObject json = new JSONObject();
JSONObject barTypesObject = new JSONObject(); // categories' colors
JSONArray categorySelectionsArray = new JSONArray(); // categories' behavior
SegmentCategory[] categories = SegmentCategory.categoriesWithoutUnsubmitted();
for (SegmentCategory category : categories) {
JSONObject categoryObject = new JSONObject();
String categoryKey = category.keyValue;
categoryObject.put("color", category.colorString());
barTypesObject.put(categoryKey, categoryObject);
if (category.behaviour != CategoryBehaviour.IGNORE) {
JSONObject behaviorObject = new JSONObject();
behaviorObject.put("name", categoryKey);
behaviorObject.put("option", category.behaviour.desktopKeyValue);
categorySelectionsArray.put(behaviorObject);
}
}
if (SponsorBlockSettings.userHasSBPrivateId()) {
json.put("userID", Settings.SB_PRIVATE_USER_ID.get());
}
json.put("isVip", Settings.SB_USER_IS_VIP.get());
json.put("serverAddress", Settings.SB_API_URL.get());
json.put("dontShowNotice", !Settings.SB_TOAST_ON_SKIP.get());
json.put("showTimeWithSkips", Settings.SB_VIDEO_LENGTH_WITHOUT_SEGMENTS.get());
json.put("minDuration", Settings.SB_SEGMENT_MIN_DURATION.get());
json.put("trackViewCount", Settings.SB_TRACK_SKIP_COUNT.get());
json.put("skipCount", Settings.SB_LOCAL_TIME_SAVED_NUMBER_SEGMENTS.get());
json.put("minutesSaved", Settings.SB_LOCAL_TIME_SAVED_MILLISECONDS.get() / (60f * 1000));
json.put("categorySelections", categorySelectionsArray);
json.put("barTypes", barTypesObject);
return json.toString(2);
} catch (Exception ex) {
Logger.printInfo(() -> "failed to export settings", ex); // use info level, as we are showing our own toast
Utils.showToastLong(str("revanced_sb_settings_export_failed", ex));
return "";
}
}
/**
* Export the categories using flatten json (no embedded dictionaries or arrays).
*/
public static void showExportWarningIfNeeded(@Nullable Context dialogContext) {
Utils.verifyOnMainThread();
initialize();
// If user has a SponsorBlock user id then show a warning.
if (dialogContext != null && SponsorBlockSettings.userHasSBPrivateId()
&& !Settings.SB_HIDE_EXPORT_WARNING.get()) {
new AlertDialog.Builder(dialogContext)
.setMessage(str("revanced_sb_settings_revanced_export_user_id_warning"))
.setNeutralButton(str("revanced_sb_settings_revanced_export_user_id_warning_dismiss"),
(dialog, which) -> Settings.SB_HIDE_EXPORT_WARNING.save(true))
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false)
.show();
}
}
public static boolean isValidSBUserId(@NonNull String userId) {
return !userId.isEmpty() && userId.length() >= SB_PRIVATE_USER_ID_MINIMUM_LENGTH;
}
/**
* A non comprehensive check if a SB api server address is valid.
*/
public static boolean isValidSBServerAddress(@NonNull String serverAddress) {
if (!Patterns.WEB_URL.matcher(serverAddress).matches()) {
return false;
}
// Verify url is only the server address and does not contain a path such as: "https://sponsor.ajay.app/api/"
// Could use Patterns.compile, but this is simpler
final int lastDotIndex = serverAddress.lastIndexOf('.');
if (lastDotIndex != -1 && serverAddress.substring(lastDotIndex).contains("/")) {
return false;
}
// Optionally, could also verify the domain exists using "InetAddress.getByName(serverAddress)"
// but that should not be done on the main thread.
// Instead, assume the domain exists and the user knows what they're doing.
return true;
}
/**
* @return if the user has ever voted, created a segment, or imported existing SB settings.
*/
public static boolean userHasSBPrivateId() {
return !Settings.SB_PRIVATE_USER_ID.get().isEmpty();
}
/**
* Use this only if a user id is required (creating segments, voting).
*/
@NonNull
public static String getSBPrivateUserID() {
String uuid = Settings.SB_PRIVATE_USER_ID.get();
if (uuid.isEmpty()) {
uuid = (UUID.randomUUID().toString() +
UUID.randomUUID().toString() +
UUID.randomUUID().toString())
.replace("-", "");
Settings.SB_PRIVATE_USER_ID.save(uuid);
}
return uuid;
}
private static boolean initialized;
public static void initialize() {
if (initialized) {
return;
}
initialized = true;
SegmentCategory.updateEnabledCategories();
}
/**
* Updates internal data based on {@link Setting} values.
*/
public static void updateFromImportedSettings() {
SegmentCategory.loadAllCategoriesFromSettings();
}
}
| 11,091 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SegmentCategory.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/objects/SegmentCategory.java | package app.revanced.integrations.youtube.sponsorblock.objects;
import static app.revanced.integrations.youtube.settings.Settings.*;
import static app.revanced.integrations.shared.StringRef.sf;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.shared.settings.StringSetting;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.StringRef;
public enum SegmentCategory {
SPONSOR("sponsor", sf("revanced_sb_segments_sponsor"), sf("revanced_sb_segments_sponsor_sum"), sf("revanced_sb_skip_button_sponsor"), sf("revanced_sb_skipped_sponsor"),
SB_CATEGORY_SPONSOR, SB_CATEGORY_SPONSOR_COLOR),
SELF_PROMO("selfpromo", sf("revanced_sb_segments_selfpromo"), sf("revanced_sb_segments_selfpromo_sum"), sf("revanced_sb_skip_button_selfpromo"), sf("revanced_sb_skipped_selfpromo"),
SB_CATEGORY_SELF_PROMO, SB_CATEGORY_SELF_PROMO_COLOR),
INTERACTION("interaction", sf("revanced_sb_segments_interaction"), sf("revanced_sb_segments_interaction_sum"), sf("revanced_sb_skip_button_interaction"), sf("revanced_sb_skipped_interaction"),
SB_CATEGORY_INTERACTION, SB_CATEGORY_INTERACTION_COLOR),
/**
* Unique category that is treated differently than the rest.
*/
HIGHLIGHT("poi_highlight", sf("revanced_sb_segments_highlight"), sf("revanced_sb_segments_highlight_sum"), sf("revanced_sb_skip_button_highlight"), sf("revanced_sb_skipped_highlight"),
SB_CATEGORY_HIGHLIGHT, SB_CATEGORY_HIGHLIGHT_COLOR),
INTRO("intro", sf("revanced_sb_segments_intro"), sf("revanced_sb_segments_intro_sum"),
sf("revanced_sb_skip_button_intro_beginning"), sf("revanced_sb_skip_button_intro_middle"), sf("revanced_sb_skip_button_intro_end"),
sf("revanced_sb_skipped_intro_beginning"), sf("revanced_sb_skipped_intro_middle"), sf("revanced_sb_skipped_intro_end"),
SB_CATEGORY_INTRO, SB_CATEGORY_INTRO_COLOR),
OUTRO("outro", sf("revanced_sb_segments_outro"), sf("revanced_sb_segments_outro_sum"), sf("revanced_sb_skip_button_outro"), sf("revanced_sb_skipped_outro"),
SB_CATEGORY_OUTRO, SB_CATEGORY_OUTRO_COLOR),
PREVIEW("preview", sf("revanced_sb_segments_preview"), sf("revanced_sb_segments_preview_sum"),
sf("revanced_sb_skip_button_preview_beginning"), sf("revanced_sb_skip_button_preview_middle"), sf("revanced_sb_skip_button_preview_end"),
sf("revanced_sb_skipped_preview_beginning"), sf("revanced_sb_skipped_preview_middle"), sf("revanced_sb_skipped_preview_end"),
SB_CATEGORY_PREVIEW, SB_CATEGORY_PREVIEW_COLOR),
FILLER("filler", sf("revanced_sb_segments_filler"), sf("revanced_sb_segments_filler_sum"), sf("revanced_sb_skip_button_filler"), sf("revanced_sb_skipped_filler"),
SB_CATEGORY_FILLER, SB_CATEGORY_FILLER_COLOR),
MUSIC_OFFTOPIC("music_offtopic", sf("revanced_sb_segments_nomusic"), sf("revanced_sb_segments_nomusic_sum"), sf("revanced_sb_skip_button_nomusic"), sf("revanced_sb_skipped_nomusic"),
SB_CATEGORY_MUSIC_OFFTOPIC, SB_CATEGORY_MUSIC_OFFTOPIC_COLOR),
UNSUBMITTED("unsubmitted", StringRef.empty, StringRef.empty, sf("revanced_sb_skip_button_unsubmitted"), sf("revanced_sb_skipped_unsubmitted"),
SB_CATEGORY_UNSUBMITTED, SB_CATEGORY_UNSUBMITTED_COLOR),;
private static final StringRef skipSponsorTextCompact = sf("revanced_sb_skip_button_compact");
private static final StringRef skipSponsorTextCompactHighlight = sf("revanced_sb_skip_button_compact_highlight");
private static final SegmentCategory[] categoriesWithoutHighlights = new SegmentCategory[]{
SPONSOR,
SELF_PROMO,
INTERACTION,
INTRO,
OUTRO,
PREVIEW,
FILLER,
MUSIC_OFFTOPIC,
};
private static final SegmentCategory[] categoriesWithoutUnsubmitted = new SegmentCategory[]{
SPONSOR,
SELF_PROMO,
INTERACTION,
HIGHLIGHT,
INTRO,
OUTRO,
PREVIEW,
FILLER,
MUSIC_OFFTOPIC,
};
private static final Map<String, SegmentCategory> mValuesMap = new HashMap<>(2 * categoriesWithoutUnsubmitted.length);
/**
* Categories currently enabled, formatted for an API call
*/
public static String sponsorBlockAPIFetchCategories = "[]";
static {
for (SegmentCategory value : categoriesWithoutUnsubmitted)
mValuesMap.put(value.keyValue, value);
}
@NonNull
public static SegmentCategory[] categoriesWithoutUnsubmitted() {
return categoriesWithoutUnsubmitted;
}
@NonNull
public static SegmentCategory[] categoriesWithoutHighlights() {
return categoriesWithoutHighlights;
}
@Nullable
public static SegmentCategory byCategoryKey(@NonNull String key) {
return mValuesMap.get(key);
}
/**
* Must be called if behavior of any category is changed
*/
public static void updateEnabledCategories() {
Utils.verifyOnMainThread();
Logger.printDebug(() -> "updateEnabledCategories");
SegmentCategory[] categories = categoriesWithoutUnsubmitted();
List<String> enabledCategories = new ArrayList<>(categories.length);
for (SegmentCategory category : categories) {
if (category.behaviour != CategoryBehaviour.IGNORE) {
enabledCategories.add(category.keyValue);
}
}
//"[%22sponsor%22,%22outro%22,%22music_offtopic%22,%22intro%22,%22selfpromo%22,%22interaction%22,%22preview%22]";
if (enabledCategories.isEmpty())
sponsorBlockAPIFetchCategories = "[]";
else
sponsorBlockAPIFetchCategories = "[%22" + TextUtils.join("%22,%22", enabledCategories) + "%22]";
}
public static void loadAllCategoriesFromSettings() {
for (SegmentCategory category : values()) {
category.loadFromSettings();
}
updateEnabledCategories();
}
@NonNull
public final String keyValue;
@NonNull
private final StringSetting behaviorSetting;
@NonNull
private final StringSetting colorSetting;
@NonNull
public final StringRef title;
@NonNull
public final StringRef description;
/**
* Skip button text, if the skip occurs in the first quarter of the video
*/
@NonNull
public final StringRef skipButtonTextBeginning;
/**
* Skip button text, if the skip occurs in the middle half of the video
*/
@NonNull
public final StringRef skipButtonTextMiddle;
/**
* Skip button text, if the skip occurs in the last quarter of the video
*/
@NonNull
public final StringRef skipButtonTextEnd;
/**
* Skipped segment toast, if the skip occurred in the first quarter of the video
*/
@NonNull
public final StringRef skippedToastBeginning;
/**
* Skipped segment toast, if the skip occurred in the middle half of the video
*/
@NonNull
public final StringRef skippedToastMiddle;
/**
* Skipped segment toast, if the skip occurred in the last quarter of the video
*/
@NonNull
public final StringRef skippedToastEnd;
@NonNull
public final Paint paint;
/**
* Value must be changed using {@link #setColor(String)}.
*/
public int color;
/**
* Value must be changed using {@link #setBehaviour(CategoryBehaviour)}.
* Caller must also {@link #updateEnabledCategories()}.
*/
@NonNull
public CategoryBehaviour behaviour = CategoryBehaviour.IGNORE;
SegmentCategory(String keyValue, StringRef title, StringRef description,
StringRef skipButtonText,
StringRef skippedToastText,
StringSetting behavior, StringSetting color) {
this(keyValue, title, description,
skipButtonText, skipButtonText, skipButtonText,
skippedToastText, skippedToastText, skippedToastText,
behavior, color);
}
SegmentCategory(String keyValue, StringRef title, StringRef description,
StringRef skipButtonTextBeginning, StringRef skipButtonTextMiddle, StringRef skipButtonTextEnd,
StringRef skippedToastBeginning, StringRef skippedToastMiddle, StringRef skippedToastEnd,
StringSetting behavior, StringSetting color) {
this.keyValue = Objects.requireNonNull(keyValue);
this.title = Objects.requireNonNull(title);
this.description = Objects.requireNonNull(description);
this.skipButtonTextBeginning = Objects.requireNonNull(skipButtonTextBeginning);
this.skipButtonTextMiddle = Objects.requireNonNull(skipButtonTextMiddle);
this.skipButtonTextEnd = Objects.requireNonNull(skipButtonTextEnd);
this.skippedToastBeginning = Objects.requireNonNull(skippedToastBeginning);
this.skippedToastMiddle = Objects.requireNonNull(skippedToastMiddle);
this.skippedToastEnd = Objects.requireNonNull(skippedToastEnd);
this.behaviorSetting = Objects.requireNonNull(behavior);
this.colorSetting = Objects.requireNonNull(color);
this.paint = new Paint();
loadFromSettings();
}
private void loadFromSettings() {
String behaviorString = behaviorSetting.get();
CategoryBehaviour savedBehavior = CategoryBehaviour.byReVancedKeyValue(behaviorString);
if (savedBehavior == null) {
Logger.printException(() -> "Invalid behavior: " + behaviorString);
behaviorSetting.resetToDefault();
loadFromSettings();
return;
}
this.behaviour = savedBehavior;
String colorString = colorSetting.get();
try {
setColor(colorString);
} catch (Exception ex) {
Logger.printException(() -> "Invalid color: " + colorString, ex);
colorSetting.resetToDefault();
loadFromSettings();
}
}
public void setBehaviour(@NonNull CategoryBehaviour behaviour) {
this.behaviour = Objects.requireNonNull(behaviour);
this.behaviorSetting.save(behaviour.reVancedKeyValue);
}
/**
* @return HTML color format string
*/
@NonNull
public String colorString() {
return String.format("#%06X", color);
}
public void setColor(@NonNull String colorString) throws IllegalArgumentException {
final int color = Color.parseColor(colorString) & 0xFFFFFF;
this.color = color;
paint.setColor(color);
paint.setAlpha(255);
colorSetting.save(colorString); // Save after parsing.
}
public void resetColor() {
setColor(colorSetting.defaultValue);
}
@NonNull
private static String getCategoryColorDotHTML(int color) {
color &= 0xFFFFFF;
return String.format("<font color=\"#%06X\">⬤</font>", color);
}
@NonNull
public static Spanned getCategoryColorDot(int color) {
return Html.fromHtml(getCategoryColorDotHTML(color));
}
@NonNull
public Spanned getCategoryColorDot() {
return getCategoryColorDot(color);
}
@NonNull
public Spanned getTitleWithColorDot() {
return Html.fromHtml(getCategoryColorDotHTML(color) + " " + title);
}
/**
* @param segmentStartTime video time the segment category started
* @param videoLength length of the video
* @return the skip button text
*/
@NonNull
StringRef getSkipButtonText(long segmentStartTime, long videoLength) {
if (Settings.SB_COMPACT_SKIP_BUTTON.get()) {
return (this == SegmentCategory.HIGHLIGHT)
? skipSponsorTextCompactHighlight
: skipSponsorTextCompact;
}
if (videoLength == 0) {
return skipButtonTextBeginning; // video is still loading. Assume it's the beginning
}
final float position = segmentStartTime / (float) videoLength;
if (position < 0.25f) {
return skipButtonTextBeginning;
} else if (position < 0.75f) {
return skipButtonTextMiddle;
}
return skipButtonTextEnd;
}
/**
* @param segmentStartTime video time the segment category started
* @param videoLength length of the video
* @return 'skipped segment' toast message
*/
@NonNull
StringRef getSkippedToastText(long segmentStartTime, long videoLength) {
if (videoLength == 0) {
return skippedToastBeginning; // video is still loading. Assume it's the beginning
}
final float position = segmentStartTime / (float) videoLength;
if (position < 0.25f) {
return skippedToastBeginning;
} else if (position < 0.75f) {
return skippedToastMiddle;
}
return skippedToastEnd;
}
}
| 13,384 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
CategoryBehaviour.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/objects/CategoryBehaviour.java | package app.revanced.integrations.youtube.sponsorblock.objects;
import static app.revanced.integrations.shared.StringRef.sf;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Objects;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.shared.StringRef;
public enum CategoryBehaviour {
SKIP_AUTOMATICALLY("skip", 2, true, sf("revanced_sb_skip_automatically")),
// desktop does not have skip-once behavior. Key is unique to ReVanced
SKIP_AUTOMATICALLY_ONCE("skip-once", 3, true, sf("revanced_sb_skip_automatically_once")),
MANUAL_SKIP("manual-skip", 1, false, sf("revanced_sb_skip_showbutton")),
SHOW_IN_SEEKBAR("seekbar-only", 0, false, sf("revanced_sb_skip_seekbaronly")),
// ignored categories are not exported to json, and ignore is the default behavior when importing
IGNORE("ignore", -1, false, sf("revanced_sb_skip_ignore"));
/**
* ReVanced specific value.
*/
@NonNull
public final String reVancedKeyValue;
/**
* Desktop specific value.
*/
public final int desktopKeyValue;
/**
* If the segment should skip automatically
*/
public final boolean skipAutomatically;
@NonNull
public final StringRef description;
CategoryBehaviour(String reVancedKeyValue, int desktopKeyValue, boolean skipAutomatically, StringRef description) {
this.reVancedKeyValue = Objects.requireNonNull(reVancedKeyValue);
this.desktopKeyValue = desktopKeyValue;
this.skipAutomatically = skipAutomatically;
this.description = Objects.requireNonNull(description);
}
@Nullable
public static CategoryBehaviour byReVancedKeyValue(@NonNull String keyValue) {
for (CategoryBehaviour behaviour : values()){
if (behaviour.reVancedKeyValue.equals(keyValue)) {
return behaviour;
}
}
return null;
}
@Nullable
public static CategoryBehaviour byDesktopKeyValue(int desktopKeyValue) {
for (CategoryBehaviour behaviour : values()) {
if (behaviour.desktopKeyValue == desktopKeyValue) {
return behaviour;
}
}
return null;
}
private static String[] behaviorKeyValues;
private static String[] behaviorDescriptions;
private static String[] behaviorKeyValuesWithoutSkipOnce;
private static String[] behaviorDescriptionsWithoutSkipOnce;
private static void createNameAndKeyArrays() {
Utils.verifyOnMainThread();
CategoryBehaviour[] behaviours = values();
final int behaviorLength = behaviours.length;
behaviorKeyValues = new String[behaviorLength];
behaviorDescriptions = new String[behaviorLength];
behaviorKeyValuesWithoutSkipOnce = new String[behaviorLength - 1];
behaviorDescriptionsWithoutSkipOnce = new String[behaviorLength - 1];
int behaviorIndex = 0, behaviorHighlightIndex = 0;
while (behaviorIndex < behaviorLength) {
CategoryBehaviour behaviour = behaviours[behaviorIndex];
String value = behaviour.reVancedKeyValue;
String description = behaviour.description.toString();
behaviorKeyValues[behaviorIndex] = value;
behaviorDescriptions[behaviorIndex] = description;
behaviorIndex++;
if (behaviour != SKIP_AUTOMATICALLY_ONCE) {
behaviorKeyValuesWithoutSkipOnce[behaviorHighlightIndex] = value;
behaviorDescriptionsWithoutSkipOnce[behaviorHighlightIndex] = description;
behaviorHighlightIndex++;
}
}
}
static String[] getBehaviorKeyValues() {
if (behaviorKeyValues == null) {
createNameAndKeyArrays();
}
return behaviorKeyValues;
}
static String[] getBehaviorKeyValuesWithoutSkipOnce() {
if (behaviorKeyValuesWithoutSkipOnce == null) {
createNameAndKeyArrays();
}
return behaviorKeyValuesWithoutSkipOnce;
}
static String[] getBehaviorDescriptions() {
if (behaviorDescriptions == null) {
createNameAndKeyArrays();
}
return behaviorDescriptions;
}
static String[] getBehaviorDescriptionsWithoutSkipOnce() {
if (behaviorDescriptionsWithoutSkipOnce == null) {
createNameAndKeyArrays();
}
return behaviorDescriptionsWithoutSkipOnce;
}
}
| 4,487 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SegmentCategoryListPreference.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/objects/SegmentCategoryListPreference.java | package app.revanced.integrations.youtube.sponsorblock.objects;
import static app.revanced.integrations.shared.StringRef.str;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.preference.ListPreference;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.util.Objects;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
public class SegmentCategoryListPreference extends ListPreference {
private final SegmentCategory category;
private EditText mEditText;
private int mClickedDialogEntryIndex;
public SegmentCategoryListPreference(Context context, SegmentCategory category) {
super(context);
final boolean isHighlightCategory = category == SegmentCategory.HIGHLIGHT;
this.category = Objects.requireNonNull(category);
setKey(category.keyValue);
setDefaultValue(category.behaviour.reVancedKeyValue);
setEntries(isHighlightCategory
? CategoryBehaviour.getBehaviorDescriptionsWithoutSkipOnce()
: CategoryBehaviour.getBehaviorDescriptions());
setEntryValues(isHighlightCategory
? CategoryBehaviour.getBehaviorKeyValuesWithoutSkipOnce()
: CategoryBehaviour.getBehaviorKeyValues());
setSummary(category.description.toString());
updateTitle();
}
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
try {
Context context = builder.getContext();
TableLayout table = new TableLayout(context);
table.setOrientation(LinearLayout.HORIZONTAL);
table.setPadding(70, 0, 150, 0);
TableRow row = new TableRow(context);
TextView colorTextLabel = new TextView(context);
colorTextLabel.setText(str("revanced_sb_color_dot_label"));
row.addView(colorTextLabel);
TextView colorDotView = new TextView(context);
colorDotView.setText(category.getCategoryColorDot());
colorDotView.setPadding(30, 0, 30, 0);
row.addView(colorDotView);
mEditText = new EditText(context);
mEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
mEditText.setText(category.colorString());
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
try {
String colorString = s.toString();
if (!colorString.startsWith("#")) {
s.insert(0, "#"); // recursively calls back into this method
return;
}
if (colorString.length() > 7) {
s.delete(7, colorString.length());
return;
}
final int color = Color.parseColor(colorString);
colorDotView.setText(SegmentCategory.getCategoryColorDot(color));
} catch (IllegalArgumentException ex) {
// ignore
}
}
});
mEditText.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1f));
row.addView(mEditText);
table.addView(row);
builder.setView(table);
builder.setTitle(category.title.toString());
builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
onClick(dialog, DialogInterface.BUTTON_POSITIVE);
});
builder.setNeutralButton(str("revanced_sb_reset_color"), (dialog, which) -> {
try {
category.resetColor();
updateTitle();
Utils.showToastShort(str("revanced_sb_color_reset"));
} catch (Exception ex) {
Logger.printException(() -> "setNeutralButton failure", ex);
}
});
builder.setNegativeButton(android.R.string.cancel, null);
mClickedDialogEntryIndex = findIndexOfValue(getValue());
builder.setSingleChoiceItems(getEntries(), mClickedDialogEntryIndex, (dialog, which) -> mClickedDialogEntryIndex = which);
} catch (Exception ex) {
Logger.printException(() -> "onPrepareDialogBuilder failure", ex);
}
}
@Override
protected void onDialogClosed(boolean positiveResult) {
try {
if (positiveResult && mClickedDialogEntryIndex >= 0 && getEntryValues() != null) {
String value = getEntryValues()[mClickedDialogEntryIndex].toString();
if (callChangeListener(value)) {
setValue(value);
category.setBehaviour(Objects.requireNonNull(CategoryBehaviour.byReVancedKeyValue(value)));
SegmentCategory.updateEnabledCategories();
}
String colorString = mEditText.getText().toString();
try {
if (!colorString.equals(category.colorString())) {
category.setColor(colorString);
Utils.showToastShort(str("revanced_sb_color_changed"));
}
} catch (IllegalArgumentException ex) {
Utils.showToastShort(str("revanced_sb_color_invalid"));
}
updateTitle();
}
} catch (Exception ex) {
Logger.printException(() -> "onDialogClosed failure", ex);
}
}
private void updateTitle() {
setTitle(category.getTitleWithColorDot());
}
} | 6,385 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SponsorSegment.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/objects/SponsorSegment.java | package app.revanced.integrations.youtube.sponsorblock.objects;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import app.revanced.integrations.youtube.patches.VideoInformation;
import app.revanced.integrations.shared.StringRef;
import java.util.Objects;
import static app.revanced.integrations.shared.StringRef.sf;
public class SponsorSegment implements Comparable<SponsorSegment> {
public enum SegmentVote {
UPVOTE(sf("revanced_sb_vote_upvote"), 1,false),
DOWNVOTE(sf("revanced_sb_vote_downvote"), 0, true),
CATEGORY_CHANGE(sf("revanced_sb_vote_category"), -1, true); // apiVoteType is not used for category change
public static final SegmentVote[] voteTypesWithoutCategoryChange = {
UPVOTE,
DOWNVOTE,
};
@NonNull
public final StringRef title;
public final int apiVoteType;
public final boolean shouldHighlight;
SegmentVote(@NonNull StringRef title, int apiVoteType, boolean shouldHighlight) {
this.title = title;
this.apiVoteType = apiVoteType;
this.shouldHighlight = shouldHighlight;
}
}
@NonNull
public final SegmentCategory category;
/**
* NULL if segment is unsubmitted
*/
@Nullable
public final String UUID;
public final long start;
public final long end;
public final boolean isLocked;
public boolean didAutoSkipped = false;
/**
* If this segment has been counted as 'skipped'
*/
public boolean recordedAsSkipped = false;
public SponsorSegment(@NonNull SegmentCategory category, @Nullable String UUID, long start, long end, boolean isLocked) {
this.category = category;
this.UUID = UUID;
this.start = start;
this.end = end;
this.isLocked = isLocked;
}
public boolean shouldAutoSkip() {
return category.behaviour.skipAutomatically && !(didAutoSkipped && category.behaviour == CategoryBehaviour.SKIP_AUTOMATICALLY_ONCE);
}
/**
* @param nearThreshold threshold to declare the time parameter is near this segment. Must be a positive number
*/
public boolean startIsNear(long videoTime, long nearThreshold) {
return Math.abs(start - videoTime) <= nearThreshold;
}
/**
* @param nearThreshold threshold to declare the time parameter is near this segment. Must be a positive number
*/
public boolean endIsNear(long videoTime, long nearThreshold) {
return Math.abs(end - videoTime) <= nearThreshold;
}
/**
* @return if the time parameter is within this segment
*/
public boolean containsTime(long videoTime) {
return start <= videoTime && videoTime < end;
}
/**
* @return if the segment is completely contained inside this segment
*/
public boolean containsSegment(SponsorSegment other) {
return start <= other.start && other.end <= end;
}
/**
* @return the length of this segment, in milliseconds. Always a positive number.
*/
public long length() {
return end - start;
}
/**
* @return 'skip segment' UI overlay button text
*/
@NonNull
public String getSkipButtonText() {
return category.getSkipButtonText(start, VideoInformation.getVideoLength()).toString();
}
/**
* @return 'skipped segment' toast message
*/
@NonNull
public String getSkippedToastText() {
return category.getSkippedToastText(start, VideoInformation.getVideoLength()).toString();
}
@Override
public int compareTo(SponsorSegment o) {
// If both segments start at the same time, then sort with the longer segment first.
// This keeps the seekbar drawing correct since it draws the segments using the sorted order.
return start == o.start ? Long.compare(o.length(), length()) : Long.compare(start, o.start);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SponsorSegment)) return false;
SponsorSegment other = (SponsorSegment) o;
return Objects.equals(UUID, other.UUID)
&& category == other.category
&& start == other.start
&& end == other.end;
}
@Override
public int hashCode() {
return Objects.hashCode(UUID);
}
@NonNull
@Override
public String toString() {
return "SponsorSegment{"
+ "category=" + category
+ ", start=" + start
+ ", end=" + end
+ '}';
}
}
| 4,664 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
UserStats.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/objects/UserStats.java | package app.revanced.integrations.youtube.sponsorblock.objects;
import androidx.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;
/**
* SponsorBlock user stats
*/
public class UserStats {
@NonNull
public final String publicUserId;
@NonNull
public final String userName;
/**
* "User reputation". Unclear how SB determines this value.
*/
public final float reputation;
/**
* {@link #segmentCount} plus {@link #ignoredSegmentCount}
*/
public final int totalSegmentCountIncludingIgnored;
public final int segmentCount;
public final int ignoredSegmentCount;
public final int viewCount;
public final double minutesSaved;
public UserStats(@NonNull JSONObject json) throws JSONException {
publicUserId = json.getString("userID");
userName = json.getString("userName");
reputation = (float)json.getDouble("reputation");
segmentCount = json.getInt("segmentCount");
ignoredSegmentCount = json.getInt("ignoredSegmentCount");
totalSegmentCountIncludingIgnored = segmentCount + ignoredSegmentCount;
viewCount = json.getInt("viewCount");
minutesSaved = json.getDouble("minutesSaved");
}
@NonNull
@Override
public String toString() {
return "UserStats{"
+ "publicUserId='" + publicUserId + '\''
+ ", userName='" + userName + '\''
+ ", reputation=" + reputation
+ ", segmentCount=" + segmentCount
+ ", ignoredSegmentCount=" + ignoredSegmentCount
+ ", viewCount=" + viewCount
+ ", minutesSaved=" + minutesSaved
+ '}';
}
} | 1,732 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
NewSegmentLayout.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/ui/NewSegmentLayout.java | package app.revanced.integrations.youtube.sponsorblock.ui;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.RippleDrawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import app.revanced.integrations.youtube.patches.VideoInformation;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.sponsorblock.SponsorBlockUtils;
import app.revanced.integrations.shared.Logger;
import static app.revanced.integrations.shared.Utils.getResourceDimensionPixelSize;
import static app.revanced.integrations.shared.Utils.getResourceIdentifier;
public final class NewSegmentLayout extends FrameLayout {
private static final ColorStateList rippleColorStateList = new ColorStateList(
new int[][]{new int[]{android.R.attr.state_enabled}},
new int[]{0x33ffffff} // sets the ripple color to white
);
private final int rippleEffectId;
final int defaultBottomMargin;
final int ctaBottomMargin;
public NewSegmentLayout(final Context context) {
this(context, null);
}
public NewSegmentLayout(final Context context, final AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public NewSegmentLayout(final Context context, final AttributeSet attributeSet, final int defStyleAttr) {
this(context, attributeSet, defStyleAttr, 0);
}
public NewSegmentLayout(final Context context, final AttributeSet attributeSet,
final int defStyleAttr, final int defStyleRes) {
super(context, attributeSet, defStyleAttr, defStyleRes);
LayoutInflater.from(context).inflate(
getResourceIdentifier(context, "revanced_sb_new_segment", "layout"), this, true
);
TypedValue rippleEffect = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, rippleEffect, true);
rippleEffectId = rippleEffect.resourceId;
initializeButton(
context,
"revanced_sb_new_segment_rewind",
() -> VideoInformation.seekToRelative(-Settings.SB_CREATE_NEW_SEGMENT_STEP.get()),
"Rewind button clicked"
);
initializeButton(
context,
"revanced_sb_new_segment_forward",
() -> VideoInformation.seekToRelative(Settings.SB_CREATE_NEW_SEGMENT_STEP.get()),
"Forward button clicked"
);
initializeButton(
context,
"revanced_sb_new_segment_adjust",
SponsorBlockUtils::onMarkLocationClicked,
"Adjust button clicked"
);
initializeButton(
context,
"revanced_sb_new_segment_compare",
SponsorBlockUtils::onPreviewClicked,
"Compare button clicked"
);
initializeButton(
context,
"revanced_sb_new_segment_edit",
SponsorBlockUtils::onEditByHandClicked,
"Edit button clicked"
);
initializeButton(
context,
"revanced_sb_new_segment_publish",
SponsorBlockUtils::onPublishClicked,
"Publish button clicked"
);
defaultBottomMargin = getResourceDimensionPixelSize("brand_interaction_default_bottom_margin");
ctaBottomMargin = getResourceDimensionPixelSize("brand_interaction_cta_bottom_margin");
}
/**
* Initializes a segment button with the given resource identifier name with the given handler and a ripple effect.
*
* @param context The context.
* @param resourceIdentifierName The resource identifier name for the button.
* @param handler The handler for the button's click event.
* @param debugMessage The debug message to print when the button is clicked.
*/
private void initializeButton(final Context context, final String resourceIdentifierName,
final ButtonOnClickHandlerFunction handler, final String debugMessage) {
final ImageButton button = findViewById(getResourceIdentifier(context, resourceIdentifierName, "id"));
// Add ripple effect
button.setBackgroundResource(rippleEffectId);
RippleDrawable rippleDrawable = (RippleDrawable) button.getBackground();
rippleDrawable.setColor(rippleColorStateList);
button.setOnClickListener((v) -> {
handler.apply();
Logger.printDebug(() -> debugMessage);
});
}
@FunctionalInterface
public interface ButtonOnClickHandlerFunction {
void apply();
}
}
| 4,910 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
CreateSegmentButtonController.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/ui/CreateSegmentButtonController.java | package app.revanced.integrations.youtube.sponsorblock.ui;
import static app.revanced.integrations.shared.Utils.getResourceIdentifier;
import android.view.View;
import android.widget.ImageView;
import java.lang.ref.WeakReference;
import java.util.Objects;
import app.revanced.integrations.youtube.patches.VideoInformation;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.youtube.videoplayer.BottomControlButton;
public class CreateSegmentButtonController {
private static WeakReference<ImageView> buttonReference = new WeakReference<>(null);
private static boolean isShowing;
/**
* injection point
*/
public static void initialize(View youtubeControlsLayout) {
try {
Logger.printDebug(() -> "initializing new segment button");
ImageView imageView = Objects.requireNonNull(youtubeControlsLayout.findViewById(
getResourceIdentifier("revanced_sb_create_segment_button", "id")));
imageView.setVisibility(View.GONE);
imageView.setOnClickListener(v -> {
SponsorBlockViewController.toggleNewSegmentLayoutVisibility();
});
buttonReference = new WeakReference<>(imageView);
} catch (Exception ex) {
Logger.printException(() -> "initialize failure", ex);
}
}
public static void changeVisibilityImmediate(boolean visible) {
changeVisibility(visible, true);
}
/**
* injection point
*/
public static void changeVisibilityNegatedImmediate(boolean visible) {
changeVisibility(!visible, true);
}
/**
* injection point
*/
public static void changeVisibility(boolean visible) {
changeVisibility(visible, false);
}
public static void changeVisibility(boolean visible, boolean immediate) {
try {
if (isShowing == visible) return;
isShowing = visible;
ImageView iView = buttonReference.get();
if (iView == null) return;
if (visible) {
iView.clearAnimation();
if (!shouldBeShown()) {
return;
}
if (!immediate) {
iView.startAnimation(BottomControlButton.getButtonFadeIn());
}
iView.setVisibility(View.VISIBLE);
return;
}
if (iView.getVisibility() == View.VISIBLE) {
iView.clearAnimation();
if (!immediate) {
iView.startAnimation(BottomControlButton.getButtonFadeOut());
}
iView.setVisibility(View.GONE);
}
} catch (Exception ex) {
Logger.printException(() -> "changeVisibility failure", ex);
}
}
private static boolean shouldBeShown() {
return Settings.SB_ENABLED.get() && Settings.SB_CREATE_NEW_SEGMENT.get()
&& !VideoInformation.isAtEndOfVideo();
}
public static void hide() {
if (!isShowing) {
return;
}
Utils.verifyOnMainThread();
View v = buttonReference.get();
if (v == null) {
return;
}
v.setVisibility(View.GONE);
isShowing = false;
}
}
| 3,432 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
VotingButtonController.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/ui/VotingButtonController.java | package app.revanced.integrations.youtube.sponsorblock.ui;
import static app.revanced.integrations.shared.Utils.getResourceIdentifier;
import android.view.View;
import android.widget.ImageView;
import java.lang.ref.WeakReference;
import java.util.Objects;
import app.revanced.integrations.youtube.patches.VideoInformation;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.sponsorblock.SegmentPlaybackController;
import app.revanced.integrations.youtube.sponsorblock.SponsorBlockUtils;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.youtube.videoplayer.BottomControlButton;
public class VotingButtonController {
private static WeakReference<ImageView> buttonReference = new WeakReference<>(null);
private static boolean isShowing;
/**
* injection point
*/
public static void initialize(View youtubeControlsLayout) {
try {
Logger.printDebug(() -> "initializing voting button");
ImageView imageView = Objects.requireNonNull(youtubeControlsLayout.findViewById(
getResourceIdentifier("revanced_sb_voting_button", "id")));
imageView.setVisibility(View.GONE);
imageView.setOnClickListener(v -> {
SponsorBlockUtils.onVotingClicked(v.getContext());
});
buttonReference = new WeakReference<>(imageView);
} catch (Exception ex) {
Logger.printException(() -> "Unable to set RelativeLayout", ex);
}
}
public static void changeVisibilityImmediate(boolean visible) {
changeVisibility(visible, true);
}
/**
* injection point
*/
public static void changeVisibilityNegatedImmediate(boolean visible) {
changeVisibility(!visible, true);
}
/**
* injection point
*/
public static void changeVisibility(boolean visible) {
changeVisibility(visible, false);
}
public static void changeVisibility(boolean visible, boolean immediate) {
try {
if (isShowing == visible) return;
isShowing = visible;
ImageView iView = buttonReference.get();
if (iView == null) return;
if (visible) {
iView.clearAnimation();
if (!shouldBeShown()) {
return;
}
if (!immediate) {
iView.startAnimation(BottomControlButton.getButtonFadeIn());
}
iView.setVisibility(View.VISIBLE);
return;
}
if (iView.getVisibility() == View.VISIBLE) {
iView.clearAnimation();
if (!immediate) {
iView.startAnimation(BottomControlButton.getButtonFadeOut());
}
iView.setVisibility(View.GONE);
}
} catch (Exception ex) {
Logger.printException(() -> "changeVisibility failure", ex);
}
}
private static boolean shouldBeShown() {
return Settings.SB_ENABLED.get() && Settings.SB_VOTING_BUTTON.get()
&& SegmentPlaybackController.videoHasSegments() && !VideoInformation.isAtEndOfVideo();
}
public static void hide() {
if (!isShowing) {
return;
}
Utils.verifyOnMainThread();
View v = buttonReference.get();
if (v == null) {
return;
}
v.setVisibility(View.GONE);
isShowing = false;
}
}
| 3,607 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SkipSponsorButton.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/ui/SkipSponsorButton.java | package app.revanced.integrations.youtube.sponsorblock.ui;
import static app.revanced.integrations.shared.Utils.getResourceColor;
import static app.revanced.integrations.shared.Utils.getResourceDimension;
import static app.revanced.integrations.shared.Utils.getResourceDimensionPixelSize;
import static app.revanced.integrations.shared.Utils.getResourceIdentifier;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import java.util.Objects;
import app.revanced.integrations.youtube.sponsorblock.SegmentPlaybackController;
import app.revanced.integrations.youtube.sponsorblock.objects.SponsorSegment;
public class SkipSponsorButton extends FrameLayout {
private static final boolean highContrast = true;
private final LinearLayout skipSponsorBtnContainer;
private final TextView skipSponsorTextView;
private final Paint background;
private final Paint border;
private SponsorSegment segment;
final int defaultBottomMargin;
final int ctaBottomMargin;
public SkipSponsorButton(Context context) {
this(context, null);
}
public SkipSponsorButton(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public SkipSponsorButton(Context context, AttributeSet attributeSet, int defStyleAttr) {
this(context, attributeSet, defStyleAttr, 0);
}
public SkipSponsorButton(Context context, AttributeSet attributeSet, int defStyleAttr, int defStyleRes) {
super(context, attributeSet, defStyleAttr, defStyleRes);
LayoutInflater.from(context).inflate(getResourceIdentifier(context, "revanced_sb_skip_sponsor_button", "layout"), this, true); // layout:skip_ad_button
setMinimumHeight(getResourceDimensionPixelSize("ad_skip_ad_button_min_height")); // dimen:ad_skip_ad_button_min_height
skipSponsorBtnContainer = Objects.requireNonNull((LinearLayout) findViewById(getResourceIdentifier(context, "revanced_sb_skip_sponsor_button_container", "id"))); // id:skip_ad_button_container
background = new Paint();
background.setColor(getResourceColor("skip_ad_button_background_color")); // color:skip_ad_button_background_color);
background.setStyle(Paint.Style.FILL);
border = new Paint();
border.setColor(getResourceColor("skip_ad_button_border_color")); // color:skip_ad_button_border_color);
border.setStrokeWidth(getResourceDimension("ad_skip_ad_button_border_width")); // dimen:ad_skip_ad_button_border_width);
border.setStyle(Paint.Style.STROKE);
skipSponsorTextView = Objects.requireNonNull((TextView) findViewById(getResourceIdentifier(context, "revanced_sb_skip_sponsor_button_text", "id"))); // id:skip_ad_button_text;
defaultBottomMargin = getResourceDimensionPixelSize("skip_button_default_bottom_margin"); // dimen:skip_button_default_bottom_margin
ctaBottomMargin = getResourceDimensionPixelSize("skip_button_cta_bottom_margin"); // dimen:skip_button_cta_bottom_margin
skipSponsorBtnContainer.setOnClickListener(v -> {
// The view controller handles hiding this button, but hide it here as well just in case something goofs.
setVisibility(View.GONE);
SegmentPlaybackController.onSkipSegmentClicked(segment);
});
}
@Override // android.view.ViewGroup
protected final void dispatchDraw(Canvas canvas) {
final int left = skipSponsorBtnContainer.getLeft();
final int top = skipSponsorBtnContainer.getTop();
final int leftPlusWidth = (left + skipSponsorBtnContainer.getWidth());
final int topPlusHeight = (top + skipSponsorBtnContainer.getHeight());
canvas.drawRect(left, top, leftPlusWidth, topPlusHeight, background);
if (!highContrast) {
canvas.drawLines(new float[]{
leftPlusWidth, top, left, top,
left, top, left, topPlusHeight,
left, topPlusHeight, leftPlusWidth, topPlusHeight},
border);
}
super.dispatchDraw(canvas);
}
/**
* @return true, if this button state was changed
*/
public boolean updateSkipButtonText(@NonNull SponsorSegment segment) {
this.segment = segment;
CharSequence newText = segment.getSkipButtonText();
if (newText.equals(skipSponsorTextView.getText())) {
return false;
}
skipSponsorTextView.setText(newText);
return true;
}
}
| 4,793 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SponsorBlockViewController.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/ui/SponsorBlockViewController.java | package app.revanced.integrations.youtube.sponsorblock.ui;
import static app.revanced.integrations.shared.Utils.getResourceIdentifier;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.Objects;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.shared.PlayerType;
import app.revanced.integrations.youtube.sponsorblock.objects.SponsorSegment;
public class SponsorBlockViewController {
private static WeakReference<RelativeLayout> inlineSponsorOverlayRef = new WeakReference<>(null);
private static WeakReference<ViewGroup> youtubeOverlaysLayoutRef = new WeakReference<>(null);
private static WeakReference<SkipSponsorButton> skipHighlightButtonRef = new WeakReference<>(null);
private static WeakReference<SkipSponsorButton> skipSponsorButtonRef = new WeakReference<>(null);
private static WeakReference<NewSegmentLayout> newSegmentLayoutRef = new WeakReference<>(null);
private static boolean canShowViewElements;
private static boolean newSegmentLayoutVisible;
@Nullable
private static SponsorSegment skipHighlight;
@Nullable
private static SponsorSegment skipSegment;
static {
PlayerType.getOnChange().addObserver((PlayerType type) -> {
playerTypeChanged(type);
return null;
});
}
public static Context getOverLaysViewGroupContext() {
ViewGroup group = youtubeOverlaysLayoutRef.get();
if (group == null) {
return null;
}
return group.getContext();
}
/**
* Injection point.
*/
public static void initialize(ViewGroup viewGroup) {
try {
Logger.printDebug(() -> "initializing");
// hide any old components, just in case they somehow are still hanging around
hideAll();
Context context = Utils.getContext();
RelativeLayout layout = new RelativeLayout(context);
layout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT));
LayoutInflater.from(context).inflate(getResourceIdentifier("revanced_sb_inline_sponsor_overlay", "layout"), layout);
inlineSponsorOverlayRef = new WeakReference<>(layout);
viewGroup.addView(layout);
viewGroup.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
@Override
public void onChildViewAdded(View parent, View child) {
// ensure SB buttons and controls are always on top, otherwise the endscreen cards can cover the skip button
RelativeLayout layout = inlineSponsorOverlayRef.get();
if (layout != null) {
layout.bringToFront();
}
}
@Override
public void onChildViewRemoved(View parent, View child) {
}
});
youtubeOverlaysLayoutRef = new WeakReference<>(viewGroup);
skipHighlightButtonRef = new WeakReference<>(
Objects.requireNonNull(layout.findViewById(getResourceIdentifier("revanced_sb_skip_highlight_button", "id"))));
skipSponsorButtonRef = new WeakReference<>(
Objects.requireNonNull(layout.findViewById(getResourceIdentifier("revanced_sb_skip_sponsor_button", "id"))));
newSegmentLayoutRef = new WeakReference<>(
Objects.requireNonNull(layout.findViewById(getResourceIdentifier("revanced_sb_new_segment_view", "id"))));
newSegmentLayoutVisible = false;
skipHighlight = null;
skipSegment = null;
} catch (Exception ex) {
Logger.printException(() -> "initialize failure", ex);
}
}
public static void hideAll() {
hideSkipHighlightButton();
hideSkipSegmentButton();
hideNewSegmentLayout();
}
public static void showSkipHighlightButton(@NonNull SponsorSegment segment) {
skipHighlight = Objects.requireNonNull(segment);
NewSegmentLayout newSegmentLayout = newSegmentLayoutRef.get();
// don't show highlight button if create new segment is visible
final boolean buttonVisibility = newSegmentLayout == null || newSegmentLayout.getVisibility() != View.VISIBLE;
updateSkipButton(skipHighlightButtonRef.get(), segment, buttonVisibility);
}
public static void showSkipSegmentButton(@NonNull SponsorSegment segment) {
skipSegment = Objects.requireNonNull(segment);
updateSkipButton(skipSponsorButtonRef.get(), segment, true);
}
public static void hideSkipHighlightButton() {
skipHighlight = null;
updateSkipButton(skipHighlightButtonRef.get(), null, false);
}
public static void hideSkipSegmentButton() {
skipSegment = null;
updateSkipButton(skipSponsorButtonRef.get(), null, false);
}
private static void updateSkipButton(@Nullable SkipSponsorButton button,
@Nullable SponsorSegment segment, boolean visible) {
if (button == null) {
return;
}
if (segment != null) {
button.updateSkipButtonText(segment);
}
setViewVisibility(button, visible);
}
public static void toggleNewSegmentLayoutVisibility() {
NewSegmentLayout newSegmentLayout = newSegmentLayoutRef.get();
if (newSegmentLayout == null) { // should never happen
Logger.printException(() -> "toggleNewSegmentLayoutVisibility failure");
return;
}
newSegmentLayoutVisible = (newSegmentLayout.getVisibility() != View.VISIBLE);
if (skipHighlight != null) {
setViewVisibility(skipHighlightButtonRef.get(), !newSegmentLayoutVisible);
}
setViewVisibility(newSegmentLayout, newSegmentLayoutVisible);
}
public static void hideNewSegmentLayout() {
newSegmentLayoutVisible = false;
setViewVisibility(newSegmentLayoutRef.get(), false);
}
private static void setViewVisibility(@Nullable View view, boolean visible) {
if (view == null) {
return;
}
visible &= canShowViewElements;
final int desiredVisibility = visible ? View.VISIBLE : View.GONE;
if (view.getVisibility() != desiredVisibility) {
view.setVisibility(desiredVisibility);
}
}
private static void playerTypeChanged(@NonNull PlayerType playerType) {
try {
final boolean isWatchFullScreen = playerType == PlayerType.WATCH_WHILE_FULLSCREEN;
canShowViewElements = (isWatchFullScreen || playerType == PlayerType.WATCH_WHILE_MAXIMIZED);
NewSegmentLayout newSegmentLayout = newSegmentLayoutRef.get();
setNewSegmentLayoutMargins(newSegmentLayout, isWatchFullScreen);
setViewVisibility(newSegmentLayoutRef.get(), newSegmentLayoutVisible);
SkipSponsorButton skipHighlightButton = skipHighlightButtonRef.get();
setSkipButtonMargins(skipHighlightButton, isWatchFullScreen);
setViewVisibility(skipHighlightButton, skipHighlight != null);
SkipSponsorButton skipSponsorButton = skipSponsorButtonRef.get();
setSkipButtonMargins(skipSponsorButton, isWatchFullScreen);
setViewVisibility(skipSponsorButton, skipSegment != null);
} catch (Exception ex) {
Logger.printException(() -> "Player type changed failure", ex);
}
}
private static void setNewSegmentLayoutMargins(@Nullable NewSegmentLayout layout, boolean fullScreen) {
if (layout != null) {
setLayoutMargins(layout, fullScreen, layout.defaultBottomMargin, layout.ctaBottomMargin);
}
}
private static void setSkipButtonMargins(@Nullable SkipSponsorButton button, boolean fullScreen) {
if (button != null) {
setLayoutMargins(button, fullScreen, button.defaultBottomMargin, button.ctaBottomMargin);
}
}
private static void setLayoutMargins(@NonNull View view, boolean fullScreen,
int defaultBottomMargin, int ctaBottomMargin) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
if (params == null) {
Logger.printException(() -> "Unable to setNewSegmentLayoutMargins (params are null)");
return;
}
params.bottomMargin = fullScreen ? ctaBottomMargin : defaultBottomMargin;
view.setLayoutParams(params);
}
/**
* Injection point.
*/
public static void endOfVideoReached() {
try {
Logger.printDebug(() -> "endOfVideoReached");
// the buttons automatically set themselves to visible when appropriate,
// but if buttons are showing when the end of the video is reached then they need
// to be forcefully hidden
if (!Settings.AUTO_REPEAT.get()) {
CreateSegmentButtonController.hide();
VotingButtonController.hide();
}
} catch (Exception ex) {
Logger.printException(() -> "endOfVideoReached failure", ex);
}
}
}
| 9,687 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SBRoutes.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/requests/SBRoutes.java | package app.revanced.integrations.youtube.sponsorblock.requests;
import static app.revanced.integrations.youtube.requests.Route.Method.GET;
import static app.revanced.integrations.youtube.requests.Route.Method.POST;
import app.revanced.integrations.youtube.requests.Route;
class SBRoutes {
static final Route IS_USER_VIP = new Route(GET, "/api/isUserVIP?userID={user_id}");
static final Route GET_SEGMENTS = new Route(GET, "/api/skipSegments?videoID={video_id}&categories={categories}");
static final Route VIEWED_SEGMENT = new Route(POST, "/api/viewedVideoSponsorTime?UUID={segment_id}");
static final Route GET_USER_STATS = new Route(GET, "/api/userInfo?userID={user_id}&values=[\"userID\",\"userName\",\"reputation\",\"segmentCount\",\"ignoredSegmentCount\",\"viewCount\",\"minutesSaved\"]");
static final Route CHANGE_USERNAME = new Route(POST, "/api/setUsername?userID={user_id}&username={username}");
static final Route SUBMIT_SEGMENTS = new Route(POST, "/api/skipSegments?userID={user_id}&videoID={video_id}&category={category}&startTime={start_time}&endTime={end_time}&videoDuration={duration}");
static final Route VOTE_ON_SEGMENT_QUALITY = new Route(POST, "/api/voteOnSponsorTime?userID={user_id}&UUID={segment_id}&type={type}");
static final Route VOTE_ON_SEGMENT_CATEGORY = new Route(POST, "/api/voteOnSponsorTime?userID={user_id}&UUID={segment_id}&category={category}");
private SBRoutes() {
}
} | 1,452 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SBRequester.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/sponsorblock/requests/SBRequester.java | package app.revanced.integrations.youtube.sponsorblock.requests;
import static app.revanced.integrations.shared.StringRef.str;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import app.revanced.integrations.youtube.requests.Requester;
import app.revanced.integrations.youtube.requests.Route;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.sponsorblock.SponsorBlockSettings;
import app.revanced.integrations.youtube.sponsorblock.objects.SegmentCategory;
import app.revanced.integrations.youtube.sponsorblock.objects.SponsorSegment;
import app.revanced.integrations.youtube.sponsorblock.objects.SponsorSegment.SegmentVote;
import app.revanced.integrations.youtube.sponsorblock.objects.UserStats;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
public class SBRequester {
private static final String TIME_TEMPLATE = "%.3f";
/**
* TCP timeout
*/
private static final int TIMEOUT_TCP_DEFAULT_MILLISECONDS = 7000;
/**
* HTTP response timeout
*/
private static final int TIMEOUT_HTTP_DEFAULT_MILLISECONDS = 10000;
/**
* Response code of a successful API call
*/
private static final int HTTP_STATUS_CODE_SUCCESS = 200;
private SBRequester() {
}
private static void handleConnectionError(@NonNull String toastMessage, @Nullable Exception ex) {
if (Settings.SB_TOAST_ON_CONNECTION_ERROR.get()) {
Utils.showToastShort(toastMessage);
}
if (ex != null) {
Logger.printInfo(() -> toastMessage, ex);
}
}
@NonNull
public static SponsorSegment[] getSegments(@NonNull String videoId) {
Utils.verifyOffMainThread();
List<SponsorSegment> segments = new ArrayList<>();
try {
HttpURLConnection connection = getConnectionFromRoute(SBRoutes.GET_SEGMENTS, videoId, SegmentCategory.sponsorBlockAPIFetchCategories);
final int responseCode = connection.getResponseCode();
if (responseCode == HTTP_STATUS_CODE_SUCCESS) {
JSONArray responseArray = Requester.parseJSONArray(connection);
final long minSegmentDuration = (long) (Settings.SB_SEGMENT_MIN_DURATION.get() * 1000);
for (int i = 0, length = responseArray.length(); i < length; i++) {
JSONObject obj = (JSONObject) responseArray.get(i);
JSONArray segment = obj.getJSONArray("segment");
final long start = (long) (segment.getDouble(0) * 1000);
final long end = (long) (segment.getDouble(1) * 1000);
String uuid = obj.getString("UUID");
final boolean locked = obj.getInt("locked") == 1;
String categoryKey = obj.getString("category");
SegmentCategory category = SegmentCategory.byCategoryKey(categoryKey);
if (category == null) {
Logger.printException(() -> "Received unknown category: " + categoryKey); // should never happen
} else if ((end - start) >= minSegmentDuration || category == SegmentCategory.HIGHLIGHT) {
segments.add(new SponsorSegment(category, uuid, start, end, locked));
}
}
Logger.printDebug(() -> {
StringBuilder builder = new StringBuilder("Downloaded segments:");
for (SponsorSegment segment : segments) {
builder.append('\n').append(segment);
}
return builder.toString();
});
runVipCheckInBackgroundIfNeeded();
} else if (responseCode == 404) {
// no segments are found. a normal response
Logger.printDebug(() -> "No segments found for video: " + videoId);
} else {
handleConnectionError(str("revanced_sb_sponsorblock_connection_failure_status", responseCode), null);
connection.disconnect(); // something went wrong, might as well disconnect
}
} catch (SocketTimeoutException ex) {
handleConnectionError(str("revanced_sb_sponsorblock_connection_failure_timeout"), ex);
} catch (IOException ex) {
handleConnectionError(str("revanced_sb_sponsorblock_connection_failure_generic"), ex);
} catch (Exception ex) {
// Should never happen
Logger.printException(() -> "getSegments failure", ex);
}
// Crude debug tests to verify random features
// Could benefit from:
// 1) collection of YouTube videos with test segment times (verify client skip timing matches the video, verify seekbar draws correctly)
// 2) unit tests (verify everything else)
if (false) {
segments.clear();
// Test auto-hide skip button:
// Button should appear only once
segments.add(new SponsorSegment(SegmentCategory.INTRO, "debug", 5000, 120000, false));
// Button should appear only once
segments.add(new SponsorSegment(SegmentCategory.SELF_PROMO, "debug", 10000, 60000, false));
// Button should appear only once
segments.add(new SponsorSegment(SegmentCategory.INTERACTION, "debug", 15000, 20000, false));
// Button should appear _twice_ (at 21s and 27s)
segments.add(new SponsorSegment(SegmentCategory.SPONSOR, "debug", 21000, 30000, false));
// Button should appear only once
segments.add(new SponsorSegment(SegmentCategory.OUTRO, "debug", 24000, 27000, false));
// Test seekbar visibility:
// All three segments should be viewable on the seekbar
segments.add(new SponsorSegment(SegmentCategory.MUSIC_OFFTOPIC, "debug", 200000, 300000, false));
segments.add(new SponsorSegment(SegmentCategory.SPONSOR, "debug", 200000, 250000, false));
segments.add(new SponsorSegment(SegmentCategory.SELF_PROMO, "debug", 200000, 330000, false));
}
return segments.toArray(new SponsorSegment[0]);
}
public static void submitSegments(@NonNull String videoId, @NonNull String category,
long startTime, long endTime, long videoLength) {
Utils.verifyOffMainThread();
try {
String privateUserId = SponsorBlockSettings.getSBPrivateUserID();
String start = String.format(Locale.US, TIME_TEMPLATE, startTime / 1000f);
String end = String.format(Locale.US, TIME_TEMPLATE, endTime / 1000f);
String duration = String.format(Locale.US, TIME_TEMPLATE, videoLength / 1000f);
HttpURLConnection connection = getConnectionFromRoute(SBRoutes.SUBMIT_SEGMENTS, privateUserId, videoId, category, start, end, duration);
final int responseCode = connection.getResponseCode();
final String messageToToast;
switch (responseCode) {
case HTTP_STATUS_CODE_SUCCESS:
messageToToast = str("revanced_sb_submit_succeeded");
break;
case 409:
messageToToast = str("revanced_sb_submit_failed_duplicate");
break;
case 403:
messageToToast = str("revanced_sb_submit_failed_forbidden", Requester.parseErrorStringAndDisconnect(connection));
break;
case 429:
messageToToast = str("revanced_sb_submit_failed_rate_limit");
break;
case 400:
messageToToast = str("revanced_sb_submit_failed_invalid", Requester.parseErrorStringAndDisconnect(connection));
break;
default:
messageToToast = str("revanced_sb_submit_failed_unknown_error", responseCode, connection.getResponseMessage());
break;
}
Utils.showToastLong(messageToToast);
} catch (SocketTimeoutException ex) {
// Always show, even if show connection toasts is turned off
Utils.showToastLong(str("revanced_sb_submit_failed_timeout"));
} catch (IOException ex) {
Utils.showToastLong(str("revanced_sb_submit_failed_unknown_error", 0, ex.getMessage()));
} catch (Exception ex) {
Logger.printException(() -> "failed to submit segments", ex);
}
}
public static void sendSegmentSkippedViewedRequest(@NonNull SponsorSegment segment) {
Utils.verifyOffMainThread();
try {
HttpURLConnection connection = getConnectionFromRoute(SBRoutes.VIEWED_SEGMENT, segment.UUID);
final int responseCode = connection.getResponseCode();
if (responseCode == HTTP_STATUS_CODE_SUCCESS) {
Logger.printDebug(() -> "Successfully sent view count for segment: " + segment);
} else {
Logger.printDebug(() -> "Failed to sent view count for segment: " + segment.UUID
+ " responseCode: " + responseCode); // debug level, no toast is shown
}
} catch (IOException ex) {
Logger.printInfo(() -> "Failed to send view count", ex); // do not show a toast
} catch (Exception ex) {
Logger.printException(() -> "Failed to send view count request", ex); // should never happen
}
}
public static void voteForSegmentOnBackgroundThread(@NonNull SponsorSegment segment, @NonNull SegmentVote voteOption) {
voteOrRequestCategoryChange(segment, voteOption, null);
}
public static void voteToChangeCategoryOnBackgroundThread(@NonNull SponsorSegment segment, @NonNull SegmentCategory categoryToVoteFor) {
voteOrRequestCategoryChange(segment, SegmentVote.CATEGORY_CHANGE, categoryToVoteFor);
}
private static void voteOrRequestCategoryChange(@NonNull SponsorSegment segment, @NonNull SegmentVote voteOption, SegmentCategory categoryToVoteFor) {
Utils.runOnBackgroundThread(() -> {
try {
String segmentUuid = segment.UUID;
String uuid = SponsorBlockSettings.getSBPrivateUserID();
HttpURLConnection connection = (voteOption == SegmentVote.CATEGORY_CHANGE)
? getConnectionFromRoute(SBRoutes.VOTE_ON_SEGMENT_CATEGORY, uuid, segmentUuid, categoryToVoteFor.keyValue)
: getConnectionFromRoute(SBRoutes.VOTE_ON_SEGMENT_QUALITY, uuid, segmentUuid, String.valueOf(voteOption.apiVoteType));
final int responseCode = connection.getResponseCode();
switch (responseCode) {
case HTTP_STATUS_CODE_SUCCESS:
Logger.printDebug(() -> "Vote success for segment: " + segment);
break;
case 403:
Utils.showToastLong(
str("revanced_sb_vote_failed_forbidden", Requester.parseErrorStringAndDisconnect(connection)));
break;
default:
Utils.showToastLong(
str("revanced_sb_vote_failed_unknown_error", responseCode, connection.getResponseMessage()));
break;
}
} catch (SocketTimeoutException ex) {
Utils.showToastShort(str("revanced_sb_vote_failed_timeout"));
} catch (IOException ex) {
Utils.showToastShort(str("revanced_sb_vote_failed_unknown_error", 0, ex.getMessage()));
} catch (Exception ex) {
Logger.printException(() -> "failed to vote for segment", ex); // should never happen
}
});
}
/**
* @return NULL, if stats fetch failed
*/
@Nullable
public static UserStats retrieveUserStats() {
Utils.verifyOffMainThread();
try {
UserStats stats = new UserStats(getJSONObject(SBRoutes.GET_USER_STATS, SponsorBlockSettings.getSBPrivateUserID()));
Logger.printDebug(() -> "user stats: " + stats);
return stats;
} catch (IOException ex) {
Logger.printInfo(() -> "failed to retrieve user stats", ex); // info level, do not show a toast
} catch (Exception ex) {
Logger.printException(() -> "failure retrieving user stats", ex); // should never happen
}
return null;
}
/**
* @return NULL if the call was successful. If unsuccessful, an error message is returned.
*/
@Nullable
public static String setUsername(@NonNull String username) {
Utils.verifyOffMainThread();
try {
HttpURLConnection connection = getConnectionFromRoute(SBRoutes.CHANGE_USERNAME, SponsorBlockSettings.getSBPrivateUserID(), username);
final int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
if (responseCode == HTTP_STATUS_CODE_SUCCESS) {
return null;
}
return str("revanced_sb_stats_username_change_unknown_error", responseCode, responseMessage);
} catch (Exception ex) { // should never happen
Logger.printInfo(() -> "failed to set username", ex); // do not toast
return str("revanced_sb_stats_username_change_unknown_error", 0, ex.getMessage());
}
}
public static void runVipCheckInBackgroundIfNeeded() {
if (!SponsorBlockSettings.userHasSBPrivateId()) {
return; // User cannot be a VIP. User has never voted, created any segments, or has imported a SB user id.
}
long now = System.currentTimeMillis();
if (now < (Settings.SB_LAST_VIP_CHECK.get() + TimeUnit.DAYS.toMillis(3))) {
return;
}
Utils.runOnBackgroundThread(() -> {
try {
JSONObject json = getJSONObject(SBRoutes.IS_USER_VIP, SponsorBlockSettings.getSBPrivateUserID());
boolean vip = json.getBoolean("vip");
Settings.SB_USER_IS_VIP.save(vip);
Settings.SB_LAST_VIP_CHECK.save(now);
} catch (IOException ex) {
Logger.printInfo(() -> "Failed to check VIP (network error)", ex); // info, so no error toast is shown
} catch (Exception ex) {
Logger.printException(() -> "Failed to check VIP", ex); // should never happen
}
});
}
// helpers
private static HttpURLConnection getConnectionFromRoute(@NonNull Route route, String... params) throws IOException {
HttpURLConnection connection = Requester.getConnectionFromRoute(Settings.SB_API_URL.get(), route, params);
connection.setConnectTimeout(TIMEOUT_TCP_DEFAULT_MILLISECONDS);
connection.setReadTimeout(TIMEOUT_HTTP_DEFAULT_MILLISECONDS);
return connection;
}
private static JSONObject getJSONObject(@NonNull Route route, String... params) throws IOException, JSONException {
return Requester.parseJSONObject(getConnectionFromRoute(route, params));
}
}
| 15,650 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ReturnYouTubeDislike.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/returnyoutubedislike/ReturnYouTubeDislike.java | package app.revanced.integrations.youtube.returnyoutubedislike;
import static app.revanced.integrations.shared.StringRef.str;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.RectShape;
import android.icu.text.CompactDecimalFormat;
import android.os.Build;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.ReplacementSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import androidx.annotation.GuardedBy;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.youtube.ThemeHelper;
import app.revanced.integrations.youtube.patches.spoof.SpoofAppVersionPatch;
import app.revanced.integrations.youtube.returnyoutubedislike.requests.RYDVoteData;
import app.revanced.integrations.youtube.returnyoutubedislike.requests.ReturnYouTubeDislikeApi;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.shared.PlayerType;
/**
* Handles fetching and creation/replacing of RYD dislike text spans.
*
* Because Litho creates spans using multiple threads, this entire class supports multithreading as well.
*/
public class ReturnYouTubeDislike {
public enum Vote {
LIKE(1),
DISLIKE(-1),
LIKE_REMOVE(0);
public final int value;
Vote(int value) {
this.value = value;
}
}
/**
* Maximum amount of time to block the UI from updates while waiting for network call to complete.
*
* Must be less than 5 seconds, as per:
* https://developer.android.com/topic/performance/vitals/anr
*/
private static final long MAX_MILLISECONDS_TO_BLOCK_UI_WAITING_FOR_FETCH = 4000;
/**
* How long to retain successful RYD fetches.
*/
private static final long CACHE_TIMEOUT_SUCCESS_MILLISECONDS = 7 * 60 * 1000; // 7 Minutes
/**
* How long to retain unsuccessful RYD fetches,
* and also the minimum time before retrying again.
*/
private static final long CACHE_TIMEOUT_FAILURE_MILLISECONDS = 3 * 60 * 1000; // 3 Minutes
/**
* Unique placeholder character, used to detect if a segmented span already has dislikes added to it.
* Must be something YouTube is unlikely to use, as it's searched for in all usage of Rolling Number.
*/
private static final char MIDDLE_SEPARATOR_CHARACTER = '◎'; // 'bullseye'
private static final boolean IS_SPOOFING_TO_OLD_SEPARATOR_COLOR
= SpoofAppVersionPatch.isSpoofingToLessThan("18.10.00");
/**
* Cached lookup of all video ids.
*/
@GuardedBy("itself")
private static final Map<String, ReturnYouTubeDislike> fetchCache = new HashMap<>();
/**
* Used to send votes, one by one, in the same order the user created them.
*/
private static final ExecutorService voteSerialExecutor = Executors.newSingleThreadExecutor();
/**
* For formatting dislikes as number.
*/
@GuardedBy("ReturnYouTubeDislike.class") // not thread safe
private static CompactDecimalFormat dislikeCountFormatter;
/**
* For formatting dislikes as percentage.
*/
@GuardedBy("ReturnYouTubeDislike.class")
private static NumberFormat dislikePercentageFormatter;
// Used for segmented dislike spans in Litho regular player.
public static final Rect leftSeparatorBounds;
private static final Rect middleSeparatorBounds;
/**
* Left separator horizontal padding for Rolling Number layout.
*/
public static final int leftSeparatorShapePaddingPixels;
private static final ShapeDrawable leftSeparatorShape;
static {
DisplayMetrics dp = Objects.requireNonNull(Utils.getContext()).getResources().getDisplayMetrics();
leftSeparatorBounds = new Rect(0, 0,
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1.2f, dp),
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18, dp));
final int middleSeparatorSize =
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3.7f, dp);
middleSeparatorBounds = new Rect(0, 0, middleSeparatorSize, middleSeparatorSize);
leftSeparatorShapePaddingPixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10.0f, dp);
leftSeparatorShape = new ShapeDrawable(new RectShape());
leftSeparatorShape.setBounds(leftSeparatorBounds);
}
private final String videoId;
/**
* Stores the results of the vote api fetch, and used as a barrier to wait until fetch completes.
* Absolutely cannot be holding any lock during calls to {@link Future#get()}.
*/
private final Future<RYDVoteData> future;
/**
* Time this instance and the fetch future was created.
*/
private final long timeFetched;
/**
* If this instance was previously used for a Short.
*/
@GuardedBy("this")
private boolean isShort;
/**
* Optional current vote status of the UI. Used to apply a user vote that was done on a previous video viewing.
*/
@Nullable
@GuardedBy("this")
private Vote userVote;
/**
* Original dislike span, before modifications.
*/
@Nullable
@GuardedBy("this")
private Spanned originalDislikeSpan;
/**
* Replacement like/dislike span that includes formatted dislikes.
* Used to prevent recreating the same span multiple times.
*/
@Nullable
@GuardedBy("this")
private SpannableString replacementLikeDislikeSpan;
/**
* Color of the left and middle separator, based on the color of the right separator.
* It's unknown where YT gets the color from, and the values here are approximated by hand.
* Ideally, this would be the actual color YT uses at runtime.
*
* Older versions before the 'Me' library tab use a slightly different color.
* If spoofing was previously used and is now turned off,
* or an old version was recently upgraded then the old colors are sometimes still used.
*/
private static int getSeparatorColor() {
if (IS_SPOOFING_TO_OLD_SEPARATOR_COLOR) {
return ThemeHelper.isDarkTheme()
? 0x29AAAAAA // transparent dark gray
: 0xFFD9D9D9; // light gray
}
return ThemeHelper.isDarkTheme()
? 0x33FFFFFF
: 0xFFD9D9D9;
}
public static ShapeDrawable getLeftSeparatorDrawable() {
leftSeparatorShape.getPaint().setColor(getSeparatorColor());
return leftSeparatorShape;
}
/**
* @param isSegmentedButton If UI is using the segmented single UI component for both like and dislike.
*/
@NonNull
private static SpannableString createDislikeSpan(@NonNull Spanned oldSpannable,
boolean isSegmentedButton,
boolean isRollingNumber,
@NonNull RYDVoteData voteData) {
if (!isSegmentedButton) {
// Simple replacement of 'dislike' with a number/percentage.
return newSpannableWithDislikes(oldSpannable, voteData);
}
// Note: Some locales use right to left layout (Arabic, Hebrew, etc).
// If making changes to this code, change device settings to a RTL language and verify layout is correct.
String oldLikesString = oldSpannable.toString();
// YouTube creators can hide the like count on a video,
// and the like count appears as a device language specific string that says 'Like'.
// Check if the string contains any numbers.
if (!stringContainsNumber(oldLikesString)) {
// Likes are hidden.
// RYD does not provide usable data for these types of videos,
// and the API returns bogus data (zero likes and zero dislikes)
// discussion about this: https://github.com/Anarios/return-youtube-dislike/discussions/530
//
// example video: https://www.youtube.com/watch?v=UnrU5vxCHxw
// RYD data: https://returnyoutubedislikeapi.com/votes?videoId=UnrU5vxCHxw
//
// Change the "Likes" string to show that likes and dislikes are hidden.
String hiddenMessageString = str("revanced_ryd_video_likes_hidden_by_video_owner");
return newSpanUsingStylingOfAnotherSpan(oldSpannable, hiddenMessageString);
}
SpannableStringBuilder builder = new SpannableStringBuilder();
final boolean compactLayout = Settings.RYD_COMPACT_LAYOUT.get();
if (!compactLayout) {
String leftSeparatorString = Utils.isRightToLeftTextLayout()
? "\u200F" // u200F = right to left character
: "\u200E"; // u200E = left to right character
final Spannable leftSeparatorSpan;
if (isRollingNumber) {
leftSeparatorSpan = new SpannableString(leftSeparatorString);
} else {
leftSeparatorString += " ";
leftSeparatorSpan = new SpannableString(leftSeparatorString);
// Styling spans cannot overwrite RTL or LTR character.
leftSeparatorSpan.setSpan(
new VerticallyCenteredImageSpan(getLeftSeparatorDrawable(), false),
1, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
leftSeparatorSpan.setSpan(
new FixedWidthEmptySpan(leftSeparatorShapePaddingPixels),
2, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
builder.append(leftSeparatorSpan);
}
// likes
builder.append(newSpanUsingStylingOfAnotherSpan(oldSpannable, oldLikesString));
// middle separator
String middleSeparatorString = compactLayout
? " " + MIDDLE_SEPARATOR_CHARACTER + " "
: " \u2009" + MIDDLE_SEPARATOR_CHARACTER + "\u2009 "; // u2009 = 'narrow space' character
final int shapeInsertionIndex = middleSeparatorString.length() / 2;
Spannable middleSeparatorSpan = new SpannableString(middleSeparatorString);
ShapeDrawable shapeDrawable = new ShapeDrawable(new OvalShape());
shapeDrawable.getPaint().setColor(getSeparatorColor());
shapeDrawable.setBounds(middleSeparatorBounds);
// Use original text width if using Rolling Number,
// to ensure the replacement styled span has the same width as the measured String,
// otherwise layout can be broken (especially on devices with small system font sizes).
middleSeparatorSpan.setSpan(
new VerticallyCenteredImageSpan(shapeDrawable, isRollingNumber),
shapeInsertionIndex, shapeInsertionIndex + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder.append(middleSeparatorSpan);
// dislikes
builder.append(newSpannableWithDislikes(oldSpannable, voteData));
return new SpannableString(builder);
}
/**
* @return If the text is likely for a previously created likes/dislikes segmented span.
*/
public static boolean isPreviouslyCreatedSegmentedSpan(@NonNull String text) {
return text.indexOf(MIDDLE_SEPARATOR_CHARACTER) >= 0;
}
/**
* Correctly handles any unicode numbers (such as Arabic numbers).
*
* @return if the string contains at least 1 number.
*/
private static boolean stringContainsNumber(@NonNull String text) {
for (int index = 0, length = text.length(); index < length; index++) {
if (Character.isDigit(text.codePointAt(index))) {
return true;
}
}
return false;
}
private static boolean spansHaveEqualTextAndColor(@NonNull Spanned one, @NonNull Spanned two) {
// Cannot use equals on the span, because many of the inner styling spans do not implement equals.
// Instead, compare the underlying text and the text color to handle when dark mode is changed.
// Cannot compare the status of device dark mode, as Litho components are updated just before dark mode status changes.
if (!one.toString().equals(two.toString())) {
return false;
}
ForegroundColorSpan[] oneColors = one.getSpans(0, one.length(), ForegroundColorSpan.class);
ForegroundColorSpan[] twoColors = two.getSpans(0, two.length(), ForegroundColorSpan.class);
final int oneLength = oneColors.length;
if (oneLength != twoColors.length) {
return false;
}
for (int i = 0; i < oneLength; i++) {
if (oneColors[i].getForegroundColor() != twoColors[i].getForegroundColor()) {
return false;
}
}
return true;
}
private static SpannableString newSpannableWithDislikes(@NonNull Spanned sourceStyling, @NonNull RYDVoteData voteData) {
return newSpanUsingStylingOfAnotherSpan(sourceStyling,
Settings.RYD_DISLIKE_PERCENTAGE.get()
? formatDislikePercentage(voteData.getDislikePercentage())
: formatDislikeCount(voteData.getDislikeCount()));
}
private static SpannableString newSpanUsingStylingOfAnotherSpan(@NonNull Spanned sourceStyle, @NonNull CharSequence newSpanText) {
SpannableString destination = new SpannableString(newSpanText);
Object[] spans = sourceStyle.getSpans(0, sourceStyle.length(), Object.class);
for (Object span : spans) {
destination.setSpan(span, 0, destination.length(), sourceStyle.getSpanFlags(span));
}
return destination;
}
private static String formatDislikeCount(long dislikeCount) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
synchronized (ReturnYouTubeDislike.class) { // number formatter is not thread safe, must synchronize
if (dislikeCountFormatter == null) {
// Note: Java number formatters will use the locale specific number characters.
// such as Arabic which formats "1.234" into "۱,۲۳٤"
// But YouTube disregards locale specific number characters
// and instead shows english number characters everywhere.
Locale locale = Objects.requireNonNull(Utils.getContext()).getResources().getConfiguration().locale;
Logger.printDebug(() -> "Locale: " + locale);
dislikeCountFormatter = CompactDecimalFormat.getInstance(locale, CompactDecimalFormat.CompactStyle.SHORT);
}
return dislikeCountFormatter.format(dislikeCount);
}
}
// Will never be reached, as the oldest supported YouTube app requires Android N or greater.
return String.valueOf(dislikeCount);
}
private static String formatDislikePercentage(float dislikePercentage) {
synchronized (ReturnYouTubeDislike.class) { // number formatter is not thread safe, must synchronize
if (dislikePercentageFormatter == null) {
Locale locale = Objects.requireNonNull(Utils.getContext()).getResources().getConfiguration().locale;
Logger.printDebug(() -> "Locale: " + locale);
dislikePercentageFormatter = NumberFormat.getPercentInstance(locale);
}
if (dislikePercentage >= 0.01) { // at least 1%
dislikePercentageFormatter.setMaximumFractionDigits(0); // show only whole percentage points
} else {
dislikePercentageFormatter.setMaximumFractionDigits(1); // show up to 1 digit precision
}
return dislikePercentageFormatter.format(dislikePercentage);
}
}
@NonNull
public static ReturnYouTubeDislike getFetchForVideoId(@Nullable String videoId) {
Objects.requireNonNull(videoId);
synchronized (fetchCache) {
// Remove any expired entries.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
final long now = System.currentTimeMillis();
fetchCache.values().removeIf(value -> {
final boolean expired = value.isExpired(now);
if (expired)
Logger.printDebug(() -> "Removing expired fetch: " + value.videoId);
return expired;
});
}
ReturnYouTubeDislike fetch = fetchCache.get(videoId);
if (fetch == null) {
fetch = new ReturnYouTubeDislike(videoId);
fetchCache.put(videoId, fetch);
}
return fetch;
}
}
/**
* Should be called if the user changes dislikes appearance settings.
*/
public static void clearAllUICaches() {
synchronized (fetchCache) {
for (ReturnYouTubeDislike fetch : fetchCache.values()) {
fetch.clearUICache();
}
}
}
private ReturnYouTubeDislike(@NonNull String videoId) {
this.videoId = Objects.requireNonNull(videoId);
this.timeFetched = System.currentTimeMillis();
this.future = Utils.submitOnBackgroundThread(() -> ReturnYouTubeDislikeApi.fetchVotes(videoId));
}
private boolean isExpired(long now) {
final long timeSinceCreation = now - timeFetched;
if (timeSinceCreation < CACHE_TIMEOUT_FAILURE_MILLISECONDS) {
return false; // Not expired, even if the API call failed.
}
if (timeSinceCreation > CACHE_TIMEOUT_SUCCESS_MILLISECONDS) {
return true; // Always expired.
}
// Only expired if the fetch failed (API null response).
return (!fetchCompleted() || getFetchData(MAX_MILLISECONDS_TO_BLOCK_UI_WAITING_FOR_FETCH) == null);
}
@Nullable
public RYDVoteData getFetchData(long maxTimeToWait) {
try {
return future.get(maxTimeToWait, TimeUnit.MILLISECONDS);
} catch (TimeoutException ex) {
Logger.printDebug(() -> "Waited but future was not complete after: " + maxTimeToWait + "ms");
} catch (ExecutionException | InterruptedException ex) {
Logger.printException(() -> "Future failure ", ex); // will never happen
}
return null;
}
/**
* @return if the RYD fetch call has completed.
*/
public boolean fetchCompleted() {
return future.isDone();
}
private synchronized void clearUICache() {
if (replacementLikeDislikeSpan != null) {
Logger.printDebug(() -> "Clearing replacement span for: " + videoId);
}
replacementLikeDislikeSpan = null;
}
@NonNull
public String getVideoId() {
return videoId;
}
/**
* Pre-emptively set this as a Short.
*/
public synchronized void setVideoIdIsShort(boolean isShort) {
this.isShort = isShort;
}
/**
* @return the replacement span containing dislikes, or the original span if RYD is not available.
*/
@NonNull
public synchronized Spanned getDislikesSpanForRegularVideo(@NonNull Spanned original,
boolean isSegmentedButton,
boolean isRollingNumber) {
return waitForFetchAndUpdateReplacementSpan(original, isSegmentedButton, isRollingNumber,false);
}
/**
* Called when a Shorts dislike Spannable is created.
*/
@NonNull
public synchronized Spanned getDislikeSpanForShort(@NonNull Spanned original) {
return waitForFetchAndUpdateReplacementSpan(original, false, false, true);
}
@NonNull
private Spanned waitForFetchAndUpdateReplacementSpan(@NonNull Spanned original,
boolean isSegmentedButton,
boolean isRollingNumber,
boolean spanIsForShort) {
try {
RYDVoteData votingData = getFetchData(MAX_MILLISECONDS_TO_BLOCK_UI_WAITING_FOR_FETCH);
if (votingData == null) {
Logger.printDebug(() -> "Cannot add dislike to UI (RYD data not available)");
return original;
}
synchronized (this) {
if (spanIsForShort) {
// Cannot set this to false if span is not for a Short.
// When spoofing to an old version and a Short is opened while a regular video
// is on screen, this instance can be loaded for the minimized regular video.
// But this Shorts data won't be displayed for that call
// and when it is un-minimized it will reload again and the load will be ignored.
isShort = true;
} else if (isShort) {
// user:
// 1, opened a video
// 2. opened a short (without closing the regular video)
// 3. closed the short
// 4. regular video is now present, but the videoId and RYD data is still for the short
Logger.printDebug(() -> "Ignoring regular video dislike span,"
+ " as data loaded was previously used for a Short: " + videoId);
return original;
}
if (originalDislikeSpan != null && replacementLikeDislikeSpan != null) {
if (spansHaveEqualTextAndColor(original, replacementLikeDislikeSpan)) {
Logger.printDebug(() -> "Ignoring previously created dislikes span of data: " + videoId);
return original;
}
if (spansHaveEqualTextAndColor(original, originalDislikeSpan)) {
Logger.printDebug(() -> "Replacing span with previously created dislike span of data: " + videoId);
return replacementLikeDislikeSpan;
}
}
if (isSegmentedButton && isPreviouslyCreatedSegmentedSpan(original.toString())) {
// need to recreate using original, as original has prior outdated dislike values
if (originalDislikeSpan == null) {
// Should never happen.
Logger.printDebug(() -> "Cannot add dislikes - original span is null. videoId: " + videoId);
return original;
}
original = originalDislikeSpan;
}
// No replacement span exist, create it now.
if (userVote != null) {
votingData.updateUsingVote(userVote);
}
originalDislikeSpan = original;
replacementLikeDislikeSpan = createDislikeSpan(original, isSegmentedButton, isRollingNumber, votingData);
Logger.printDebug(() -> "Replaced: '" + originalDislikeSpan + "' with: '"
+ replacementLikeDislikeSpan + "'" + " using video: " + videoId);
return replacementLikeDislikeSpan;
}
} catch (Exception e) {
Logger.printException(() -> "waitForFetchAndUpdateReplacementSpan failure", e); // should never happen
}
return original;
}
public void sendVote(@NonNull Vote vote) {
Utils.verifyOnMainThread();
Objects.requireNonNull(vote);
try {
if (isShort != PlayerType.getCurrent().isNoneOrHidden()) {
// Shorts was loaded with regular video present, then Shorts was closed.
// and then user voted on the now visible original video.
// Cannot send a vote, because this instance is for the wrong video.
Utils.showToastLong(str("revanced_ryd_failure_ryd_enabled_while_playing_video_then_user_voted"));
return;
}
setUserVote(vote);
voteSerialExecutor.execute(() -> {
try { // Must wrap in try/catch to properly log exceptions.
ReturnYouTubeDislikeApi.sendVote(videoId, vote);
} catch (Exception ex) {
Logger.printException(() -> "Failed to send vote", ex);
}
});
} catch (Exception ex) {
Logger.printException(() -> "Error trying to send vote", ex);
}
}
/**
* Sets the current user vote value, and does not send the vote to the RYD API.
*
* Only used to set value if thumbs up/down is already selected on video load.
*/
public void setUserVote(@NonNull Vote vote) {
Objects.requireNonNull(vote);
try {
Logger.printDebug(() -> "setUserVote: " + vote);
synchronized (this) {
userVote = vote;
clearUICache();
}
if (future.isDone()) {
// Update the fetched vote data.
RYDVoteData voteData = getFetchData(MAX_MILLISECONDS_TO_BLOCK_UI_WAITING_FOR_FETCH);
if (voteData == null) {
// RYD fetch failed.
Logger.printDebug(() -> "Cannot update UI (vote data not available)");
return;
}
voteData.updateUsingVote(vote);
} // Else, vote will be applied after fetch completes.
} catch (Exception ex) {
Logger.printException(() -> "setUserVote failure", ex);
}
}
}
/**
* Styles a Spannable with an empty fixed width.
*/
class FixedWidthEmptySpan extends ReplacementSpan {
final int fixedWidth;
/**
* @param fixedWith Fixed width in screen pixels.
*/
FixedWidthEmptySpan(int fixedWith) {
this.fixedWidth = fixedWith;
if (fixedWith < 0) throw new IllegalArgumentException();
}
@Override
public int getSize(@NonNull Paint paint, @NonNull CharSequence text,
int start, int end, @Nullable Paint.FontMetricsInt fontMetrics) {
return fixedWidth;
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end,
float x, int top, int y, int bottom, @NonNull Paint paint) {
// Nothing to draw.
}
}
/**
* Vertically centers a Spanned Drawable.
*/
class VerticallyCenteredImageSpan extends ImageSpan {
final boolean useOriginalWidth;
/**
* @param useOriginalWidth Use the original layout width of the text this span is applied to,
* and not the bounds of the Drawable. Drawable is always displayed using it's own bounds,
* and this setting only affects the layout width of the entire span.
*/
public VerticallyCenteredImageSpan(Drawable drawable, boolean useOriginalWidth) {
super(drawable);
this.useOriginalWidth = useOriginalWidth;
}
@Override
public int getSize(@NonNull Paint paint, @NonNull CharSequence text,
int start, int end, @Nullable Paint.FontMetricsInt fontMetrics) {
Drawable drawable = getDrawable();
Rect bounds = drawable.getBounds();
if (fontMetrics != null) {
Paint.FontMetricsInt paintMetrics = paint.getFontMetricsInt();
final int fontHeight = paintMetrics.descent - paintMetrics.ascent;
final int drawHeight = bounds.bottom - bounds.top;
final int halfDrawHeight = drawHeight / 2;
final int yCenter = paintMetrics.ascent + fontHeight / 2;
fontMetrics.ascent = yCenter - halfDrawHeight;
fontMetrics.top = fontMetrics.ascent;
fontMetrics.bottom = yCenter + halfDrawHeight;
fontMetrics.descent = fontMetrics.bottom;
}
if (useOriginalWidth) {
return (int) paint.measureText(text, start, end);
}
return bounds.right;
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end,
float x, int top, int y, int bottom, @NonNull Paint paint) {
Drawable drawable = getDrawable();
canvas.save();
Paint.FontMetricsInt paintMetrics = paint.getFontMetricsInt();
final int fontHeight = paintMetrics.descent - paintMetrics.ascent;
final int yCenter = y + paintMetrics.descent - fontHeight / 2;
final Rect drawBounds = drawable.getBounds();
float translateX = x;
if (useOriginalWidth) {
// Horizontally center the drawable in the same space as the original text.
translateX += (paint.measureText(text, start, end) - (drawBounds.right - drawBounds.left)) / 2;
}
final int translateY = yCenter - (drawBounds.bottom - drawBounds.top) / 2;
canvas.translate(translateX, translateY);
drawable.draw(canvas);
canvas.restore();
}
} | 30,100 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
RYDVoteData.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/returnyoutubedislike/requests/RYDVoteData.java | package app.revanced.integrations.youtube.returnyoutubedislike.requests;
import static app.revanced.integrations.youtube.returnyoutubedislike.ReturnYouTubeDislike.Vote;
import androidx.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;
/**
* ReturnYouTubeDislike API estimated like/dislike/view counts.
*
* ReturnYouTubeDislike does not guarantee when the counts are updated.
* So these values may lag behind what YouTube shows.
*/
public final class RYDVoteData {
@NonNull
public final String videoId;
/**
* Estimated number of views
*/
public final long viewCount;
private final long fetchedLikeCount;
private volatile long likeCount; // read/write from different threads
private volatile float likePercentage;
private final long fetchedDislikeCount;
private volatile long dislikeCount; // read/write from different threads
private volatile float dislikePercentage;
/**
* @throws JSONException if JSON parse error occurs, or if the values make no sense (ie: negative values)
*/
public RYDVoteData(@NonNull JSONObject json) throws JSONException {
videoId = json.getString("id");
viewCount = json.getLong("viewCount");
fetchedLikeCount = json.getLong("likes");
fetchedDislikeCount = json.getLong("dislikes");
if (viewCount < 0 || fetchedLikeCount < 0 || fetchedDislikeCount < 0) {
throw new JSONException("Unexpected JSON values: " + json);
}
likeCount = fetchedLikeCount;
dislikeCount = fetchedDislikeCount;
updatePercentages();
}
/**
* Estimated like count
*/
public long getLikeCount() {
return likeCount;
}
/**
* Estimated dislike count
*/
public long getDislikeCount() {
return dislikeCount;
}
/**
* Estimated percentage of likes for all votes. Value has range of [0, 1]
*
* A video with 400 positive votes, and 100 negative votes, has a likePercentage of 0.8
*/
public float getLikePercentage() {
return likePercentage;
}
/**
* Estimated percentage of dislikes for all votes. Value has range of [0, 1]
*
* A video with 400 positive votes, and 100 negative votes, has a dislikePercentage of 0.2
*/
public float getDislikePercentage() {
return dislikePercentage;
}
public void updateUsingVote(Vote vote) {
switch (vote) {
case LIKE:
likeCount = fetchedLikeCount + 1;
dislikeCount = fetchedDislikeCount;
break;
case DISLIKE:
likeCount = fetchedLikeCount;
dislikeCount = fetchedDislikeCount + 1;
break;
case LIKE_REMOVE:
likeCount = fetchedLikeCount;
dislikeCount = fetchedDislikeCount;
break;
default:
throw new IllegalStateException();
}
updatePercentages();
}
private void updatePercentages() {
likePercentage = (likeCount == 0 ? 0 : (float) likeCount / (likeCount + dislikeCount));
dislikePercentage = (dislikeCount == 0 ? 0 : (float) dislikeCount / (likeCount + dislikeCount));
}
@NonNull
@Override
public String toString() {
return "RYDVoteData{"
+ "videoId=" + videoId
+ ", viewCount=" + viewCount
+ ", likeCount=" + likeCount
+ ", dislikeCount=" + dislikeCount
+ ", likePercentage=" + likePercentage
+ ", dislikePercentage=" + dislikePercentage
+ '}';
}
// equals and hashcode is not implemented (currently not needed)
}
| 3,782 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ReturnYouTubeDislikeApi.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/returnyoutubedislike/requests/ReturnYouTubeDislikeApi.java | package app.revanced.integrations.youtube.returnyoutubedislike.requests;
import static app.revanced.integrations.shared.StringRef.str;
import static app.revanced.integrations.youtube.returnyoutubedislike.requests.ReturnYouTubeDislikeRoutes.getRYDConnectionFromRoute;
import android.util.Base64;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Objects;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.youtube.requests.Requester;
import app.revanced.integrations.youtube.returnyoutubedislike.ReturnYouTubeDislike;
import app.revanced.integrations.youtube.settings.Settings;
public class ReturnYouTubeDislikeApi {
/**
* {@link #fetchVotes(String)} TCP connection timeout
*/
private static final int API_GET_VOTES_TCP_TIMEOUT_MILLISECONDS = 2 * 1000; // 2 Seconds.
/**
* {@link #fetchVotes(String)} HTTP read timeout.
* To locally debug and force timeouts, change this to a very small number (ie: 100)
*/
private static final int API_GET_VOTES_HTTP_TIMEOUT_MILLISECONDS = 4 * 1000; // 4 Seconds.
/**
* Default connection and response timeout for voting and registration.
*
* Voting and user registration runs in the background and has has no urgency
* so this can be a larger value.
*/
private static final int API_REGISTER_VOTE_TIMEOUT_MILLISECONDS = 60 * 1000; // 60 Seconds.
/**
* Response code of a successful API call
*/
private static final int HTTP_STATUS_CODE_SUCCESS = 200;
/**
* Indicates a client rate limit has been reached and the client must back off.
*/
private static final int HTTP_STATUS_CODE_RATE_LIMIT = 429;
/**
* How long to wait until API calls are resumed, if the API requested a back off.
* No clear guideline of how long to wait until resuming.
*/
private static final int BACKOFF_RATE_LIMIT_MILLISECONDS = 10 * 60 * 1000; // 10 Minutes.
/**
* How long to wait until API calls are resumed, if any connection error occurs.
*/
private static final int BACKOFF_CONNECTION_ERROR_MILLISECONDS = 2 * 60 * 1000; // 2 Minutes.
/**
* If non zero, then the system time of when API calls can resume.
*/
private static volatile long timeToResumeAPICalls;
/**
* If the last API getVotes call failed for any reason (including server requested rate limit).
* Used to prevent showing repeat connection toasts when the API is down.
*/
private static volatile boolean lastApiCallFailed;
/**
* Number of times {@link #HTTP_STATUS_CODE_RATE_LIMIT} was requested by RYD api.
* Does not include network calls attempted while rate limit is in effect,
* and does not include rate limit imposed if a fetch fails.
*/
private static volatile int numberOfRateLimitRequestsEncountered;
/**
* Number of network calls made in {@link #fetchVotes(String)}
*/
private static volatile int fetchCallCount;
/**
* Number of times {@link #fetchVotes(String)} failed due to timeout or any other error.
* This does not include when rate limit requests are encountered.
*/
private static volatile int fetchCallNumberOfFailures;
/**
* Total time spent waiting for {@link #fetchVotes(String)} network call to complete.
* Value does does not persist on app shut down.
*/
private static volatile long fetchCallResponseTimeTotal;
/**
* Round trip network time for the most recent call to {@link #fetchVotes(String)}
*/
private static volatile long fetchCallResponseTimeLast;
private static volatile long fetchCallResponseTimeMin;
private static volatile long fetchCallResponseTimeMax;
public static final int FETCH_CALL_RESPONSE_TIME_VALUE_RATE_LIMIT = -1;
/**
* If rate limit was hit, this returns {@link #FETCH_CALL_RESPONSE_TIME_VALUE_RATE_LIMIT}
*/
public static long getFetchCallResponseTimeLast() {
return fetchCallResponseTimeLast;
}
public static long getFetchCallResponseTimeMin() {
return fetchCallResponseTimeMin;
}
public static long getFetchCallResponseTimeMax() {
return fetchCallResponseTimeMax;
}
public static long getFetchCallResponseTimeAverage() {
return fetchCallCount == 0 ? 0 : (fetchCallResponseTimeTotal / fetchCallCount);
}
public static int getFetchCallCount() {
return fetchCallCount;
}
public static int getFetchCallNumberOfFailures() {
return fetchCallNumberOfFailures;
}
public static int getNumberOfRateLimitRequestsEncountered() {
return numberOfRateLimitRequestsEncountered;
}
private ReturnYouTubeDislikeApi() {
} // utility class
/**
* Simulates a slow response by doing meaningless calculations.
* Used to debug the app UI and verify UI timeout logic works
*/
private static void randomlyWaitIfLocallyDebugging() {
final boolean DEBUG_RANDOMLY_DELAY_NETWORK_CALLS = false; // set true to debug UI
if (DEBUG_RANDOMLY_DELAY_NETWORK_CALLS) {
final long amountOfTimeToWaste = (long) (Math.random()
* (API_GET_VOTES_TCP_TIMEOUT_MILLISECONDS + API_GET_VOTES_HTTP_TIMEOUT_MILLISECONDS));
Utils.doNothingForDuration(amountOfTimeToWaste);
}
}
/**
* Clears any backoff rate limits in effect.
* Should be called if RYD is turned on/off.
*/
public static void resetRateLimits() {
if (lastApiCallFailed || timeToResumeAPICalls != 0) {
Logger.printDebug(() -> "Reset rate limit");
}
lastApiCallFailed = false;
timeToResumeAPICalls = 0;
}
/**
* @return True, if api rate limit is in effect.
*/
private static boolean checkIfRateLimitInEffect(String apiEndPointName) {
if (timeToResumeAPICalls == 0) {
return false;
}
final long now = System.currentTimeMillis();
if (now > timeToResumeAPICalls) {
timeToResumeAPICalls = 0;
return false;
}
Logger.printDebug(() -> "Ignoring api call " + apiEndPointName + " as rate limit is in effect");
return true;
}
/**
* @return True, if a client rate limit was requested
*/
private static boolean checkIfRateLimitWasHit(int httpResponseCode) {
final boolean DEBUG_RATE_LIMIT = false; // set to true, to verify rate limit works
if (DEBUG_RATE_LIMIT) {
final double RANDOM_RATE_LIMIT_PERCENTAGE = 0.2; // 20% chance of a triggering a rate limit
if (Math.random() < RANDOM_RATE_LIMIT_PERCENTAGE) {
Logger.printDebug(() -> "Artificially triggering rate limit for debug purposes");
httpResponseCode = HTTP_STATUS_CODE_RATE_LIMIT;
}
}
return httpResponseCode == HTTP_STATUS_CODE_RATE_LIMIT;
}
@SuppressWarnings("NonAtomicOperationOnVolatileField") // Don't care, fields are estimates.
private static void updateRateLimitAndStats(long timeNetworkCallStarted, boolean connectionError, boolean rateLimitHit) {
if (connectionError && rateLimitHit) {
throw new IllegalArgumentException();
}
final long responseTimeOfFetchCall = System.currentTimeMillis() - timeNetworkCallStarted;
fetchCallResponseTimeTotal += responseTimeOfFetchCall;
fetchCallResponseTimeMin = (fetchCallResponseTimeMin == 0) ? responseTimeOfFetchCall : Math.min(responseTimeOfFetchCall, fetchCallResponseTimeMin);
fetchCallResponseTimeMax = Math.max(responseTimeOfFetchCall, fetchCallResponseTimeMax);
fetchCallCount++;
if (connectionError) {
timeToResumeAPICalls = System.currentTimeMillis() + BACKOFF_CONNECTION_ERROR_MILLISECONDS;
fetchCallResponseTimeLast = responseTimeOfFetchCall;
fetchCallNumberOfFailures++;
lastApiCallFailed = true;
} else if (rateLimitHit) {
Logger.printDebug(() -> "API rate limit was hit. Stopping API calls for the next "
+ BACKOFF_RATE_LIMIT_MILLISECONDS + " seconds");
timeToResumeAPICalls = System.currentTimeMillis() + BACKOFF_RATE_LIMIT_MILLISECONDS;
numberOfRateLimitRequestsEncountered++;
fetchCallResponseTimeLast = FETCH_CALL_RESPONSE_TIME_VALUE_RATE_LIMIT;
if (!lastApiCallFailed && Settings.RYD_TOAST_ON_CONNECTION_ERROR.get()) {
Utils.showToastLong(str("revanced_ryd_failure_client_rate_limit_requested"));
}
lastApiCallFailed = true;
} else {
fetchCallResponseTimeLast = responseTimeOfFetchCall;
lastApiCallFailed = false;
}
}
private static void handleConnectionError(@NonNull String toastMessage,
@Nullable Exception ex,
boolean showLongToast) {
if (!lastApiCallFailed && Settings.RYD_TOAST_ON_CONNECTION_ERROR.get()) {
if (showLongToast) {
Utils.showToastLong(toastMessage);
} else {
Utils.showToastShort(toastMessage);
}
}
lastApiCallFailed = true;
Logger.printInfo(() -> toastMessage, ex);
}
/**
* @return NULL if fetch failed, or if a rate limit is in effect.
*/
@Nullable
public static RYDVoteData fetchVotes(String videoId) {
Utils.verifyOffMainThread();
Objects.requireNonNull(videoId);
if (checkIfRateLimitInEffect("fetchVotes")) {
return null;
}
Logger.printDebug(() -> "Fetching votes for: " + videoId);
final long timeNetworkCallStarted = System.currentTimeMillis();
try {
HttpURLConnection connection = getRYDConnectionFromRoute(ReturnYouTubeDislikeRoutes.GET_DISLIKES, videoId);
// request headers, as per https://returnyoutubedislike.com/docs/fetching
// the documentation says to use 'Accept:text/html', but the RYD browser plugin uses 'Accept:application/json'
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Connection", "keep-alive"); // keep-alive is on by default with http 1.1, but specify anyways
connection.setRequestProperty("Pragma", "no-cache");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setUseCaches(false);
connection.setConnectTimeout(API_GET_VOTES_TCP_TIMEOUT_MILLISECONDS); // timeout for TCP connection to server
connection.setReadTimeout(API_GET_VOTES_HTTP_TIMEOUT_MILLISECONDS); // timeout for server response
randomlyWaitIfLocallyDebugging();
final int responseCode = connection.getResponseCode();
if (checkIfRateLimitWasHit(responseCode)) {
connection.disconnect(); // rate limit hit, should disconnect
updateRateLimitAndStats(timeNetworkCallStarted, false, true);
return null;
}
if (responseCode == HTTP_STATUS_CODE_SUCCESS) {
// Do not disconnect, the same server connection will likely be used again soon.
JSONObject json = Requester.parseJSONObject(connection);
try {
RYDVoteData votingData = new RYDVoteData(json);
updateRateLimitAndStats(timeNetworkCallStarted, false, false);
Logger.printDebug(() -> "Voting data fetched: " + votingData);
return votingData;
} catch (JSONException ex) {
Logger.printException(() -> "Failed to parse video: " + videoId + " json: " + json, ex);
// fall thru to update statistics
}
} else {
// Unexpected response code. Most likely RYD is temporarily broken.
handleConnectionError(str("revanced_ryd_failure_connection_status_code", responseCode),
null, true);
}
connection.disconnect(); // Something went wrong, might as well disconnect.
} catch (SocketTimeoutException ex) {
handleConnectionError((str("revanced_ryd_failure_connection_timeout")), ex, false);
} catch (IOException ex) {
handleConnectionError((str("revanced_ryd_failure_generic", ex.getMessage())), ex, true);
} catch (Exception ex) {
// should never happen
Logger.printException(() -> "Failed to fetch votes", ex, str("revanced_ryd_failure_generic", ex.getMessage()));
}
updateRateLimitAndStats(timeNetworkCallStarted, true, false);
return null;
}
/**
* @return The newly created and registered user id. Returns NULL if registration failed.
*/
@Nullable
public static String registerAsNewUser() {
Utils.verifyOffMainThread();
try {
if (checkIfRateLimitInEffect("registerAsNewUser")) {
return null;
}
String userId = randomString(36);
Logger.printDebug(() -> "Trying to register new user");
HttpURLConnection connection = getRYDConnectionFromRoute(ReturnYouTubeDislikeRoutes.GET_REGISTRATION, userId);
connection.setRequestProperty("Accept", "application/json");
connection.setConnectTimeout(API_REGISTER_VOTE_TIMEOUT_MILLISECONDS);
connection.setReadTimeout(API_REGISTER_VOTE_TIMEOUT_MILLISECONDS);
final int responseCode = connection.getResponseCode();
if (checkIfRateLimitWasHit(responseCode)) {
connection.disconnect(); // disconnect, as no more connections will be made for a little while
return null;
}
if (responseCode == HTTP_STATUS_CODE_SUCCESS) {
JSONObject json = Requester.parseJSONObject(connection);
String challenge = json.getString("challenge");
int difficulty = json.getInt("difficulty");
String solution = solvePuzzle(challenge, difficulty);
return confirmRegistration(userId, solution);
}
handleConnectionError(str("revanced_ryd_failure_connection_status_code", responseCode),
null, true);
connection.disconnect();
} catch (SocketTimeoutException ex) {
handleConnectionError(str("revanced_ryd_failure_connection_timeout"), ex, false);
} catch (IOException ex) {
handleConnectionError(str("revanced_ryd_failure_generic", "registration failed"), ex, true);
} catch (Exception ex) {
Logger.printException(() -> "Failed to register user", ex); // should never happen
}
return null;
}
@Nullable
private static String confirmRegistration(String userId, String solution) {
Utils.verifyOffMainThread();
Objects.requireNonNull(userId);
Objects.requireNonNull(solution);
try {
if (checkIfRateLimitInEffect("confirmRegistration")) {
return null;
}
Logger.printDebug(() -> "Trying to confirm registration with solution: " + solution);
HttpURLConnection connection = getRYDConnectionFromRoute(ReturnYouTubeDislikeRoutes.CONFIRM_REGISTRATION, userId);
applyCommonPostRequestSettings(connection);
String jsonInputString = "{\"solution\": \"" + solution + "\"}";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
final int responseCode = connection.getResponseCode();
if (checkIfRateLimitWasHit(responseCode)) {
connection.disconnect(); // disconnect, as no more connections will be made for a little while
return null;
}
if (responseCode == HTTP_STATUS_CODE_SUCCESS) {
Logger.printDebug(() -> "Registration confirmation successful");
return userId;
}
// Something went wrong, might as well disconnect.
String response = Requester.parseStringAndDisconnect(connection);
Logger.printInfo(() -> "Failed to confirm registration for user: " + userId
+ " solution: " + solution + " responseCode: " + responseCode + " response: '" + response + "''");
handleConnectionError(str("revanced_ryd_failure_connection_status_code", responseCode),
null, true);
} catch (SocketTimeoutException ex) {
handleConnectionError(str("revanced_ryd_failure_connection_timeout"), ex, false);
} catch (IOException ex) {
handleConnectionError(str("revanced_ryd_failure_generic", "confirm registration failed"),
ex, true);
} catch (Exception ex) {
Logger.printException(() -> "Failed to confirm registration for user: " + userId
+ "solution: " + solution, ex);
}
return null;
}
/**
* Must call off main thread, as this will make a network call if user is not yet registered.
*
* @return ReturnYouTubeDislike user ID. If user registration has never happened
* and the network call fails, this returns NULL.
*/
@Nullable
private static String getUserId() {
Utils.verifyOffMainThread();
String userId = Settings.RYD_USER_ID.get();
if (!userId.isEmpty()) {
return userId;
}
userId = registerAsNewUser();
if (userId != null) {
Settings.RYD_USER_ID.save(userId);
}
return userId;
}
public static boolean sendVote(String videoId, ReturnYouTubeDislike.Vote vote) {
Utils.verifyOffMainThread();
Objects.requireNonNull(videoId);
Objects.requireNonNull(vote);
try {
String userId = getUserId();
if (userId == null) return false;
if (checkIfRateLimitInEffect("sendVote")) {
return false;
}
Logger.printDebug(() -> "Trying to vote for video: " + videoId + " with vote: " + vote);
HttpURLConnection connection = getRYDConnectionFromRoute(ReturnYouTubeDislikeRoutes.SEND_VOTE);
applyCommonPostRequestSettings(connection);
String voteJsonString = "{\"userId\": \"" + userId + "\", \"videoId\": \"" + videoId + "\", \"value\": \"" + vote.value + "\"}";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = voteJsonString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
final int responseCode = connection.getResponseCode();
if (checkIfRateLimitWasHit(responseCode)) {
connection.disconnect(); // disconnect, as no more connections will be made for a little while
return false;
}
if (responseCode == HTTP_STATUS_CODE_SUCCESS) {
JSONObject json = Requester.parseJSONObject(connection);
String challenge = json.getString("challenge");
int difficulty = json.getInt("difficulty");
String solution = solvePuzzle(challenge, difficulty);
return confirmVote(videoId, userId, solution);
}
Logger.printInfo(() -> "Failed to send vote for video: " + videoId + " vote: " + vote
+ " response code was: " + responseCode);
handleConnectionError(str("revanced_ryd_failure_connection_status_code", responseCode),
null, true);
connection.disconnect(); // something went wrong, might as well disconnect
} catch (SocketTimeoutException ex) {
handleConnectionError(str("revanced_ryd_failure_connection_timeout"), ex, false);
} catch (IOException ex) {
handleConnectionError(str("revanced_ryd_failure_generic", "send vote failed"), ex, true);
} catch (Exception ex) {
// should never happen
Logger.printException(() -> "Failed to send vote for video: " + videoId + " vote: " + vote, ex);
}
return false;
}
private static boolean confirmVote(String videoId, String userId, String solution) {
Utils.verifyOffMainThread();
Objects.requireNonNull(videoId);
Objects.requireNonNull(userId);
Objects.requireNonNull(solution);
try {
if (checkIfRateLimitInEffect("confirmVote")) {
return false;
}
Logger.printDebug(() -> "Trying to confirm vote for video: " + videoId + " solution: " + solution);
HttpURLConnection connection = getRYDConnectionFromRoute(ReturnYouTubeDislikeRoutes.CONFIRM_VOTE);
applyCommonPostRequestSettings(connection);
String jsonInputString = "{\"userId\": \"" + userId + "\", \"videoId\": \"" + videoId + "\", \"solution\": \"" + solution + "\"}";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
final int responseCode = connection.getResponseCode();
if (checkIfRateLimitWasHit(responseCode)) {
connection.disconnect(); // disconnect, as no more connections will be made for a little while
return false;
}
if (responseCode == HTTP_STATUS_CODE_SUCCESS) {
Logger.printDebug(() -> "Vote confirm successful for video: " + videoId);
return true;
}
// Something went wrong, might as well disconnect.
String response = Requester.parseStringAndDisconnect(connection);
Logger.printInfo(() -> "Failed to confirm vote for video: " + videoId
+ " solution: " + solution + " responseCode: " + responseCode + " response: '" + response + "'");
handleConnectionError(str("revanced_ryd_failure_connection_status_code", responseCode),
null, true);
} catch (SocketTimeoutException ex) {
handleConnectionError(str("revanced_ryd_failure_connection_timeout"), ex, false);
} catch (IOException ex) {
handleConnectionError(str("revanced_ryd_failure_generic", "confirm vote failed"),
ex, true);
} catch (Exception ex) {
Logger.printException(() -> "Failed to confirm vote for video: " + videoId
+ " solution: " + solution, ex); // should never happen
}
return false;
}
private static void applyCommonPostRequestSettings(HttpURLConnection connection) throws ProtocolException {
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Pragma", "no-cache");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setConnectTimeout(API_REGISTER_VOTE_TIMEOUT_MILLISECONDS); // timeout for TCP connection to server
connection.setReadTimeout(API_REGISTER_VOTE_TIMEOUT_MILLISECONDS); // timeout for server response
}
private static String solvePuzzle(String challenge, int difficulty) {
final long timeSolveStarted = System.currentTimeMillis();
byte[] decodedChallenge = Base64.decode(challenge, Base64.NO_WRAP);
byte[] buffer = new byte[20];
System.arraycopy(decodedChallenge, 0, buffer, 4, 16);
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException(ex); // should never happen
}
final int maxCount = (int) (Math.pow(2, difficulty + 1) * 5);
for (int i = 0; i < maxCount; i++) {
buffer[0] = (byte) i;
buffer[1] = (byte) (i >> 8);
buffer[2] = (byte) (i >> 16);
buffer[3] = (byte) (i >> 24);
byte[] messageDigest = md.digest(buffer);
if (countLeadingZeroes(messageDigest) >= difficulty) {
String solution = Base64.encodeToString(new byte[]{buffer[0], buffer[1], buffer[2], buffer[3]}, Base64.NO_WRAP);
Logger.printDebug(() -> "Found puzzle solution: " + solution + " of difficulty: " + difficulty
+ " in: " + (System.currentTimeMillis() - timeSolveStarted) + " ms");
return solution;
}
}
// should never be reached
throw new IllegalStateException("Failed to solve puzzle challenge: " + challenge + " difficulty: " + difficulty);
}
// https://stackoverflow.com/a/157202
private static String randomString(int len) {
String AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
SecureRandom rnd = new SecureRandom();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
private static int countLeadingZeroes(byte[] uInt8View) {
int zeroes = 0;
for (byte b : uInt8View) {
int value = b & 0xFF;
if (value == 0) {
zeroes += 8;
} else {
int count = 1;
if (value >>> 4 == 0) {
count += 4;
value <<= 4;
}
if (value >>> 6 == 0) {
count += 2;
value <<= 2;
}
zeroes += count - (value >>> 7);
break;
}
}
return zeroes;
}
}
| 26,770 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ReturnYouTubeDislikeRoutes.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/returnyoutubedislike/requests/ReturnYouTubeDislikeRoutes.java | package app.revanced.integrations.youtube.returnyoutubedislike.requests;
import static app.revanced.integrations.youtube.requests.Route.Method.GET;
import static app.revanced.integrations.youtube.requests.Route.Method.POST;
import java.io.IOException;
import java.net.HttpURLConnection;
import app.revanced.integrations.youtube.requests.Requester;
import app.revanced.integrations.youtube.requests.Route;
class ReturnYouTubeDislikeRoutes {
static final String RYD_API_URL = "https://returnyoutubedislikeapi.com/";
static final Route SEND_VOTE = new Route(POST, "interact/vote");
static final Route CONFIRM_VOTE = new Route(POST, "interact/confirmVote");
static final Route GET_DISLIKES = new Route(GET, "votes?videoId={video_id}");
static final Route GET_REGISTRATION = new Route(GET, "puzzle/registration?userId={user_id}");
static final Route CONFIRM_REGISTRATION = new Route(POST, "puzzle/registration?userId={user_id}");
private ReturnYouTubeDislikeRoutes() {
}
static HttpURLConnection getRYDConnectionFromRoute(Route route, String... params) throws IOException {
return Requester.getConnectionFromRoute(RYD_API_URL, route, params);
}
} | 1,197 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
CopyVideoUrlPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/CopyVideoUrlPatch.java | package app.revanced.integrations.youtube.patches;
import static app.revanced.integrations.shared.StringRef.str;
import android.os.Build;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
public class CopyVideoUrlPatch {
public static void copyUrl(boolean withTimestamp) {
try {
StringBuilder builder = new StringBuilder("https://youtu.be/");
builder.append(VideoInformation.getVideoId());
final long currentVideoTimeInSeconds = VideoInformation.getVideoTime() / 1000;
if (withTimestamp && currentVideoTimeInSeconds > 0) {
final long hour = currentVideoTimeInSeconds / (60 * 60);
final long minute = (currentVideoTimeInSeconds / 60) % 60;
final long second = currentVideoTimeInSeconds % 60;
builder.append("?t=");
if (hour > 0) {
builder.append(hour).append("h");
}
if (minute > 0) {
builder.append(minute).append("m");
}
if (second > 0) {
builder.append(second).append("s");
}
}
Utils.setClipboard(builder.toString());
// Do not show a toast if using Android 13+ as it shows it's own toast.
// But if the user copied with a timestamp then show a toast.
// Unfortunately this will show 2 toasts on Android 13+, but no way around this.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2 || (withTimestamp && currentVideoTimeInSeconds > 0)) {
Utils.showToastShort(withTimestamp && currentVideoTimeInSeconds > 0
? str("revanced_share_copy_url_timestamp_success")
: str("revanced_share_copy_url_success"));
}
} catch (Exception e) {
Logger.printException(() -> "Failed to generate video url", e);
}
}
}
| 2,014 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
RemoveTrackingQueryParameterPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/RemoveTrackingQueryParameterPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class RemoveTrackingQueryParameterPatch {
private static final String NEW_TRACKING_PARAMETER_REGEX = ".si=.+";
private static final String OLD_TRACKING_PARAMETER_REGEX = ".feature=.+";
public static String sanitize(String url) {
if (!Settings.REMOVE_TRACKING_QUERY_PARAMETER.get()) return url;
return url
.replaceAll(NEW_TRACKING_PARAMETER_REGEX, "")
.replaceAll(OLD_TRACKING_PARAMETER_REGEX, "");
}
}
| 622 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SeekbarTappingPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/SeekbarTappingPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class SeekbarTappingPatch {
public static boolean seekbarTappingEnabled() {
return Settings.SEEKBAR_TAPPING.get();
}
}
| 289 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
MinimizedPlaybackPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/MinimizedPlaybackPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.shared.PlayerType;
@SuppressWarnings("unused")
public class MinimizedPlaybackPatch {
/**
* Injection point.
*/
public static boolean playbackIsNotShort() {
// Steps to verify most edge cases:
// 1. Open a regular video
// 2. Minimize app (PIP should appear)
// 3. Reopen app
// 4. Open a Short (without closing the regular video)
// (try opening both Shorts in the video player suggestions AND Shorts from the home feed)
// 5. Minimize the app (PIP should not appear)
// 6. Reopen app
// 7. Close the Short
// 8. Resume playing the regular video
// 9. Minimize the app (PIP should appear)
if (!VideoInformation.lastVideoIdIsShort()) {
return true; // Definitely is not a Short.
}
// Might be a Short, or might be a prior regular video on screen again after a Short was closed.
// This incorrectly prevents PIP if player is in WATCH_WHILE_MINIMIZED after closing a Short,
// But there's no way around this unless an additional hook is added to definitively detect
// the Shorts player is on screen. This use case is unusual anyways so it's not a huge concern.
return !PlayerType.getCurrent().isNoneHiddenOrMinimized();
}
/**
* Injection point.
*/
public static boolean overrideMinimizedPlaybackAvailable() {
// This could be done entirely in the patch,
// but having a unique method to search for makes manually inspecting the patched apk much easier.
return true;
}
}
| 1,694 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideEndscreenCardsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideEndscreenCardsPatch.java | package app.revanced.integrations.youtube.patches;
import android.view.View;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class HideEndscreenCardsPatch {
//Used by app.revanced.patches.youtube.layout.hideendscreencards.bytecode.patch.HideEndscreenCardsPatch
public static void hideEndscreen(View view) {
if (!Settings.HIDE_ENDSCREEN_CARDS.get()) return;
view.setVisibility(View.GONE);
}
} | 469 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideEmailAddressPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideEmailAddressPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class HideEmailAddressPatch {
//Used by app.revanced.patches.youtube.layout.personalinformation.patch.HideEmailAddressPatch
public static int hideEmailAddress(int originalValue) {
if (Settings.HIDE_EMAIL_ADDRESS.get())
return 8;
return originalValue;
}
}
| 443 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ZoomHapticsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/ZoomHapticsPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class ZoomHapticsPatch {
public static boolean shouldVibrate() {
return !Settings.DISABLE_ZOOM_HAPTICS.get();
}
}
| 278 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
WideSearchbarPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/WideSearchbarPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class WideSearchbarPatch {
public static boolean enableWideSearchbar(boolean original) {
return Settings.WIDE_SEARCHBAR.get() || original;
}
}
| 314 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
DisableResumingStartupShortsPlayerPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/DisableResumingStartupShortsPlayerPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
/** @noinspection unused*/
public class DisableResumingStartupShortsPlayerPatch {
/**
* Injection point.
*/
public static boolean disableResumingStartupShortsPlayer() {
return Settings.DISABLE_RESUMING_SHORTS_PLAYER.get();
}
}
| 371 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
CustomPlayerOverlayOpacityPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/CustomPlayerOverlayOpacityPatch.java | package app.revanced.integrations.youtube.patches;
import android.widget.ImageView;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.shared.Utils;
@SuppressWarnings("unused")
public class CustomPlayerOverlayOpacityPatch {
public static void changeOpacity(ImageView imageView) {
int opacity = Settings.PLAYER_OVERLAY_OPACITY.get();
if (opacity < 0 || opacity > 100) {
Utils.showToastLong("Player overlay opacity must be between 0-100");
Settings.PLAYER_OVERLAY_OPACITY.resetToDefault();
opacity = Settings.PLAYER_OVERLAY_OPACITY.defaultValue;
}
imageView.setImageAlpha((opacity * 255) / 100);
}
}
| 722 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
OpenLinksExternallyPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/OpenLinksExternallyPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class OpenLinksExternallyPatch {
/**
* Return the intent to open links with. If empty, the link will be opened with the default browser.
*
* @param originalIntent The original intent to open links with.
* @return The intent to open links with. Empty means the link will be opened with the default browser.
*/
public static String getIntent(String originalIntent) {
if (Settings.EXTERNAL_BROWSER.get()) return "";
return originalIntent;
}
}
| 642 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
NavigationButtonsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/NavigationButtonsPatch.java | package app.revanced.integrations.youtube.patches;
import static app.revanced.integrations.youtube.shared.NavigationBar.NavigationButton;
import android.view.View;
import java.util.EnumMap;
import java.util.Map;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class NavigationButtonsPatch {
private static final Map<NavigationButton, Boolean> shouldHideMap = new EnumMap<>(NavigationButton.class) {
{
put(NavigationButton.HOME, Settings.HIDE_HOME_BUTTON.get());
put(NavigationButton.CREATE, Settings.HIDE_CREATE_BUTTON.get());
put(NavigationButton.SHORTS, Settings.HIDE_SHORTS_BUTTON.get());
put(NavigationButton.SUBSCRIPTIONS, Settings.HIDE_SUBSCRIPTIONS_BUTTON.get());
}
};
private static final Boolean SWITCH_CREATE_WITH_NOTIFICATIONS_BUTTON
= Settings.SWITCH_CREATE_WITH_NOTIFICATIONS_BUTTON.get();
/**
* Injection point.
*/
public static boolean switchCreateWithNotificationButton() {
return SWITCH_CREATE_WITH_NOTIFICATIONS_BUTTON;
}
/**
* Injection point.
*/
public static void navigationTabCreated(NavigationButton button, View tabView) {
if (Boolean.TRUE.equals(shouldHideMap.get(button))) {
tabView.setVisibility(View.GONE);
}
}
}
| 1,419 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideCrowdfundingBoxPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideCrowdfundingBoxPatch.java | package app.revanced.integrations.youtube.patches;
import android.view.View;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.shared.Utils;
@SuppressWarnings("unused")
public class HideCrowdfundingBoxPatch {
//Used by app.revanced.patches.youtube.layout.hidecrowdfundingbox.patch.HideCrowdfundingBoxPatch
public static void hideCrowdfundingBox(View view) {
if (!Settings.HIDE_CROWDFUNDING_BOX.get()) return;
Utils.hideViewByLayoutParams(view);
}
}
| 523 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
RestoreOldSeekbarThumbnailsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/RestoreOldSeekbarThumbnailsPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class RestoreOldSeekbarThumbnailsPatch {
public static boolean useFullscreenSeekbarThumbnails() {
return !Settings.RESTORE_OLD_SEEKBAR_THUMBNAILS.get();
}
}
| 327 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SlideToSeekPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/SlideToSeekPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class SlideToSeekPatch {
public static boolean isSlideToSeekDisabled() {
return !Settings.SLIDE_TO_SEEK.get();
}
}
| 285 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideSeekbarPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideSeekbarPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class HideSeekbarPatch {
public static boolean hideSeekbar() {
return Settings.HIDE_SEEKBAR.get();
}
}
| 267 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
PlayerOverlaysHookPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/PlayerOverlaysHookPatch.java | package app.revanced.integrations.youtube.patches;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import app.revanced.integrations.youtube.shared.PlayerOverlays;
@SuppressWarnings("unused")
public class PlayerOverlaysHookPatch {
/**
* Injection point.
*/
public static void playerOverlayInflated(ViewGroup group) {
PlayerOverlays.attach(group);
}
} | 403 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideCaptionsButtonPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideCaptionsButtonPatch.java | package app.revanced.integrations.youtube.patches;
import android.widget.ImageView;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class HideCaptionsButtonPatch {
//Used by app.revanced.patches.youtube.layout.hidecaptionsbutton.patch.HideCaptionsButtonPatch
public static void hideCaptionsButton(ImageView imageView) {
imageView.setVisibility(Settings.HIDE_CAPTIONS_BUTTON.get() ? ImageView.GONE : ImageView.VISIBLE);
}
}
| 493 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
BypassURLRedirectsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/BypassURLRedirectsPatch.java | package app.revanced.integrations.youtube.patches;
import android.net.Uri;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.shared.Logger;
@SuppressWarnings("unused")
public class BypassURLRedirectsPatch {
private static final String YOUTUBE_REDIRECT_PATH = "/redirect";
/**
* Convert the YouTube redirect URI string to the redirect query URI.
*
* @param uri The YouTube redirect URI string.
* @return The redirect query URI.
*/
public static Uri parseRedirectUri(String uri) {
final var parsed = Uri.parse(uri);
if (Settings.BYPASS_URL_REDIRECTS.get() && parsed.getPath().equals(YOUTUBE_REDIRECT_PATH)) {
var query = Uri.parse(Uri.decode(parsed.getQueryParameter("q")));
Logger.printDebug(() -> "Bypassing YouTube redirect URI: " + query);
return query;
}
return parsed;
}
}
| 937 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideTimestampPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideTimestampPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class HideTimestampPatch {
public static boolean hideTimestamp() {
return Settings.HIDE_TIMESTAMP.get();
}
}
| 273 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
DisablePlayerPopupPanelsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/DisablePlayerPopupPanelsPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class DisablePlayerPopupPanelsPatch {
//Used by app.revanced.patches.youtube.layout.playerpopuppanels.patch.PlayerPopupPanelsPatch
public static boolean disablePlayerPopupPanels() {
return Settings.PLAYER_POPUP_PANELS.get();
}
}
| 397 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
AlternativeThumbnailsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/AlternativeThumbnailsPatch.java | package app.revanced.integrations.youtube.patches;
import static app.revanced.integrations.shared.StringRef.str;
import static app.revanced.integrations.youtube.settings.Settings.*;
import static app.revanced.integrations.youtube.shared.NavigationBar.NavigationButton;
import android.net.Uri;
import androidx.annotation.GuardedBy;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.net.UrlRequest;
import org.chromium.net.UrlResponseInfo;
import org.chromium.net.impl.CronetUrlRequest;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.shared.settings.Setting;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.shared.NavigationBar;
import app.revanced.integrations.youtube.shared.PlayerType;
/**
* Alternative YouTube thumbnails.
* <p>
* Can show YouTube provided screen captures of beginning/middle/end of the video.
* (ie: sd1.jpg, sd2.jpg, sd3.jpg).
* <p>
* Or can show crowd-sourced thumbnails provided by DeArrow (<a href="http://dearrow.ajay.app">...</a>).
* <p>
* Or can use DeArrow and fall back to screen captures if DeArrow is not available.
* <p>
* Has an additional option to use 'fast' video still thumbnails,
* where it forces sd thumbnail quality and skips verifying if the alt thumbnail image exists.
* The UI loading time will be the same or better than using original thumbnails,
* but thumbnails will initially fail to load for all live streams, unreleased, and occasionally very old videos.
* If a failed thumbnail load is reloaded (ie: scroll off, then on screen), then the original thumbnail
* is reloaded instead. Fast thumbnails requires using SD or lower thumbnail resolution,
* because a noticeable number of videos do not have hq720 and too much fail to load.
*/
@SuppressWarnings("unused")
public final class AlternativeThumbnailsPatch {
// These must be class declarations if declared here,
// otherwise the app will not load due to cyclic initialization errors.
public static final class DeArrowAvailability implements Setting.Availability {
public static boolean usingDeArrowAnywhere() {
return ALT_THUMBNAIL_HOME.get().useDeArrow
|| ALT_THUMBNAIL_SUBSCRIPTIONS.get().useDeArrow
|| ALT_THUMBNAIL_LIBRARY.get().useDeArrow
|| ALT_THUMBNAIL_PLAYER.get().useDeArrow
|| ALT_THUMBNAIL_SEARCH.get().useDeArrow;
}
@Override
public boolean isAvailable() {
return usingDeArrowAnywhere();
}
}
public static final class StillImagesAvailability implements Setting.Availability {
public static boolean usingStillImagesAnywhere() {
return ALT_THUMBNAIL_HOME.get().useStillImages
|| ALT_THUMBNAIL_SUBSCRIPTIONS.get().useStillImages
|| ALT_THUMBNAIL_LIBRARY.get().useStillImages
|| ALT_THUMBNAIL_PLAYER.get().useStillImages
|| ALT_THUMBNAIL_SEARCH.get().useStillImages;
}
@Override
public boolean isAvailable() {
return usingStillImagesAnywhere();
}
}
public enum ThumbnailOption {
ORIGINAL(false, false),
DEARROW(true, false),
DEARROW_STILL_IMAGES(true, true),
STILL_IMAGES(false, true);
final boolean useDeArrow;
final boolean useStillImages;
ThumbnailOption(boolean useDeArrow, boolean useStillImages) {
this.useDeArrow = useDeArrow;
this.useStillImages = useStillImages;
}
}
public enum ThumbnailStillTime {
BEGINNING(1),
MIDDLE(2),
END(3);
/**
* The url alt image number. Such as the 2 in 'hq720_2.jpg'
*/
final int altImageNumber;
ThumbnailStillTime(int altImageNumber) {
this.altImageNumber = altImageNumber;
}
}
private static final Uri dearrowApiUri;
/**
* The scheme and host of {@link #dearrowApiUri}.
*/
private static final String deArrowApiUrlPrefix;
/**
* How long to temporarily turn off DeArrow if it fails for any reason.
*/
private static final long DEARROW_FAILURE_API_BACKOFF_MILLISECONDS = 5 * 60 * 1000; // 5 Minutes.
/**
* If non zero, then the system time of when DeArrow API calls can resume.
*/
private static volatile long timeToResumeDeArrowAPICalls;
static {
dearrowApiUri = validateSettings();
final int port = dearrowApiUri.getPort();
String portString = port == -1 ? "" : (":" + port);
deArrowApiUrlPrefix = dearrowApiUri.getScheme() + "://" + dearrowApiUri.getHost() + portString + "/";
Logger.printDebug(() -> "Using DeArrow API address: " + deArrowApiUrlPrefix);
}
/**
* Fix any bad imported data.
*/
private static Uri validateSettings() {
Uri apiUri = Uri.parse(Settings.ALT_THUMBNAIL_DEARROW_API_URL.get());
// Cannot use unsecured 'http', otherwise the connections fail to start and no callbacks hooks are made.
String scheme = apiUri.getScheme();
if (scheme == null || scheme.equals("http") || apiUri.getHost() == null) {
Utils.showToastLong("Invalid DeArrow API URL. Using default");
Settings.ALT_THUMBNAIL_DEARROW_API_URL.resetToDefault();
return validateSettings();
}
return apiUri;
}
private static ThumbnailOption optionSettingForCurrentNavigation() {
// Must check player type first, as search bar can be active behind the player.
if (PlayerType.getCurrent().isMaximizedOrFullscreen()) {
return ALT_THUMBNAIL_PLAYER.get();
}
// Must check second, as search can be from any tab.
if (NavigationBar.isSearchBarActive()) {
return ALT_THUMBNAIL_SEARCH.get();
}
// Avoid checking which navigation button is selected, if all other settings are the same.
ThumbnailOption homeOption = ALT_THUMBNAIL_HOME.get();
ThumbnailOption subscriptionsOption = ALT_THUMBNAIL_SUBSCRIPTIONS.get();
ThumbnailOption libraryOption = ALT_THUMBNAIL_LIBRARY.get();
if ((homeOption == subscriptionsOption) && (homeOption == libraryOption)) {
return homeOption; // All are the same option.
}
NavigationButton selectedNavButton = NavigationButton.getSelectedNavigationButton();
if (selectedNavButton == null) {
// Unknown tab, treat as the home tab;
return homeOption;
}
if (selectedNavButton == NavigationButton.HOME) {
return homeOption;
}
if (selectedNavButton == NavigationButton.SUBSCRIPTIONS || selectedNavButton == NavigationButton.NOTIFICATIONS) {
return subscriptionsOption;
}
// A library tab variant is active.
return libraryOption;
}
/**
* Build the alternative thumbnail url using YouTube provided still video captures.
*
* @param decodedUrl Decoded original thumbnail request url.
* @return The alternative thumbnail url, or the original url. Both without tracking parameters.
*/
@NonNull
private static String buildYoutubeVideoStillURL(@NonNull DecodedThumbnailUrl decodedUrl,
@NonNull ThumbnailQuality qualityToUse) {
String sanitizedReplacement = decodedUrl.createStillsUrl(qualityToUse, false);
if (VerifiedQualities.verifyAltThumbnailExist(decodedUrl.videoId, qualityToUse, sanitizedReplacement)) {
return sanitizedReplacement;
}
return decodedUrl.sanitizedUrl;
}
/**
* Build the alternative thumbnail url using DeArrow thumbnail cache.
*
* @param videoId ID of the video to get a thumbnail of. Can be any video (regular or Short).
* @param fallbackUrl URL to fall back to in case.
* @return The alternative thumbnail url, without tracking parameters.
*/
@NonNull
private static String buildDeArrowThumbnailURL(String videoId, String fallbackUrl) {
// Build thumbnail request url.
// See https://github.com/ajayyy/DeArrowThumbnailCache/blob/29eb4359ebdf823626c79d944a901492d760bbbc/app.py#L29.
return dearrowApiUri
.buildUpon()
.appendQueryParameter("videoID", videoId)
.appendQueryParameter("redirectUrl", fallbackUrl)
.build()
.toString();
}
private static boolean urlIsDeArrow(@NonNull String imageUrl) {
return imageUrl.startsWith(deArrowApiUrlPrefix);
}
/**
* @return If this client has not recently experienced any DeArrow API errors.
*/
private static boolean canUseDeArrowAPI() {
if (timeToResumeDeArrowAPICalls == 0) {
return true;
}
if (timeToResumeDeArrowAPICalls < System.currentTimeMillis()) {
Logger.printDebug(() -> "Resuming DeArrow API calls");
timeToResumeDeArrowAPICalls = 0;
return true;
}
return false;
}
private static void handleDeArrowError(@NonNull String url, int statusCode) {
Logger.printDebug(() -> "Encountered DeArrow error. Url: " + url);
final long now = System.currentTimeMillis();
if (timeToResumeDeArrowAPICalls < now) {
timeToResumeDeArrowAPICalls = now + DEARROW_FAILURE_API_BACKOFF_MILLISECONDS;
if (Settings.ALT_THUMBNAIL_DEARROW_CONNECTION_TOAST.get()) {
String toastMessage = (statusCode != 0)
? str("revanced_alt_thumbnail_dearrow_error", statusCode)
: str("revanced_alt_thumbnail_dearrow_error_generic");
Utils.showToastLong(toastMessage);
}
}
}
/**
* Injection point. Called off the main thread and by multiple threads at the same time.
*
* @param originalUrl Image url for all url images loaded, including video thumbnails.
*/
public static String overrideImageURL(String originalUrl) {
try {
ThumbnailOption option = optionSettingForCurrentNavigation();
if (option == ThumbnailOption.ORIGINAL) {
return originalUrl;
}
final var decodedUrl = DecodedThumbnailUrl.decodeImageUrl(originalUrl);
if (decodedUrl == null) {
return originalUrl; // Not a thumbnail.
}
Logger.printDebug(() -> "Original url: " + decodedUrl.sanitizedUrl);
ThumbnailQuality qualityToUse = ThumbnailQuality.getQualityToUse(decodedUrl.imageQuality);
if (qualityToUse == null) {
// Thumbnail is a Short or a Storyboard image used for seekbar thumbnails (must not replace these).
return originalUrl;
}
String sanitizedReplacementUrl;
final boolean includeTracking;
if (option.useDeArrow && canUseDeArrowAPI()) {
includeTracking = false; // Do not include view tracking parameters with API call.
final String fallbackUrl = option.useStillImages
? buildYoutubeVideoStillURL(decodedUrl, qualityToUse)
: decodedUrl.sanitizedUrl;
sanitizedReplacementUrl = buildDeArrowThumbnailURL(decodedUrl.videoId, fallbackUrl);
} else if (option.useStillImages) {
includeTracking = true; // Include view tracking parameters if present.
sanitizedReplacementUrl = buildYoutubeVideoStillURL(decodedUrl, qualityToUse);
} else {
return originalUrl; // Recently experienced DeArrow failure and video stills are not enabled.
}
// Do not log any tracking parameters.
Logger.printDebug(() -> "Replacement url: " + sanitizedReplacementUrl);
return includeTracking
? sanitizedReplacementUrl + decodedUrl.viewTrackingParameters
: sanitizedReplacementUrl;
} catch (Exception ex) {
Logger.printException(() -> "overrideImageURL failure", ex);
return originalUrl;
}
}
/**
* Injection point.
* <p>
* Cronet considers all completed connections as a success, even if the response is 404 or 5xx.
*/
public static void handleCronetSuccess(UrlRequest request, @NonNull UrlResponseInfo responseInfo) {
try {
final int statusCode = responseInfo.getHttpStatusCode();
if (statusCode == 200) {
return;
}
String url = responseInfo.getUrl();
if (urlIsDeArrow(url)) {
Logger.printDebug(() -> "handleCronetSuccess, statusCode: " + statusCode);
if (statusCode == 304) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304
return; // Normal response.
}
handleDeArrowError(url, statusCode);
return;
}
if (statusCode == 404) {
// Fast alt thumbnails is enabled and the thumbnail is not available.
// The video is:
// - live stream
// - upcoming unreleased video
// - very old
// - very low view count
// Take note of this, so if the image reloads the original thumbnail will be used.
DecodedThumbnailUrl decodedUrl = DecodedThumbnailUrl.decodeImageUrl(url);
if (decodedUrl == null) {
return; // Not a thumbnail.
}
Logger.printDebug(() -> "handleCronetSuccess, image not available: " + url);
ThumbnailQuality quality = ThumbnailQuality.altImageNameToQuality(decodedUrl.imageQuality);
if (quality == null) {
// Video is a short or a seekbar thumbnail, but somehow did not load. Should not happen.
Logger.printDebug(() -> "Failed to recognize image quality of url: " + decodedUrl.sanitizedUrl);
return;
}
VerifiedQualities.setAltThumbnailDoesNotExist(decodedUrl.videoId, quality);
}
} catch (Exception ex) {
Logger.printException(() -> "Callback success error", ex);
}
}
/**
* Injection point.
* <p>
* To test failure cases, try changing the API URL to each of:
* - A non-existent domain.
* - A url path of something incorrect (ie: /v1/nonExistentEndPoint).
* <p>
* Cronet uses a very timeout (several minutes), so if the API never responds this hook can take a while to be called.
* But this does not appear to be a problem, as the DeArrow API has not been observed to 'go silent'
* Instead if there's a problem it returns an error code status response, which is handled in this patch.
*/
public static void handleCronetFailure(UrlRequest request,
@Nullable UrlResponseInfo responseInfo,
IOException exception) {
try {
String url = ((CronetUrlRequest) request).getHookedUrl();
if (urlIsDeArrow(url)) {
Logger.printDebug(() -> "handleCronetFailure, exception: " + exception);
final int statusCode = (responseInfo != null)
? responseInfo.getHttpStatusCode()
: 0;
handleDeArrowError(url, statusCode);
}
} catch (Exception ex) {
Logger.printException(() -> "Callback failure error", ex);
}
}
private enum ThumbnailQuality {
// In order of lowest to highest resolution.
DEFAULT("default", ""), // effective alt name is 1.jpg, 2.jpg, 3.jpg
MQDEFAULT("mqdefault", "mq"),
HQDEFAULT("hqdefault", "hq"),
SDDEFAULT("sddefault", "sd"),
HQ720("hq720", "hq720_"),
MAXRESDEFAULT("maxresdefault", "maxres");
/**
* Lookup map of original name to enum.
*/
private static final Map<String, ThumbnailQuality> originalNameToEnum = new HashMap<>();
/**
* Lookup map of alt name to enum. ie: "hq720_1" to {@link #HQ720}.
*/
private static final Map<String, ThumbnailQuality> altNameToEnum = new HashMap<>();
static {
for (ThumbnailQuality quality : values()) {
originalNameToEnum.put(quality.originalName, quality);
for (ThumbnailStillTime time : ThumbnailStillTime.values()) {
// 'custom' thumbnails set by the content creator.
// These show up in place of regular thumbnails
// and seem to be limited to the same [1, 3] range as the still captures.
originalNameToEnum.put(quality.originalName + "_custom_" + time.altImageNumber, quality);
altNameToEnum.put(quality.altImageName + time.altImageNumber, quality);
}
}
}
/**
* Convert an alt image name to enum.
* ie: "hq720_2" returns {@link #HQ720}.
*/
@Nullable
static ThumbnailQuality altImageNameToQuality(@NonNull String altImageName) {
return altNameToEnum.get(altImageName);
}
/**
* Original quality to effective alt quality to use.
* ie: If fast alt image is enabled, then "hq720" returns {@link #SDDEFAULT}.
*/
@Nullable
static ThumbnailQuality getQualityToUse(@NonNull String originalSize) {
ThumbnailQuality quality = originalNameToEnum.get(originalSize);
if (quality == null) {
return null; // Not a thumbnail for a regular video.
}
final boolean useFastQuality = Settings.ALT_THUMBNAIL_STILLS_FAST.get();
switch (quality) {
case SDDEFAULT:
// SD alt images have somewhat worse quality with washed out color and poor contrast.
// But the 720 images look much better and don't suffer from these issues.
// For unknown reasons, the 720 thumbnails are used only for the home feed,
// while SD is used for the search and subscription feed
// (even though search and subscriptions use the exact same layout as the home feed).
// Of note, this image quality issue only appears with the alt thumbnail images,
// and the regular thumbnails have identical color/contrast quality for all sizes.
// Fix this by falling thru and upgrading SD to 720.
case HQ720:
if (useFastQuality) {
return SDDEFAULT; // SD is max resolution for fast alt images.
}
return HQ720;
case MAXRESDEFAULT:
if (useFastQuality) {
return SDDEFAULT;
}
return MAXRESDEFAULT;
default:
return quality;
}
}
final String originalName;
final String altImageName;
ThumbnailQuality(String originalName, String altImageName) {
this.originalName = originalName;
this.altImageName = altImageName;
}
String getAltImageNameToUse() {
return altImageName + Settings.ALT_THUMBNAIL_STILLS_TIME.get().altImageNumber;
}
}
/**
* Uses HTTP HEAD requests to verify and keep track of which thumbnail sizes
* are available and not available.
*/
private static class VerifiedQualities {
/**
* After a quality is verified as not available, how long until the quality is re-verified again.
* Used only if fast mode is not enabled. Intended for live streams and unreleased videos
* that are now finished and available (and thus, the alt thumbnails are also now available).
*/
private static final long NOT_AVAILABLE_TIMEOUT_MILLISECONDS = 10 * 60 * 1000; // 10 minutes.
/**
* Cache used to verify if an alternative thumbnails exists for a given video id.
*/
@GuardedBy("itself")
private static final Map<String, VerifiedQualities> altVideoIdLookup = new LinkedHashMap<>(100) {
private static final int CACHE_LIMIT = 1000;
@Override
protected boolean removeEldestEntry(Entry eldest) {
return size() > CACHE_LIMIT; // Evict the oldest entry if over the cache limit.
}
};
private static VerifiedQualities getVerifiedQualities(@NonNull String videoId, boolean returnNullIfDoesNotExist) {
synchronized (altVideoIdLookup) {
VerifiedQualities verified = altVideoIdLookup.get(videoId);
if (verified == null) {
if (returnNullIfDoesNotExist) {
return null;
}
verified = new VerifiedQualities();
altVideoIdLookup.put(videoId, verified);
}
return verified;
}
}
static boolean verifyAltThumbnailExist(@NonNull String videoId, @NonNull ThumbnailQuality quality,
@NonNull String imageUrl) {
VerifiedQualities verified = getVerifiedQualities(videoId, Settings.ALT_THUMBNAIL_STILLS_FAST.get());
if (verified == null) return true; // Fast alt thumbnails is enabled.
return verified.verifyYouTubeThumbnailExists(videoId, quality, imageUrl);
}
static void setAltThumbnailDoesNotExist(@NonNull String videoId, @NonNull ThumbnailQuality quality) {
VerifiedQualities verified = getVerifiedQualities(videoId, false);
//noinspection ConstantConditions
verified.setQualityVerified(videoId, quality, false);
}
/**
* Highest quality verified as existing.
*/
@Nullable
private ThumbnailQuality highestQualityVerified;
/**
* Lowest quality verified as not existing.
*/
@Nullable
private ThumbnailQuality lowestQualityNotAvailable;
/**
* System time, of when to invalidate {@link #lowestQualityNotAvailable}.
* Used only if fast mode is not enabled.
*/
private long timeToReVerifyLowestQuality;
private synchronized void setQualityVerified(String videoId, ThumbnailQuality quality, boolean isVerified) {
if (isVerified) {
if (highestQualityVerified == null || highestQualityVerified.ordinal() < quality.ordinal()) {
highestQualityVerified = quality;
}
} else {
if (lowestQualityNotAvailable == null || lowestQualityNotAvailable.ordinal() > quality.ordinal()) {
lowestQualityNotAvailable = quality;
timeToReVerifyLowestQuality = System.currentTimeMillis() + NOT_AVAILABLE_TIMEOUT_MILLISECONDS;
}
Logger.printDebug(() -> quality + " not available for video: " + videoId);
}
}
/**
* Verify if a video alt thumbnail exists. Does so by making a minimal HEAD http request.
*/
synchronized boolean verifyYouTubeThumbnailExists(@NonNull String videoId, @NonNull ThumbnailQuality quality,
@NonNull String imageUrl) {
if (highestQualityVerified != null && highestQualityVerified.ordinal() >= quality.ordinal()) {
return true; // Previously verified as existing.
}
final boolean fastQuality = Settings.ALT_THUMBNAIL_STILLS_FAST.get();
if (lowestQualityNotAvailable != null && lowestQualityNotAvailable.ordinal() <= quality.ordinal()) {
if (fastQuality || System.currentTimeMillis() < timeToReVerifyLowestQuality) {
return false; // Previously verified as not existing.
}
// Enough time has passed, and should re-verify again.
Logger.printDebug(() -> "Resetting lowest verified quality for: " + videoId);
lowestQualityNotAvailable = null;
}
if (fastQuality) {
return true; // Unknown if it exists or not. Use the URL anyways and update afterwards if loading fails.
}
boolean imageFileFound;
try {
// This hooked code is running on a low priority thread, and it's slightly faster
// to run the url connection thru the integrations thread pool which runs at the highest priority.
final long start = System.currentTimeMillis();
imageFileFound = Utils.submitOnBackgroundThread(() -> {
final int connectionTimeoutMillis = 10000; // 10 seconds.
HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl).openConnection();
connection.setConnectTimeout(connectionTimeoutMillis);
connection.setReadTimeout(connectionTimeoutMillis);
connection.setRequestMethod("HEAD");
// Even with a HEAD request, the response is the same size as a full GET request.
// Using an empty range fixes this.
connection.setRequestProperty("Range", "bytes=0-0");
final int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
String contentType = connection.getContentType();
return (contentType != null && contentType.startsWith("image"));
}
if (responseCode != HttpURLConnection.HTTP_NOT_FOUND) {
Logger.printDebug(() -> "Unexpected response code: " + responseCode + " for url: " + imageUrl);
}
return false;
}).get();
Logger.printDebug(() -> "Verification took: " + (System.currentTimeMillis() - start) + "ms for image: " + imageUrl);
} catch (ExecutionException | InterruptedException ex) {
Logger.printInfo(() -> "Could not verify alt url: " + imageUrl, ex);
imageFileFound = false;
}
setQualityVerified(videoId, quality, imageFileFound);
return imageFileFound;
}
}
/**
* YouTube video thumbnail url, decoded into it's relevant parts.
*/
private static class DecodedThumbnailUrl {
/**
* YouTube thumbnail URL prefix. Can be '/vi/' or '/vi_webp/'
*/
private static final String YOUTUBE_THUMBNAIL_PREFIX = "https://i.ytimg.com/vi";
@Nullable
static DecodedThumbnailUrl decodeImageUrl(String url) {
final int videoIdStartIndex = url.indexOf('/', YOUTUBE_THUMBNAIL_PREFIX.length()) + 1;
if (videoIdStartIndex <= 0) return null;
final int videoIdEndIndex = url.indexOf('/', videoIdStartIndex);
if (videoIdEndIndex < 0) return null;
final int imageSizeStartIndex = videoIdEndIndex + 1;
final int imageSizeEndIndex = url.indexOf('.', imageSizeStartIndex);
if (imageSizeEndIndex < 0) return null;
int imageExtensionEndIndex = url.indexOf('?', imageSizeEndIndex);
if (imageExtensionEndIndex < 0) imageExtensionEndIndex = url.length();
return new DecodedThumbnailUrl(url, videoIdStartIndex, videoIdEndIndex,
imageSizeStartIndex, imageSizeEndIndex, imageExtensionEndIndex);
}
final String originalFullUrl;
/** Full usable url, but stripped of any tracking information. */
final String sanitizedUrl;
/** Url up to the video ID. */
final String urlPrefix;
final String videoId;
/** Quality, such as hq720 or sddefault. */
final String imageQuality;
/** JPG or WEBP */
final String imageExtension;
/** User view tracking parameters, only present on some images. */
final String viewTrackingParameters;
DecodedThumbnailUrl(String fullUrl, int videoIdStartIndex, int videoIdEndIndex,
int imageSizeStartIndex, int imageSizeEndIndex, int imageExtensionEndIndex) {
originalFullUrl = fullUrl;
sanitizedUrl = fullUrl.substring(0, imageExtensionEndIndex);
urlPrefix = fullUrl.substring(0, videoIdStartIndex);
videoId = fullUrl.substring(videoIdStartIndex, videoIdEndIndex);
imageQuality = fullUrl.substring(imageSizeStartIndex, imageSizeEndIndex);
imageExtension = fullUrl.substring(imageSizeEndIndex + 1, imageExtensionEndIndex);
viewTrackingParameters = (imageExtensionEndIndex == fullUrl.length())
? "" : fullUrl.substring(imageExtensionEndIndex);
}
/** @noinspection SameParameterValue */
String createStillsUrl(@NonNull ThumbnailQuality qualityToUse, boolean includeViewTracking) {
// Images could be upgraded to webp if they are not already, but this fails quite often,
// especially for new videos uploaded in the last hour.
// And even if alt webp images do exist, sometimes they can load much slower than the original jpg alt images.
// (as much as 4x slower has been observed, despite the alt webp image being a smaller file).
StringBuilder builder = new StringBuilder(originalFullUrl.length() + 2);
builder.append(urlPrefix);
builder.append(videoId).append('/');
builder.append(qualityToUse.getAltImageNameToUse());
builder.append('.').append(imageExtension);
if (includeViewTracking) {
builder.append(viewTrackingParameters);
}
return builder.toString();
}
}
}
| 30,876 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideAutoplayButtonPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideAutoplayButtonPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class HideAutoplayButtonPatch {
public static boolean isButtonShown() {
return !Settings.HIDE_AUTOPLAY_BUTTON.get();
}
}
| 285 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
DisableSuggestedVideoEndScreenPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/DisableSuggestedVideoEndScreenPatch.java | package app.revanced.integrations.youtube.patches;
import android.annotation.SuppressLint;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.youtube.settings.Settings;
/** @noinspection unused*/
public final class DisableSuggestedVideoEndScreenPatch {
@SuppressLint("StaticFieldLeak")
private static ImageView lastView;
public static void closeEndScreen(final ImageView imageView) {
if (!Settings.DISABLE_SUGGESTED_VIDEO_END_SCREEN.get()) return;
// Prevent adding the listener multiple times.
if (lastView == imageView) return;
lastView = imageView;
imageView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
if (imageView.isShown()) imageView.callOnClick();
});
}
}
| 952 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
DisableAutoCaptionsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/DisableAutoCaptionsPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class DisableAutoCaptionsPatch {
/**
* Used by injected code. Do not delete.
*/
public static boolean captionsButtonDisabled;
public static boolean autoCaptionsEnabled() {
return Settings.AUTO_CAPTIONS.get();
}
}
| 398 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
FixBackToExitGesturePatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/FixBackToExitGesturePatch.java | package app.revanced.integrations.youtube.patches;
import android.app.Activity;
import app.revanced.integrations.shared.Logger;
@SuppressWarnings("unused")
public class FixBackToExitGesturePatch {
/**
* State whether the scroll position reaches the top.
*/
public static boolean isTopView = false;
/**
* Handle the event after clicking the back button.
*
* @param activity The activity, the app is launched with to finish.
*/
public static void onBackPressed(Activity activity) {
if (!isTopView) return;
Logger.printDebug(() -> "Activity is closed");
activity.finish();
}
/**
* Handle the event when the homepage list of views is being scrolled.
*/
public static void onScrollingViews() {
Logger.printDebug(() -> "Views are scrolling");
isTopView = false;
}
/**
* Handle the event when the homepage list of views reached the top.
*/
public static void onTopView() {
Logger.printDebug(() -> "Scrolling reached the top");
isTopView = true;
}
}
| 1,102 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
AutoRepeatPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/AutoRepeatPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class AutoRepeatPatch {
//Used by app.revanced.patches.youtube.layout.autorepeat.patch.AutoRepeatPatch
public static boolean shouldAutoRepeat() {
return Settings.AUTO_REPEAT.get();
}
}
| 353 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
PlayerTypeHookPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/PlayerTypeHookPatch.java | package app.revanced.integrations.youtube.patches;
import androidx.annotation.Nullable;
import app.revanced.integrations.youtube.shared.PlayerType;
import app.revanced.integrations.youtube.shared.VideoState;
@SuppressWarnings("unused")
public class PlayerTypeHookPatch {
/**
* Injection point.
*/
public static void setPlayerType(@Nullable Enum<?> youTubePlayerType) {
if (youTubePlayerType == null) return;
PlayerType.setFromString(youTubePlayerType.name());
}
/**
* Injection point.
*/
public static void setVideoState(@Nullable Enum<?> youTubeVideoState) {
if (youTubeVideoState == null) return;
VideoState.setFromString(youTubeVideoState.name());
}
}
| 737 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
TabletMiniPlayerOverridePatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/TabletMiniPlayerOverridePatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class TabletMiniPlayerOverridePatch {
public static boolean getTabletMiniPlayerOverride(boolean original) {
if (Settings.USE_TABLET_MINIPLAYER.get())
return true;
return original;
}
}
| 369 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
RemoveViewerDiscretionDialogPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/RemoveViewerDiscretionDialogPatch.java | package app.revanced.integrations.youtube.patches;
import android.app.AlertDialog;
import app.revanced.integrations.youtube.settings.Settings;
/** @noinspection unused*/
public class RemoveViewerDiscretionDialogPatch {
public static void confirmDialog(AlertDialog dialog) {
if (!Settings.REMOVE_VIEWER_DISCRETION_DIALOG.get()) {
// Since the patch replaces the AlertDialog#show() method, we need to call the original method here.
dialog.show();
return;
}
final var button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setSoundEffectsEnabled(false);
button.performClick();
}
}
| 673 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
EnableTabletLayoutPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/EnableTabletLayoutPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class EnableTabletLayoutPatch {
public static boolean enableTabletLayout() {
return Settings.TABLET_LAYOUT.get();
}
}
| 288 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
VideoInformation.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/VideoInformation.java | package app.revanced.integrations.youtube.patches;
import androidx.annotation.NonNull;
import app.revanced.integrations.youtube.patches.playback.speed.RememberPlaybackSpeedPatch;
import app.revanced.integrations.youtube.shared.VideoState;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.Objects;
/**
* Hooking class for the current playing video.
* @noinspection unused
*/
public final class VideoInformation {
private static final float DEFAULT_YOUTUBE_PLAYBACK_SPEED = 1.0f;
private static final String SEEK_METHOD_NAME = "seekTo";
/**
* Prefix present in all Short player parameters signature.
*/
private static final String SHORTS_PLAYER_PARAMETERS = "8AEB";
private static WeakReference<Object> playerControllerRef;
private static Method seekMethod;
@NonNull
private static String videoId = "";
private static long videoLength = 0;
private static long videoTime = -1;
@NonNull
private static volatile String playerResponseVideoId = "";
private static volatile boolean playerResponseVideoIdIsShort;
private static volatile boolean videoIdIsShort;
/**
* The current playback speed
*/
private static float playbackSpeed = DEFAULT_YOUTUBE_PLAYBACK_SPEED;
/**
* Injection point.
*
* @param playerController player controller object.
*/
public static void initialize(@NonNull Object playerController) {
try {
playerControllerRef = new WeakReference<>(Objects.requireNonNull(playerController));
videoTime = -1;
videoLength = 0;
playbackSpeed = DEFAULT_YOUTUBE_PLAYBACK_SPEED;
seekMethod = playerController.getClass().getMethod(SEEK_METHOD_NAME, Long.TYPE);
seekMethod.setAccessible(true);
} catch (Exception ex) {
Logger.printException(() -> "Failed to initialize", ex);
}
}
/**
* Injection point.
*
* @param newlyLoadedVideoId id of the current video
*/
public static void setVideoId(@NonNull String newlyLoadedVideoId) {
if (!videoId.equals(newlyLoadedVideoId)) {
Logger.printDebug(() -> "New video id: " + newlyLoadedVideoId);
videoId = newlyLoadedVideoId;
}
}
/**
* @return If the player parameters are for a Short.
*/
public static boolean playerParametersAreShort(@NonNull String parameters) {
return parameters.startsWith(SHORTS_PLAYER_PARAMETERS);
}
/**
* Injection point.
*/
public static String newPlayerResponseSignature(@NonNull String signature, boolean isShortAndOpeningOrPlaying) {
final boolean isShort = playerParametersAreShort(signature);
playerResponseVideoIdIsShort = isShort;
if (!isShort || isShortAndOpeningOrPlaying) {
if (videoIdIsShort != isShort) {
videoIdIsShort = isShort;
Logger.printDebug(() -> "videoIdIsShort: " + isShort);
}
}
return signature; // Return the original value since we are observing and not modifying.
}
/**
* Injection point. Called off the main thread.
*
* @param videoId The id of the last video loaded.
*/
public static void setPlayerResponseVideoId(@NonNull String videoId, boolean isShortAndOpeningOrPlaying) {
if (!playerResponseVideoId.equals(videoId)) {
Logger.printDebug(() -> "New player response video id: " + videoId);
playerResponseVideoId = videoId;
}
}
/**
* Injection point.
* Called when user selects a playback speed.
*
* @param userSelectedPlaybackSpeed The playback speed the user selected
*/
public static void userSelectedPlaybackSpeed(float userSelectedPlaybackSpeed) {
Logger.printDebug(() -> "User selected playback speed: " + userSelectedPlaybackSpeed);
playbackSpeed = userSelectedPlaybackSpeed;
}
/**
* Overrides the current playback speed.
* <p>
* <b> Used exclusively by {@link RememberPlaybackSpeedPatch} </b>
*/
public static void overridePlaybackSpeed(float speedOverride) {
if (playbackSpeed != speedOverride) {
Logger.printDebug(() -> "Overriding playback speed to: " + speedOverride);
playbackSpeed = speedOverride;
}
}
/**
* Injection point.
*
* @param length The length of the video in milliseconds.
*/
public static void setVideoLength(final long length) {
if (videoLength != length) {
Logger.printDebug(() -> "Current video length: " + length);
videoLength = length;
}
}
/**
* Injection point.
* Called on the main thread every 1000ms.
*
* @param currentPlaybackTime The current playback time of the video in milliseconds.
*/
public static void setVideoTime(final long currentPlaybackTime) {
videoTime = currentPlaybackTime;
}
/**
* Seek on the current video.
* Does not function for playback of Shorts.
* <p>
* Caution: If called from a videoTimeHook() callback,
* this will cause a recursive call into the same videoTimeHook() callback.
*
* @param seekTime The seekTime to seek the video to.
* @return true if the seek was successful.
*/
public static boolean seekTo(final long seekTime) {
Utils.verifyOnMainThread();
try {
final long videoTime = getVideoTime();
final long videoLength = getVideoLength();
// Prevent issues such as play/ pause button or autoplay not working.
final long adjustedSeekTime = Math.min(seekTime, videoLength - 250);
if (videoTime <= seekTime && videoTime >= adjustedSeekTime) {
// Both the current video time and the seekTo are in the last 250ms of the video.
// Ignore this seek call, otherwise if a video ends with multiple closely timed segments
// then seeking here can create an infinite loop of skip attempts.
Logger.printDebug(() -> "Ignoring seekTo call as video playback is almost finished. "
+ " videoTime: " + videoTime + " videoLength: " + videoLength + " seekTo: " + seekTime);
return false;
}
Logger.printDebug(() -> "Seeking to " + adjustedSeekTime);
//noinspection DataFlowIssue
return (Boolean) seekMethod.invoke(playerControllerRef.get(), adjustedSeekTime);
} catch (Exception ex) {
Logger.printException(() -> "Failed to seek", ex);
return false;
}
}
/** @noinspection UnusedReturnValue*/
public static boolean seekToRelative(long millisecondsRelative) {
return seekTo(videoTime + millisecondsRelative);
}
/**
* Id of the last video opened. Includes Shorts.
*
* @return The id of the video, or an empty string if no videos have been opened yet.
*/
@NonNull
public static String getVideoId() {
return videoId;
}
/**
* Differs from {@link #videoId} as this is the video id for the
* last player response received, which may not be the last video opened.
* <p>
* If Shorts are loading the background, this commonly will be
* different from the Short that is currently on screen.
* <p>
* For most use cases, you should instead use {@link #getVideoId()}.
*
* @return The id of the last video loaded, or an empty string if no videos have been loaded yet.
*/
@NonNull
public static String getPlayerResponseVideoId() {
return playerResponseVideoId;
}
/**
* @return If the last player response video id was a Short.
* Includes Shorts shelf items appearing in the feed that are not opened.
* @see #lastVideoIdIsShort()
*/
public static boolean lastPlayerResponseIsShort() {
return playerResponseVideoIdIsShort;
}
/**
* @return If the last player response video id _that was opened_ was a Short.
*/
public static boolean lastVideoIdIsShort() {
return videoIdIsShort;
}
/**
* @return The current playback speed.
*/
public static float getPlaybackSpeed() {
return playbackSpeed;
}
/**
* Length of the current video playing. Includes Shorts.
*
* @return The length of the video in milliseconds.
* If the video is not yet loaded, or if the video is playing in the background with no video visible,
* then this returns zero.
*/
public static long getVideoLength() {
return videoLength;
}
/**
* Playback time of the current video playing. Includes Shorts.
* <p>
* Value will lag behind the actual playback time by a variable amount based on the playback speed.
* <p>
* If playback speed is 2.0x, this value may be up to 2000ms behind the actual playback time.
* If playback speed is 1.0x, this value may be up to 1000ms behind the actual playback time.
* If playback speed is 0.5x, this value may be up to 500ms behind the actual playback time.
* Etc.
*
* @return The time of the video in milliseconds. -1 if not set yet.
*/
public static long getVideoTime() {
return videoTime;
}
/**
* @return If the playback is at the end of the video.
* <p>
* If video is playing in the background with no video visible,
* this always returns false (even if the video is actually at the end).
* <p>
* This is equivalent to checking for {@link VideoState#ENDED},
* but can give a more up-to-date result for code calling from some hooks.
*
* @see VideoState
*/
public static boolean isAtEndOfVideo() {
return videoTime >= videoLength && videoLength > 0;
}
}
| 10,072 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideCastButtonPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideCastButtonPatch.java | package app.revanced.integrations.youtube.patches;
import android.view.View;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class HideCastButtonPatch {
// Used by app.revanced.patches.youtube.layout.castbutton.patch.HideCastButonPatch
public static int getCastButtonOverrideV2(int original) {
return Settings.HIDE_CAST_BUTTON.get() ? View.GONE : original;
}
}
| 432 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
DisableRollingNumberAnimationsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/DisableRollingNumberAnimationsPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class DisableRollingNumberAnimationsPatch {
/**
* Injection point.
*/
public static boolean disableRollingNumberAnimations() {
return Settings.DISABLE_ROLLING_NUMBER_ANIMATIONS.get();
}
}
| 366 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideFloatingMicrophoneButtonPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideFloatingMicrophoneButtonPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class HideFloatingMicrophoneButtonPatch {
public static boolean hideFloatingMicrophoneButton(final boolean original) {
return Settings.HIDE_FLOATING_MICROPHONE_BUTTON.get() || original;
}
}
| 360 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
DownloadsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/DownloadsPatch.java | package app.revanced.integrations.youtube.patches;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import androidx.annotation.NonNull;
import java.lang.ref.WeakReference;
import java.util.Objects;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.StringRef;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class DownloadsPatch {
private static WeakReference<Activity> activityRef = new WeakReference<>(null);
/**
* Injection point.
*/
public static void activityCreated(Activity mainActivity) {
activityRef = new WeakReference<>(mainActivity);
}
/**
* Injection point.
*
* Called from the in app download hook,
* for both the player action button (below the video)
* and the 'Download video' flyout option for feed videos.
*
* Appears to always be called from the main thread.
*/
public static boolean inAppDownloadButtonOnClick(@NonNull String videoId) {
try {
if (!Settings.EXTERNAL_DOWNLOADER_ACTION_BUTTON.get()) {
return false;
}
// If possible, use the main activity as the context.
// Otherwise fall back on using the application context.
Context context = activityRef.get();
boolean isActivityContext = true;
if (context == null) {
// Utils context is the application context, and not an activity context.
context = Utils.getContext();
isActivityContext = false;
}
launchExternalDownloader(videoId, context, isActivityContext);
return true;
} catch (Exception ex) {
Logger.printException(() -> "inAppDownloadButtonOnClick failure", ex);
}
return false;
}
/**
* @param isActivityContext If the context parameter is for an Activity. If this is false, then
* the downloader is opened as a new task (which forces YT to minimize).
*/
public static void launchExternalDownloader(@NonNull String videoId,
@NonNull Context context, boolean isActivityContext) {
try {
Objects.requireNonNull(videoId);
Logger.printDebug(() -> "Launching external downloader with context: " + context);
// Trim string to avoid any accidental whitespace.
var downloaderPackageName = Settings.EXTERNAL_DOWNLOADER_PACKAGE_NAME.get().trim();
boolean packageEnabled = false;
try {
packageEnabled = context.getPackageManager().getApplicationInfo(downloaderPackageName, 0).enabled;
} catch (PackageManager.NameNotFoundException error) {
Logger.printDebug(() -> "External downloader could not be found: " + error);
}
// If the package is not installed, show the toast
if (!packageEnabled) {
Utils.showToastLong(StringRef.str("revanced_external_downloader_not_installed_warning", downloaderPackageName));
return;
}
String content = "https://youtu.be/" + videoId;
Intent intent = new Intent("android.intent.action.SEND");
intent.setType("text/plain");
intent.setPackage(downloaderPackageName);
intent.putExtra("android.intent.extra.TEXT", content);
if (!isActivityContext) {
Logger.printDebug(() -> "Using new task intent");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
} catch (Exception ex) {
Logger.printException(() -> "launchExternalDownloader failure", ex);
}
}
}
| 3,990 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
DisablePreciseSeekingGesturePatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/DisablePreciseSeekingGesturePatch.java | package app.revanced.integrations.youtube.patches;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public final class DisablePreciseSeekingGesturePatch {
/**
* Disables the gesture that is used to seek precisely.
* @param tracker The velocity tracker that is used to determine the gesture.
* @param event The motion event that is used to determine the gesture.
*/
public static void disableGesture(VelocityTracker tracker, MotionEvent event) {
if (Settings.DISABLE_PRECISE_SEEKING_GESTURE.get()) return;
tracker.addMovement(event);
}
}
| 698 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideAlbumCardsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideAlbumCardsPatch.java | package app.revanced.integrations.youtube.patches;
import android.view.View;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.shared.Utils;
@SuppressWarnings("unused")
public class HideAlbumCardsPatch {
public static void hideAlbumCard(View view) {
if (!Settings.HIDE_ALBUM_CARDS.get()) return;
Utils.hideViewByLayoutParams(view);
}
} | 405 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ReturnYouTubeDislikePatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/ReturnYouTubeDislikePatch.java | package app.revanced.integrations.youtube.patches;
import android.graphics.Rect;
import android.graphics.drawable.ShapeDrawable;
import android.os.Build;
import android.text.*;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import app.revanced.integrations.youtube.patches.components.ReturnYouTubeDislikeFilterPatch;
import app.revanced.integrations.youtube.patches.spoof.SpoofAppVersionPatch;
import app.revanced.integrations.youtube.returnyoutubedislike.ReturnYouTubeDislike;
import app.revanced.integrations.youtube.returnyoutubedislike.requests.ReturnYouTubeDislikeApi;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.shared.PlayerType;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static app.revanced.integrations.youtube.returnyoutubedislike.ReturnYouTubeDislike.Vote;
/**
* Handles all interaction of UI patch components.
*
* Known limitation:
* The implementation of Shorts litho requires blocking the loading the first Short until RYD has completed.
* This is because it modifies the dislikes text synchronously, and if the RYD fetch has
* not completed yet then the UI will be temporarily frozen.
*
* A (yet to be implemented) solution that fixes this problem. Any one of:
* - Modify patch to hook onto the Shorts Litho TextView, and update the dislikes text asynchronously.
* - Find a way to force Litho to rebuild it's component tree,
* and use that hook to force the shorts dislikes to update after the fetch is completed.
* - Hook into the dislikes button image view, and replace the dislikes thumb down image with a
* generated image of the number of dislikes, then update the image asynchronously. This Could
* also be used for the regular video player to give a better UI layout and completely remove
* the need for the Rolling Number patches.
*/
@SuppressWarnings("unused")
public class ReturnYouTubeDislikePatch {
public static final boolean IS_SPOOFING_TO_NON_LITHO_SHORTS_PLAYER =
SpoofAppVersionPatch.isSpoofingToLessThan("18.34.00");
/**
* RYD data for the current video on screen.
*/
@Nullable
private static volatile ReturnYouTubeDislike currentVideoData;
/**
* The last litho based Shorts loaded.
* May be the same value as {@link #currentVideoData}, but usually is the next short to swipe to.
*/
@Nullable
private static volatile ReturnYouTubeDislike lastLithoShortsVideoData;
/**
* Because the litho Shorts spans are created after {@link ReturnYouTubeDislikeFilterPatch}
* detects the video ids, after the user votes the litho will update
* but {@link #lastLithoShortsVideoData} is not the correct data to use.
* If this is true, then instead use {@link #currentVideoData}.
*/
private static volatile boolean lithoShortsShouldUseCurrentData;
/**
* Last video id prefetched. Field is to prevent prefetching the same video id multiple times in a row.
*/
@Nullable
private static volatile String lastPrefetchedVideoId;
public static void onRYDStatusChange(boolean rydEnabled) {
ReturnYouTubeDislikeApi.resetRateLimits();
// Must remove all values to protect against using stale data
// if the user enables RYD while a video is on screen.
clearData();
}
private static void clearData() {
currentVideoData = null;
lastLithoShortsVideoData = null;
lithoShortsShouldUseCurrentData = false;
// Rolling number text should not be cleared,
// as it's used if incognito Short is opened/closed
// while a regular video is on screen.
}
//
// 17.x non litho regular video player.
//
/**
* Resource identifier of old UI dislike button.
*/
private static final int OLD_UI_DISLIKE_BUTTON_RESOURCE_ID
= Utils.getResourceIdentifier("dislike_button", "id");
/**
* Dislikes text label used by old UI.
*/
@NonNull
private static WeakReference<TextView> oldUITextViewRef = new WeakReference<>(null);
/**
* Original old UI 'Dislikes' text before patch modifications.
* Required to reset the dislikes when changing videos and RYD is not available.
* Set only once during the first load.
*/
private static Spanned oldUIOriginalSpan;
/**
* Replacement span that contains dislike value. Used by {@link #oldUiTextWatcher}.
*/
@Nullable
private static Spanned oldUIReplacementSpan;
/**
* Old UI dislikes can be set multiple times by YouTube.
* To prevent reverting changes made here, this listener overrides any future changes YouTube makes.
*/
private static final TextWatcher oldUiTextWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
if (oldUIReplacementSpan == null || oldUIReplacementSpan.toString().equals(s.toString())) {
return;
}
s.replace(0, s.length(), oldUIReplacementSpan); // Causes a recursive call back into this listener
}
};
private static void updateOldUIDislikesTextView() {
ReturnYouTubeDislike videoData = currentVideoData;
if (videoData == null) {
return;
}
TextView oldUITextView = oldUITextViewRef.get();
if (oldUITextView == null) {
return;
}
oldUIReplacementSpan = videoData.getDislikesSpanForRegularVideo(oldUIOriginalSpan, false, false);
if (!oldUIReplacementSpan.equals(oldUITextView.getText())) {
oldUITextView.setText(oldUIReplacementSpan);
}
}
/**
* Injection point. Called on main thread.
*
* Used when spoofing to 16.x and 17.x versions.
*/
public static void setOldUILayoutDislikes(int buttonViewResourceId, @Nullable TextView textView) {
try {
if (!Settings.RYD_ENABLED.get()
|| buttonViewResourceId != OLD_UI_DISLIKE_BUTTON_RESOURCE_ID
|| textView == null) {
return;
}
Logger.printDebug(() -> "setOldUILayoutDislikes");
if (oldUIOriginalSpan == null) {
// Use value of the first instance, as it appears TextViews can be recycled
// and might contain dislikes previously added by the patch.
oldUIOriginalSpan = (Spanned) textView.getText();
}
oldUITextViewRef = new WeakReference<>(textView);
// No way to check if a listener is already attached, so remove and add again.
textView.removeTextChangedListener(oldUiTextWatcher);
textView.addTextChangedListener(oldUiTextWatcher);
updateOldUIDislikesTextView();
} catch (Exception ex) {
Logger.printException(() -> "setOldUILayoutDislikes failure", ex);
}
}
//
// Litho player for both regular videos and Shorts.
//
/**
* Injection point.
*
* For Litho segmented buttons and Litho Shorts player.
*/
@NonNull
public static CharSequence onLithoTextLoaded(@NonNull Object conversionContext,
@NonNull CharSequence original) {
return onLithoTextLoaded(conversionContext, original, false);
}
/**
* Called when a litho text component is initially created,
* and also when a Span is later reused again (such as scrolling off/on screen).
*
* This method is sometimes called on the main thread, but it usually is called _off_ the main thread.
* This method can be called multiple times for the same UI element (including after dislikes was added).
*
* @param original Original char sequence was created or reused by Litho.
* @param isRollingNumber If the span is for a Rolling Number.
* @return The original char sequence (if nothing should change), or a replacement char sequence that contains dislikes.
*/
@NonNull
private static CharSequence onLithoTextLoaded(@NonNull Object conversionContext,
@NonNull CharSequence original,
boolean isRollingNumber) {
try {
if (!Settings.RYD_ENABLED.get()) {
return original;
}
String conversionContextString = conversionContext.toString();
final CharSequence replacement;
if (conversionContextString.contains("|segmented_like_dislike_button.eml|")) {
// Regular video.
ReturnYouTubeDislike videoData = currentVideoData;
if (videoData == null) {
return original; // User enabled RYD while a video was on screen.
}
if (!(original instanceof Spanned)) {
original = new SpannableString(original);
}
replacement = videoData.getDislikesSpanForRegularVideo((Spanned) original,
true, isRollingNumber);
} else if (!isRollingNumber && conversionContextString.contains("|shorts_dislike_button.eml|")) {
// Litho Shorts player.
if (!Settings.RYD_SHORTS.get()) {
// Must clear the current video here, otherwise if the user opens a regular video
// then opens a litho short (while keeping the regular video on screen), then closes the short,
// the original video may show the incorrect dislike value.
clearData();
return original;
}
ReturnYouTubeDislike videoData = lastLithoShortsVideoData;
if (videoData == null) {
// The Shorts litho video id filter did not detect the video id.
// This is normal in incognito mode, but otherwise is abnormal.
Logger.printDebug(() -> "Cannot modify Shorts litho span, data is null");
return original;
}
// Use the correct dislikes data after voting.
if (lithoShortsShouldUseCurrentData) {
lithoShortsShouldUseCurrentData = false;
videoData = currentVideoData;
if (videoData == null) {
Logger.printException(() -> "currentVideoData is null"); // Should never happen
return original;
}
Logger.printDebug(() -> "Using current video data for litho span");
}
replacement = videoData.getDislikeSpanForShort((Spanned) original);
} else {
return original;
}
return replacement;
} catch (Exception ex) {
Logger.printException(() -> "onLithoTextLoaded failure", ex);
}
return original;
}
//
// Rolling Number
//
/**
* Current regular video rolling number text, if rolling number is in use.
* This is saved to a field as it's used in every draw() call.
*/
@Nullable
private static volatile CharSequence rollingNumberSpan;
/**
* Injection point.
*/
public static String onRollingNumberLoaded(@NonNull Object conversionContext,
@NonNull String original) {
try {
CharSequence replacement = onLithoTextLoaded(conversionContext, original, true);
String replacementString = replacement.toString();
if (!replacementString.equals(original)) {
rollingNumberSpan = replacement;
return replacementString;
} // Else, the text was not a likes count but instead the view count or something else.
} catch (Exception ex) {
Logger.printException(() -> "onRollingNumberLoaded failure", ex);
}
return original;
}
/**
* Injection point.
*
* Called for all usage of Rolling Number.
* Modifies the measured String text width to include the left separator and padding, if needed.
*/
public static float onRollingNumberMeasured(String text, float measuredTextWidth) {
try {
if (Settings.RYD_ENABLED.get()) {
if (ReturnYouTubeDislike.isPreviouslyCreatedSegmentedSpan(text)) {
// +1 pixel is needed for some foreign languages that measure
// the text different from what is used for layout (Greek in particular).
// Probably a bug in Android, but who knows.
// Single line mode is also used as an additional fix for this issue.
if (Settings.RYD_COMPACT_LAYOUT.get()) {
return measuredTextWidth + 1;
}
return measuredTextWidth + 1
+ ReturnYouTubeDislike.leftSeparatorBounds.right
+ ReturnYouTubeDislike.leftSeparatorShapePaddingPixels;
}
}
} catch (Exception ex) {
Logger.printException(() -> "onRollingNumberMeasured failure", ex);
}
return measuredTextWidth;
}
/**
* Add Rolling Number text view modifications.
*/
private static void addRollingNumberPatchChanges(TextView view) {
// YouTube Rolling Numbers do not use compound drawables or drawable padding.
if (view.getCompoundDrawablePadding() == 0) {
Logger.printDebug(() -> "Adding rolling number TextView changes");
view.setCompoundDrawablePadding(ReturnYouTubeDislike.leftSeparatorShapePaddingPixels);
ShapeDrawable separator = ReturnYouTubeDislike.getLeftSeparatorDrawable();
if (Utils.isRightToLeftTextLayout()) {
view.setCompoundDrawables(null, null, separator, null);
} else {
view.setCompoundDrawables(separator, null, null, null);
}
// Disliking can cause the span to grow in size, which is ok and is laid out correctly,
// but if the user then removes their dislike the layout will not adjust to the new shorter width.
// Use a center alignment to take up any extra space.
view.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
// Single line mode does not clip words if the span is larger than the view bounds.
// The styled span applied to the view should always have the same bounds,
// but use this feature just in case the measurements are somehow off by a few pixels.
view.setSingleLine(true);
}
}
/**
* Remove Rolling Number text view modifications made by this patch.
* Required as it appears text views can be reused for other rolling numbers (view count, upload time, etc).
*/
private static void removeRollingNumberPatchChanges(TextView view) {
if (view.getCompoundDrawablePadding() != 0) {
Logger.printDebug(() -> "Removing rolling number TextView changes");
view.setCompoundDrawablePadding(0);
view.setCompoundDrawables(null, null, null, null);
view.setTextAlignment(View.TEXT_ALIGNMENT_GRAVITY); // Default alignment
view.setSingleLine(false);
}
}
/**
* Injection point.
*/
public static CharSequence updateRollingNumber(TextView view, CharSequence original) {
try {
if (!Settings.RYD_ENABLED.get()) {
removeRollingNumberPatchChanges(view);
return original;
}
// Called for all instances of RollingNumber, so must check if text is for a dislikes.
// Text will already have the correct content but it's missing the drawable separators.
if (!ReturnYouTubeDislike.isPreviouslyCreatedSegmentedSpan(original.toString())) {
// The text is the video view count, upload time, or some other text.
removeRollingNumberPatchChanges(view);
return original;
}
CharSequence replacement = rollingNumberSpan;
if (replacement == null) {
// User enabled RYD while a video was open,
// or user opened/closed a Short while a regular video was opened.
Logger.printDebug(() -> "Cannot update rolling number (field is null");
removeRollingNumberPatchChanges(view);
return original;
}
if (Settings.RYD_COMPACT_LAYOUT.get()) {
removeRollingNumberPatchChanges(view);
} else {
addRollingNumberPatchChanges(view);
}
// Remove any padding set by Rolling Number.
view.setPadding(0, 0, 0, 0);
// When displaying dislikes, the rolling animation is not visually correct
// and the dislikes always animate (even though the dislike count has not changed).
// The animation is caused by an image span attached to the span,
// and using only the modified segmented span prevents the animation from showing.
return replacement;
} catch (Exception ex) {
Logger.printException(() -> "updateRollingNumber failure", ex);
return original;
}
}
//
// Non litho Shorts player.
//
/**
* Replacement text to use for "Dislikes" while RYD is fetching.
*/
private static final Spannable SHORTS_LOADING_SPAN = new SpannableString("-");
/**
* Dislikes TextViews used by Shorts.
*
* Multiple TextViews are loaded at once (for the prior and next videos to swipe to).
* Keep track of all of them, and later pick out the correct one based on their on screen position.
*/
private static final List<WeakReference<TextView>> shortsTextViewRefs = new ArrayList<>();
private static void clearRemovedShortsTextViews() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // YouTube requires Android N or greater
shortsTextViewRefs.removeIf(ref -> ref.get() == null);
}
}
/**
* Injection point. Called when a Shorts dislike is updated. Always on main thread.
* Handles update asynchronously, otherwise Shorts video will be frozen while the UI thread is blocked.
*
* @return if RYD is enabled and the TextView was updated.
*/
public static boolean setShortsDislikes(@NonNull View likeDislikeView) {
try {
if (!Settings.RYD_ENABLED.get()) {
return false;
}
if (!Settings.RYD_SHORTS.get()) {
// Must clear the data here, in case a new video was loaded while PlayerType
// suggested the video was not a short (can happen when spoofing to an old app version).
clearData();
return false;
}
Logger.printDebug(() -> "setShortsDislikes");
TextView textView = (TextView) likeDislikeView;
textView.setText(SHORTS_LOADING_SPAN); // Change 'Dislike' text to the loading text.
shortsTextViewRefs.add(new WeakReference<>(textView));
if (likeDislikeView.isSelected() && isShortTextViewOnScreen(textView)) {
Logger.printDebug(() -> "Shorts dislike is already selected");
ReturnYouTubeDislike videoData = currentVideoData;
if (videoData != null) videoData.setUserVote(Vote.DISLIKE);
}
// For the first short played, the Shorts dislike hook is called after the video id hook.
// But for most other times this hook is called before the video id (which is not ideal).
// Must update the TextViews here, and also after the videoId changes.
updateOnScreenShortsTextViews(false);
return true;
} catch (Exception ex) {
Logger.printException(() -> "setShortsDislikes failure", ex);
return false;
}
}
/**
* @param forceUpdate if false, then only update the 'loading text views.
* If true, update all on screen text views.
*/
private static void updateOnScreenShortsTextViews(boolean forceUpdate) {
try {
clearRemovedShortsTextViews();
if (shortsTextViewRefs.isEmpty()) {
return;
}
ReturnYouTubeDislike videoData = currentVideoData;
if (videoData == null) {
return;
}
Logger.printDebug(() -> "updateShortsTextViews");
Runnable update = () -> {
Spanned shortsDislikesSpan = videoData.getDislikeSpanForShort(SHORTS_LOADING_SPAN);
Utils.runOnMainThreadNowOrLater(() -> {
String videoId = videoData.getVideoId();
if (!videoId.equals(VideoInformation.getVideoId())) {
// User swiped to new video before fetch completed
Logger.printDebug(() -> "Ignoring stale dislikes data for short: " + videoId);
return;
}
// Update text views that appear to be visible on screen.
// Only 1 will be the actual textview for the current Short,
// but discarded and not yet garbage collected views can remain.
// So must set the dislike span on all views that match.
for (WeakReference<TextView> textViewRef : shortsTextViewRefs) {
TextView textView = textViewRef.get();
if (textView == null) {
continue;
}
if (isShortTextViewOnScreen(textView)
&& (forceUpdate || textView.getText().toString().equals(SHORTS_LOADING_SPAN.toString()))) {
Logger.printDebug(() -> "Setting Shorts TextView to: " + shortsDislikesSpan);
textView.setText(shortsDislikesSpan);
}
}
});
};
if (videoData.fetchCompleted()) {
update.run(); // Network call is completed, no need to wait on background thread.
} else {
Utils.runOnBackgroundThread(update);
}
} catch (Exception ex) {
Logger.printException(() -> "updateOnScreenShortsTextViews failure", ex);
}
}
/**
* Check if a view is within the screen bounds.
*/
private static boolean isShortTextViewOnScreen(@NonNull View view) {
final int[] location = new int[2];
view.getLocationInWindow(location);
if (location[0] <= 0 && location[1] <= 0) { // Lower bound
return false;
}
Rect windowRect = new Rect();
view.getWindowVisibleDisplayFrame(windowRect); // Upper bound
return location[0] < windowRect.width() && location[1] < windowRect.height();
}
//
// Video Id and voting hooks (all players).
//
private static volatile boolean lastPlayerResponseWasShort;
/**
* Injection point. Uses 'playback response' video id hook to preload RYD.
*/
public static void preloadVideoId(@NonNull String videoId, boolean isShortAndOpeningOrPlaying) {
try {
if (!Settings.RYD_ENABLED.get()) {
return;
}
if (videoId.equals(lastPrefetchedVideoId)) {
return;
}
final boolean videoIdIsShort = VideoInformation.lastPlayerResponseIsShort();
// Shorts shelf in home and subscription feed causes player response hook to be called,
// and the 'is opening/playing' parameter will be false.
// This hook will be called again when the Short is actually opened.
if (videoIdIsShort && (!isShortAndOpeningOrPlaying || !Settings.RYD_SHORTS.get())) {
return;
}
final boolean waitForFetchToComplete = !IS_SPOOFING_TO_NON_LITHO_SHORTS_PLAYER
&& videoIdIsShort && !lastPlayerResponseWasShort;
Logger.printDebug(() -> "Prefetching RYD for video: " + videoId);
ReturnYouTubeDislike fetch = ReturnYouTubeDislike.getFetchForVideoId(videoId);
if (waitForFetchToComplete && !fetch.fetchCompleted()) {
// This call is off the main thread, so wait until the RYD fetch completely finishes,
// otherwise if this returns before the fetch completes then the UI can
// become frozen when the main thread tries to modify the litho Shorts dislikes and
// it must wait for the fetch.
// Only need to do this for the first Short opened, as the next Short to swipe to
// are preloaded in the background.
//
// If an asynchronous litho Shorts solution is found, then this blocking call should be removed.
Logger.printDebug(() -> "Waiting for prefetch to complete: " + videoId);
fetch.getFetchData(20000); // Any arbitrarily large max wait time.
}
// Set the fields after the fetch completes, so any concurrent calls will also wait.
lastPlayerResponseWasShort = videoIdIsShort;
lastPrefetchedVideoId = videoId;
} catch (Exception ex) {
Logger.printException(() -> "preloadVideoId failure", ex);
}
}
/**
* Injection point. Uses 'current playing' video id hook. Always called on main thread.
*/
public static void newVideoLoaded(@NonNull String videoId) {
try {
if (!Settings.RYD_ENABLED.get()) return;
Objects.requireNonNull(videoId);
PlayerType currentPlayerType = PlayerType.getCurrent();
final boolean isNoneHiddenOrSlidingMinimized = currentPlayerType.isNoneHiddenOrSlidingMinimized();
if (isNoneHiddenOrSlidingMinimized && !Settings.RYD_SHORTS.get()) {
// Must clear here, otherwise the wrong data can be used for a minimized regular video.
clearData();
return;
}
if (videoIdIsSame(currentVideoData, videoId)) {
return;
}
Logger.printDebug(() -> "New video id: " + videoId + " playerType: " + currentPlayerType);
ReturnYouTubeDislike data = ReturnYouTubeDislike.getFetchForVideoId(videoId);
// Pre-emptively set the data to short status.
// Required to prevent Shorts data from being used on a minimized video in incognito mode.
if (isNoneHiddenOrSlidingMinimized) {
data.setVideoIdIsShort(true);
}
currentVideoData = data;
// Current video id hook can be called out of order with the non litho Shorts text view hook.
// Must manually update again here.
if (isNoneHiddenOrSlidingMinimized) {
updateOnScreenShortsTextViews(true);
}
} catch (Exception ex) {
Logger.printException(() -> "newVideoLoaded failure", ex);
}
}
public static void setLastLithoShortsVideoId(@Nullable String videoId) {
if (videoIdIsSame(lastLithoShortsVideoData, videoId)) {
return;
}
if (videoId == null) {
// Litho filter did not detect the video id. App is in incognito mode,
// or the proto buffer structure was changed and the video id is no longer present.
// Must clear both currently playing and last litho data otherwise the
// next regular video may use the wrong data.
Logger.printDebug(() -> "Litho filter did not find any video ids");
clearData();
return;
}
Logger.printDebug(() -> "New litho Shorts video id: " + videoId);
ReturnYouTubeDislike videoData = ReturnYouTubeDislike.getFetchForVideoId(videoId);
videoData.setVideoIdIsShort(true);
lastLithoShortsVideoData = videoData;
lithoShortsShouldUseCurrentData = false;
}
private static boolean videoIdIsSame(@Nullable ReturnYouTubeDislike fetch, @Nullable String videoId) {
return (fetch == null && videoId == null)
|| (fetch != null && fetch.getVideoId().equals(videoId));
}
/**
* Injection point.
*
* Called when the user likes or dislikes.
*
* @param vote int that matches {@link Vote#value}
*/
public static void sendVote(int vote) {
try {
if (!Settings.RYD_ENABLED.get()) {
return;
}
final boolean isNoneHiddenOrMinimized = PlayerType.getCurrent().isNoneHiddenOrMinimized();
if (isNoneHiddenOrMinimized && !Settings.RYD_SHORTS.get()) {
return;
}
ReturnYouTubeDislike videoData = currentVideoData;
if (videoData == null) {
Logger.printDebug(() -> "Cannot send vote, as current video data is null");
return; // User enabled RYD while a regular video was minimized.
}
for (Vote v : Vote.values()) {
if (v.value == vote) {
videoData.sendVote(v);
if (isNoneHiddenOrMinimized) {
if (lastLithoShortsVideoData != null) {
lithoShortsShouldUseCurrentData = true;
}
updateOldUIDislikesTextView();
}
return;
}
}
Logger.printException(() -> "Unknown vote type: " + vote);
} catch (Exception ex) {
Logger.printException(() -> "sendVote failure", ex);
}
}
}
| 30,631 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HDRAutoBrightnessPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HDRAutoBrightnessPatch.java | package app.revanced.integrations.youtube.patches;
import android.view.WindowManager;
import app.revanced.integrations.youtube.settings.Settings;
import app.revanced.integrations.youtube.swipecontrols.SwipeControlsHostActivity;
/**
* Patch class for 'hdr-auto-brightness' patch.
*
* Edit: This patch no longer does anything, as YT already uses BRIGHTNESS_OVERRIDE_NONE
* as the default brightness level. The hooked code was also removed from YT 19.09+ as well.
*/
@Deprecated
@SuppressWarnings("unused")
public class HDRAutoBrightnessPatch {
/**
* get brightness override for HDR brightness
*
* @param original brightness youtube would normally set
* @return brightness to set on HRD video
*/
public static float getHDRBrightness(float original) {
// do nothing if disabled
if (!Settings.HDR_AUTO_BRIGHTNESS.get()) {
return original;
}
// override with brightness set by swipe-controls
// only when swipe-controls is active and has overridden the brightness
final SwipeControlsHostActivity swipeControlsHost = SwipeControlsHostActivity.getCurrentHost().get();
if (swipeControlsHost != null
&& swipeControlsHost.getScreen() != null
&& swipeControlsHost.getConfig().getEnableBrightnessControl()
&& !swipeControlsHost.getScreen().isDefaultBrightness()) {
return swipeControlsHost.getScreen().getRawScreenBrightness();
}
// otherwise, set the brightness to auto
return WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
}
}
| 1,622 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
DisableFullscreenAmbientModePatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/DisableFullscreenAmbientModePatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
/** @noinspection unused*/
public final class DisableFullscreenAmbientModePatch {
public static boolean enableFullScreenAmbientMode() {
return !Settings.DISABLE_FULLSCREEN_AMBIENT_MODE.get();
}
}
| 325 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
HideInfoCardsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideInfoCardsPatch.java | package app.revanced.integrations.youtube.patches;
import android.view.View;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class HideInfoCardsPatch {
public static void hideInfoCardsIncognito(View view) {
if (!Settings.HIDE_INFO_CARDS.get()) return;
view.setVisibility(View.GONE);
}
public static boolean hideInfoCardsMethodCall() {
return Settings.HIDE_INFO_CARDS.get();
}
}
| 469 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
VideoAdsPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/VideoAdsPatch.java | package app.revanced.integrations.youtube.patches;
import app.revanced.integrations.youtube.settings.Settings;
@SuppressWarnings("unused")
public class VideoAdsPatch {
// Used by app.revanced.patches.youtube.ad.general.video.patch.VideoAdsPatch
// depends on Whitelist patch (still needs to be written)
public static boolean shouldShowAds() {
return !Settings.HIDE_VIDEO_ADS.get(); // TODO && Whitelist.shouldShowAds();
}
}
| 452 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.