Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
37900cac49 | ||
|
|
be57c76d93 | ||
|
|
8b52ad7858 | ||
|
|
a0976bde02 | ||
|
|
15c97d5cfc | ||
|
|
905cbd5a35 | ||
|
|
5c0e2e6185 | ||
|
|
4836d2dacb | ||
|
|
bc81ec1ab5 | ||
|
|
8a4d039a37 | ||
|
|
468639264a | ||
|
|
9b649b470f | ||
|
|
edd5cf2bf7 | ||
|
|
67c605e640 | ||
|
|
8d4b878656 | ||
|
|
bf532dd1d0 | ||
|
|
eb1a125e59 | ||
|
|
256659a72d | ||
|
|
dbf3aa7e7d | ||
|
|
a75ce181ff | ||
|
|
37ae6b4ebf | ||
|
|
6631a6a95b | ||
|
|
918f8578ad | ||
|
|
10fa9f68ae | ||
|
|
6b5c9ccb0f | ||
|
|
652e8f1a9d | ||
|
|
fe53ae733d | ||
|
|
690dab2ae8 | ||
|
|
530542163e | ||
|
|
cf7f4c75c0 | ||
|
|
c6b395cf4c | ||
|
|
e72edeed62 | ||
|
|
3f22d53f89 | ||
|
|
08c0fa62b1 | ||
|
|
4c79cca079 | ||
|
|
67096242a2 | ||
|
|
f66112375d | ||
|
|
c5a082e248 | ||
|
|
c2a1b0aa33 | ||
|
|
a89dcc96d8 | ||
|
|
b2a10eafd9 | ||
|
|
f027aff89d | ||
|
|
b4eaf0d1c4 | ||
|
|
9d2975faaa | ||
|
|
0c0fdf9d78 | ||
|
|
e17afa0ef3 | ||
|
|
3d3eb6aa36 | ||
|
|
e22132255e | ||
|
|
ef041526ec | ||
|
|
704311dd9a | ||
|
|
9617a6f20f | ||
|
|
bc17442961 | ||
|
|
574d6818c1 | ||
|
|
5c416055ee | ||
|
|
fa30458dc6 | ||
|
|
638af93225 | ||
|
|
2c6ca741c7 | ||
|
|
d7f2df2540 | ||
|
|
b85ade1dba | ||
|
|
1c61a0b34e | ||
|
|
46b9449969 | ||
|
|
cc1bbd1231 | ||
|
|
b29cba2911 | ||
|
|
13bde3aa2c | ||
|
|
35b4f5fc97 | ||
|
|
1b0482b7d4 | ||
|
|
c9ff6eeab6 | ||
|
|
5ac57b743d | ||
|
|
f7b219701f | ||
|
|
d009aa3f8c | ||
|
|
078d49f883 | ||
|
|
f1bf517ba5 | ||
|
|
6269ed6f6e | ||
|
|
43b8dedbb1 | ||
|
|
978be7bd49 | ||
|
|
1b7f3aef62 | ||
|
|
7d24ee4867 | ||
|
|
269a3475b0 | ||
|
|
18e2bc6afc | ||
|
|
c6ef54e115 | ||
|
|
441b2831fc | ||
|
|
3cf4d60eca | ||
|
|
d228c89a1c | ||
|
|
f3b592e81b | ||
|
|
a5ff659fb4 | ||
|
|
ab80e2f3b3 | ||
|
|
2ef082f87e |
@@ -3,4 +3,5 @@
|
||||
/**/*/target
|
||||
/**/*/build-dir
|
||||
/**/*/java-runtime
|
||||
.idea
|
||||
.idea
|
||||
.vripper
|
||||
@@ -1,5 +1,169 @@
|
||||
# Changelog
|
||||
|
||||
## [3.0.2] - 2020-08-15
|
||||
### Changed
|
||||
- Fix bugs with download queue
|
||||
|
||||
## [3.0.1] - 2020-08-03
|
||||
### Changed
|
||||
- Fix bugs with download queue
|
||||
|
||||
## [3.0.0] - 2020-08-03
|
||||
### Changed
|
||||
- Major rewrites
|
||||
- Introducing a proper database for persistence
|
||||
|
||||
## [2.12.1] - 2020-05-22
|
||||
### Changed
|
||||
- Fix alternative name bug
|
||||
|
||||
## [2.12.0] - 2020-05-21
|
||||
### Changed
|
||||
- Use new user hash from the api
|
||||
|
||||
## [2.11.7] - 2020-05-08
|
||||
### Changed
|
||||
- Fix bug with paths creation
|
||||
- Move Open Link button
|
||||
- Rename rename all title
|
||||
|
||||
## [2.11.6] - 2020-05-04
|
||||
### Changed
|
||||
- PNG filenames are now correctly named
|
||||
- Fix issue with special characters in post titles
|
||||
|
||||
## [2.11.5] - 2020-05-03
|
||||
### Changed
|
||||
- Reduce rows buffer size
|
||||
|
||||
## [2.11.4] - 2020-05-03
|
||||
### Changed
|
||||
- Code cleanup
|
||||
- Dependencies update
|
||||
|
||||
## [2.11.3] - 2020-04-30
|
||||
### Changed
|
||||
- Source code restructure
|
||||
- UI fixes and enhancements
|
||||
### Added
|
||||
- Add menu entry to rename a gallery to first alternative title
|
||||
- Add menu on toolbar for massive rename to first alternative title
|
||||
|
||||
## [2.11.2] - 2020-04-26
|
||||
### Changed
|
||||
- Bug fixes
|
||||
|
||||
## [2.11.1] - 2020-04-25
|
||||
### Changed
|
||||
- Code source maintenance
|
||||
### Added
|
||||
- Added option to rename gallery
|
||||
|
||||
## [2.11.0] - 2020-03-29
|
||||
### Changed
|
||||
- Upgrade Electron to v8
|
||||
- Upgrade Angular to v9
|
||||
- App settings are now portable in a json file
|
||||
- General code source maintenance
|
||||
### Added
|
||||
- Added Support for pixroute.com
|
||||
- Added grab post title from thread option
|
||||
|
||||
## [2.10.8] - 2020-01-25
|
||||
### Changed
|
||||
- Fix app url
|
||||
|
||||
## [2.10.7] - 2020-01-25
|
||||
### Changed
|
||||
- Drop SockJs and switch to WebSocket
|
||||
- Autoreconnect front to back
|
||||
|
||||
## [2.10.6] - 2020-01-19
|
||||
### Changed
|
||||
- Limit cache size
|
||||
|
||||
## [2.10.5] - 2020-01-18
|
||||
### Changed
|
||||
- Bug fixes
|
||||
|
||||
## [2.10.4] - 2020-01-18
|
||||
### Changed
|
||||
- Zero value for total max download will disable the limit
|
||||
- Add system notification
|
||||
- Bug fixes
|
||||
|
||||
## [2.10.3] - 2020-01-16
|
||||
### Changed
|
||||
- Some bug fixes
|
||||
- Enhance download queue logic
|
||||
- Clear cache button
|
||||
- Fix the partial status
|
||||
- Sanitize URLs with spaces
|
||||
### Added
|
||||
- Support for Postimg host
|
||||
- Support for Imagevenue host
|
||||
|
||||
## [2.10.2] - 2019-12-29
|
||||
### Changed
|
||||
- Upgrade electron to v7
|
||||
- Bug fix
|
||||
|
||||
## [2.10.1] - 2019-12-27
|
||||
### Changed
|
||||
- Bug fix
|
||||
|
||||
## [2.10.0] - 2019-12-27
|
||||
### Changed
|
||||
- Fix spring dependency bug
|
||||
### Added
|
||||
- Add support for imgspice
|
||||
|
||||
## [2.9.0] - 2019-12-27
|
||||
### Changed
|
||||
- Fix build issue
|
||||
|
||||
## [2.9.0] - 2019-12-27
|
||||
### Changed
|
||||
- Decrease timeout for fast fail
|
||||
### Added
|
||||
- Allow many hosts to run at the same time
|
||||
- Add title to gallery
|
||||
- Add global concurrent downloads
|
||||
- Add counter badge in link collector
|
||||
|
||||
## [2.8.1] - 2019-12-24
|
||||
### Changed
|
||||
- Fix issue with path creation
|
||||
|
||||
## [2.8.0] - 2019-12-24
|
||||
### Added
|
||||
- Photo gallery feature
|
||||
|
||||
## [2.7.1] - 2019-12-21
|
||||
### Added
|
||||
- Add version to title bar
|
||||
|
||||
## [2.7.0] - 2019-12-21
|
||||
### Changed
|
||||
- Add missing icon
|
||||
### Added
|
||||
- Add support for pixxxels
|
||||
|
||||
## [2.6.0] - 2019-12-21
|
||||
### Changed
|
||||
- Disable download button when nothing selected in Link collector grab menu
|
||||
- Better quality app icon
|
||||
- Implement context menu on download tab
|
||||
- Add stop remove and start button to context menu
|
||||
- Link will not be removed automatically from link collector tab
|
||||
- Some UI fixes
|
||||
|
||||
## [2.5.1] - 2019-12-09
|
||||
### Changed
|
||||
- Disable download button when nothing selected in Link collector grab menu
|
||||
### Added
|
||||
- Add hosts column in Link collector grab menu
|
||||
|
||||
## [2.5.0] - 2019-12-08
|
||||
### Changed
|
||||
- Change loading screen
|
||||
@@ -222,4 +386,4 @@
|
||||
- Add real time communication for progress updates via websocket (SockJS)
|
||||
- Add settings for download path, max concurrent download, enable/disable integration with vipergirls
|
||||
- Add integration with vipergitls.to (possibility to auto leave thanks after grab post)
|
||||
- Add support for acidimg.cc, imagezilla.net, imgbox.com, imx.to, pixhost.to, turboimagehost.com
|
||||
- Add support for acidimg.cc, imagezilla.net, imgbox.com, imx.to, pixhost.to, turboimagehost.com
|
||||
|
||||
@@ -1,26 +1,24 @@
|
||||
# Viper Ripper!
|
||||
|
||||
This is my spin for a gallery ripper app for [vipergirls](https://vipergirls.to) website.
|
||||
This is my spin for a cross platform gallery ripper app for [vipergirls](https://vipergirls.to) website.
|
||||
The purpose of this project is to build a robust and clean application to conveniently download photo galleries using modern web technologies, Java + Spring boot for the back end and angular + electron for the front end.
|
||||
|
||||
## How to build
|
||||
You need a recent version of maven 3.6.1+.
|
||||
|
||||
The application support 2 build modes:
|
||||
- Desktop app (*Partially cross platform): Self contained app, built with electron, depends on Java runtimes.
|
||||
- Server app (Fully cross platform): Depends on Java runtimes, you need a web browser to access the app UI.
|
||||
- Desktop app: Self contained app, built with electron includes Java runtimes.
|
||||
- Server app: Depends on Java runtimes, you need a web browser to access the app UI.
|
||||
|
||||
Most people will be interested only on the desktop app, however if you have a nas or a server, the server app is there for you.
|
||||
|
||||
To build the server app:
|
||||
|
||||
mvn clean install
|
||||
mvn clean install -DskipTests
|
||||
To build the desktop app:
|
||||
|
||||
mvn clean install -Pelectron
|
||||
mvn clean install -Pelectron -DskipTests
|
||||
|
||||
Maven will automatically handle front end compilation. However, for development, you will need to install a recent version of nodejs on your system.
|
||||
|
||||
*Partially cross platform:
|
||||
Technically cross platform, but the Desktop app relies on electron builder to make appropriate binaries for each platform. mac binaries can only be generated on a mac, and i don't own one. So i can only provide binaries for windows and linux.
|
||||
The Server app however depends only on Java, so it will work just fine on a mac, you only need a browser to access it.
|
||||
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=SC7M5LNWZ528Q)
|
||||
@@ -4,12 +4,12 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>tn.mnlr</groupId>
|
||||
<artifactId>vripper</artifactId>
|
||||
<version>2.5.0</version>
|
||||
<version>3.0.2</version>
|
||||
<packaging>pom</packaging>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.1.RELEASE</version>
|
||||
<version>2.3.0.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<modules>
|
||||
|
||||
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 303 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 592 B |
|
After Width: | Height: | Size: 8.3 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
@@ -1,3 +1,4 @@
|
||||
require('v8-compile-cache');
|
||||
const { app, BrowserWindow } = require("electron");
|
||||
const path = require("path");
|
||||
const url = require("url");
|
||||
@@ -18,134 +19,140 @@ let terminationInteval;
|
||||
let terminated = false;
|
||||
|
||||
process.on("uncaughtException", err => {
|
||||
dialog.showErrorBox(err.message, err.stack);
|
||||
process.exit(1);
|
||||
dialog.showErrorBox(err.message, err.stack);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
function createWindow() {
|
||||
let icon;
|
||||
if(process.platform === "win32") {
|
||||
icon = __dirname + '/icon.ico';
|
||||
} else {
|
||||
icon = __dirname + '/icon.png';
|
||||
}
|
||||
win = new BrowserWindow({
|
||||
width: 1024,
|
||||
height: 800,
|
||||
minWidth: 800,
|
||||
minHeight: 600,
|
||||
webPreferences: {
|
||||
nodeIntegration: true
|
||||
},
|
||||
icon: icon
|
||||
});
|
||||
|
||||
win.removeMenu();
|
||||
win.setMenu(null);
|
||||
win.setMenuBarVisibility(false);
|
||||
if (process.platform === 'win32') {
|
||||
app.setAppUserModelId("tn.mnlr.vripper");
|
||||
}
|
||||
|
||||
win.loadURL(
|
||||
url.format({
|
||||
pathname: path.join(__dirname, `vripper-ui/index.html`),
|
||||
protocol: "file:",
|
||||
slashes: true
|
||||
})
|
||||
);
|
||||
let icon;
|
||||
if(process.platform === "win32") {
|
||||
icon = __dirname + '/icon.ico';
|
||||
} else {
|
||||
icon = __dirname + '/icon.png';
|
||||
}
|
||||
win = new BrowserWindow({
|
||||
width: 1024,
|
||||
height: 800,
|
||||
minWidth: 800,
|
||||
minHeight: 600,
|
||||
webPreferences: {
|
||||
nodeIntegration: true,
|
||||
enableRemoteModule: true
|
||||
},
|
||||
icon: icon
|
||||
});
|
||||
|
||||
// win.webContents.openDevTools();
|
||||
win.removeMenu();
|
||||
win.setMenu(null);
|
||||
win.setMenuBarVisibility(false);
|
||||
|
||||
win.on("closed", () => {
|
||||
win = null;
|
||||
});
|
||||
win.loadURL(
|
||||
url.format({
|
||||
pathname: path.join(__dirname, `vripper-ui/index.html`),
|
||||
protocol: "file:",
|
||||
slashes: true
|
||||
})
|
||||
);
|
||||
|
||||
// win.webContents.openDevTools();
|
||||
|
||||
win.on("closed", () => {
|
||||
win = null;
|
||||
});
|
||||
}
|
||||
|
||||
getPort().then(port => {
|
||||
serverPort = port;
|
||||
ipcMain.on("get-port", event => {
|
||||
event.reply("port", port);
|
||||
});
|
||||
let javaBinPath;
|
||||
if(appDir !== undefined) {
|
||||
javaBinPath = path.join(appDir, "java-runtime/bin/java");
|
||||
} else {
|
||||
if(process.platform === 'darwin') {
|
||||
javaBinPath = path.join(app.getPath('exe'), "../../java-runtime/bin/java");
|
||||
} else {
|
||||
javaBinPath = path.join(app.getPath('exe'), "../java-runtime/bin/java");
|
||||
}
|
||||
}
|
||||
let jarPath;
|
||||
if(appDir !== undefined) {
|
||||
jarPath = path.join(appDir, "bin/vripper-server.jar");
|
||||
} else {
|
||||
if(process.platform === 'darwin') {
|
||||
jarPath = path.join(app.getPath('exe'), "../../bin/vripper-server.jar");
|
||||
} else {
|
||||
jarPath = path.join(app.getPath('exe'), "../bin/vripper-server.jar");
|
||||
}
|
||||
}
|
||||
vripperServer = spawn(javaBinPath, [
|
||||
"-Xms256m",
|
||||
"-Xmx1024m",
|
||||
"-Dvripper.server.port=" + port,
|
||||
"-jar",
|
||||
jarPath
|
||||
], {
|
||||
stdio: 'ignore'
|
||||
});
|
||||
vripperServer.on('exit', (code, signal) => {
|
||||
console.log(`vripper server terminated, code = ${code}, signal = ${signal}`);
|
||||
terminated = true;
|
||||
app.quit();
|
||||
});
|
||||
});
|
||||
|
||||
const gotTheLock = app.requestSingleInstanceLock();
|
||||
|
||||
if (!gotTheLock) {
|
||||
app.quit();
|
||||
app.quit();
|
||||
} else {
|
||||
app.on("second-instance", (event, commandLine, workingDirectory) => {
|
||||
if (win) {
|
||||
if (win.isMinimized()) win.restore();
|
||||
win.focus();
|
||||
}
|
||||
});
|
||||
|
||||
app.on("ready", createWindow);
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
axios.post('http://localhost:' + serverPort + '/actuator/shutdown', {}, {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}).then((response) => {
|
||||
terminationInteval= setInterval(() => {
|
||||
terminationAttemps++;
|
||||
if(terminated) {
|
||||
console.log('viper server terminated');
|
||||
clearInterval(terminationInteval);
|
||||
getPort().then(port => {
|
||||
serverPort = port;
|
||||
ipcMain.on("get-port", event => {
|
||||
event.reply("port", port);
|
||||
});
|
||||
let javaBinPath;
|
||||
if(appDir !== undefined) {
|
||||
javaBinPath = path.join(appDir, "java-runtime/bin/java");
|
||||
} else {
|
||||
if(process.platform === 'darwin') {
|
||||
javaBinPath = path.join(app.getPath('exe'), "../../java-runtime/bin/java");
|
||||
} else {
|
||||
javaBinPath = path.join(app.getPath('exe'), "../java-runtime/bin/java");
|
||||
}
|
||||
}
|
||||
let jarPath;
|
||||
if(appDir !== undefined) {
|
||||
jarPath = path.join(appDir, "bin/vripper-server.jar");
|
||||
} else {
|
||||
if(process.platform === 'darwin') {
|
||||
jarPath = path.join(app.getPath('exe'), "../../bin/vripper-server.jar");
|
||||
} else {
|
||||
jarPath = path.join(app.getPath('exe'), "../bin/vripper-server.jar");
|
||||
}
|
||||
}
|
||||
vripperServer = spawn(javaBinPath, [
|
||||
"-Xms256m",
|
||||
"-Dvripper.server.port=" + port,
|
||||
"-jar",
|
||||
jarPath
|
||||
], {
|
||||
stdio: 'ignore'
|
||||
});
|
||||
vripperServer.on('exit', (code, signal) => {
|
||||
console.log(`vripper server terminated, code = ${code}, signal = ${signal}`);
|
||||
terminated = true;
|
||||
app.quit();
|
||||
} else if(terminationAttemps > maxTerminationAttemps) {
|
||||
console.log('viper server is not terminated');
|
||||
console.log('Proceed to kill');
|
||||
vripperServer.kill('SIGKILL');
|
||||
clearInterval(terminationInteval);
|
||||
app.quit();
|
||||
}
|
||||
}, 1000);
|
||||
})
|
||||
.catch((error) => {
|
||||
// Terminate immediately
|
||||
vripperServer.kill('SIGKILL');
|
||||
terminated = true;
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
if (win === null) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
app.on("second-instance", (event, commandLine, workingDirectory) => {
|
||||
if (win) {
|
||||
if (win.isMinimized()) win.restore();
|
||||
win.focus();
|
||||
}
|
||||
});
|
||||
|
||||
app.on("ready", createWindow);
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
axios.post('http://localhost:' + serverPort + '/actuator/shutdown', {}, {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}).then((response) => {
|
||||
terminationInteval= setInterval(() => {
|
||||
terminationAttemps++;
|
||||
if(terminated) {
|
||||
console.log('viper server terminated');
|
||||
clearInterval(terminationInteval);
|
||||
app.quit();
|
||||
} else if(terminationAttemps > maxTerminationAttemps) {
|
||||
console.log('viper server is not terminated');
|
||||
console.log('Proceed to kill');
|
||||
vripperServer.kill('SIGKILL');
|
||||
clearInterval(terminationInteval);
|
||||
app.quit();
|
||||
}
|
||||
}, 1000);
|
||||
})
|
||||
.catch((error) => {
|
||||
// Terminate immediately
|
||||
console.log(error);
|
||||
vripperServer.kill('SIGKILL');
|
||||
terminated = true;
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
if (win === null) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "vripper-electron",
|
||||
"version": "2.5.0",
|
||||
"version": "3.0.2",
|
||||
"description": "A ripper for vipergirls.to built using web technolgies",
|
||||
"main": "main.js",
|
||||
"author": "death-claw <53543762+death-claw@users.noreply.github.com>",
|
||||
@@ -8,7 +8,7 @@
|
||||
"license": "ISC",
|
||||
"build": {
|
||||
"appId": "tn.mnlr.vripper",
|
||||
"productName": "vripper",
|
||||
"productName": "VRipper",
|
||||
"files": [
|
||||
"**/*",
|
||||
"!**/node_modules/*/{CHANGELOG.md,README.md,README,readme.md,readme}",
|
||||
@@ -38,7 +38,7 @@
|
||||
}
|
||||
],
|
||||
"win": {
|
||||
"icon": "icon.png",
|
||||
"icon": "icon.ico",
|
||||
"target": [
|
||||
"nsis"
|
||||
]
|
||||
@@ -62,7 +62,7 @@
|
||||
"target": [
|
||||
"dmg"
|
||||
],
|
||||
"icon": "icon.png"
|
||||
"icon": "icon.icns"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
@@ -70,16 +70,16 @@
|
||||
"dist": "node pre-build.js && electron-builder"
|
||||
},
|
||||
"devDependencies": {
|
||||
"electron": "^6.0.9",
|
||||
"electron-builder": "^21.2.0"
|
||||
"electron": "9.1.0",
|
||||
"electron-builder": "22.7.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^0.19.0",
|
||||
"cheerio": "^1.0.0-rc.3",
|
||||
"copy-dir": "^1.1.0",
|
||||
"custom-electron-titlebar": "^3.0.10",
|
||||
"electron-context-menu": "^0.13.0",
|
||||
"get-port": "^5.0.0",
|
||||
"rimraf": "^2.6.3"
|
||||
"axios": "0.19.2",
|
||||
"cheerio": "1.0.0-rc.3",
|
||||
"copy-dir": "1.3.0",
|
||||
"electron-context-menu": "2.1.0",
|
||||
"get-port": "5.1.1",
|
||||
"rimraf": "3.0.2",
|
||||
"v8-compile-cache": "2.1.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<groupId>tn.mnlr</groupId>
|
||||
<artifactId>vripper</artifactId>
|
||||
<version>2.5.0</version>
|
||||
<version>3.0.2</version>
|
||||
</parent>
|
||||
<artifactId>vripper-electron</artifactId>
|
||||
<name>vripper-electron</name>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<groupId>tn.mnlr</groupId>
|
||||
<artifactId>vripper</artifactId>
|
||||
<version>2.5.0</version>
|
||||
<version>3.0.2</version>
|
||||
</parent>
|
||||
<artifactId>vripper-server</artifactId>
|
||||
<name>vripper-server</name>
|
||||
@@ -32,6 +32,20 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.liquibase</groupId>
|
||||
<artifactId>liquibase-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>2.5.1</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package tn.mnlr.vripper;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.event.ContextRefreshedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tn.mnlr.vripper.jpa.repositories.IRepository;
|
||||
import tn.mnlr.vripper.services.DataService;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@Component
|
||||
public class EventListenerBean {
|
||||
|
||||
@Getter
|
||||
private static boolean init = false;
|
||||
|
||||
private final DataService dataService;
|
||||
private final Set<IRepository> repositorySet;
|
||||
|
||||
@Autowired
|
||||
public EventListenerBean(DataService dataService, Set<IRepository> repositorySet) {
|
||||
this.dataService = dataService;
|
||||
this.repositorySet = repositorySet;
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void onApplicationEvent(ContextRefreshedEvent event) {
|
||||
repositorySet.forEach(IRepository::init);
|
||||
dataService.setDownloadingToStopped();
|
||||
init = true;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package tn.mnlr.vripper;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
@@ -11,10 +10,9 @@ import org.springframework.stereotype.Component;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class SpringContext implements ApplicationContextAware {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SpringContext.class);
|
||||
|
||||
private static ConfigurableApplicationContext context;
|
||||
|
||||
public static <T> T getBean(Class<T> beanClass) {
|
||||
@@ -26,8 +24,10 @@ public class SpringContext implements ApplicationContextAware {
|
||||
}
|
||||
|
||||
public static void close() {
|
||||
logger.info("Application terminating...");
|
||||
context.close();
|
||||
log.info("Application terminating...");
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,77 +1,28 @@
|
||||
package tn.mnlr.vripper;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.jodah.failsafe.RetryPolicy;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tn.mnlr.vripper.exception.VripperException;
|
||||
import tn.mnlr.vripper.services.AppSettingsService;
|
||||
import tn.mnlr.vripper.services.PersistenceService;
|
||||
import tn.mnlr.vripper.services.VipergirlsAuthService;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.File;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
@SpringBootApplication
|
||||
@Slf4j
|
||||
public class VripperApplication {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VripperApplication.class);
|
||||
public static final ExecutorService commonExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
|
||||
public static final RetryPolicy<Object> retryPolicy = new RetryPolicy<>()
|
||||
.withDelay(1, 3, ChronoUnit.SECONDS)
|
||||
.withMaxAttempts(5)
|
||||
.onFailedAttempt(e -> log.warn(String.format("#%d tries failed", e.getAttemptCount()), e.getLastFailure()));
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(SpringContext::close));
|
||||
SpringApplication.run(VripperApplication.class, args);
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to run the application", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
public class AppCommandRunner implements CommandLineRunner {
|
||||
|
||||
@Autowired
|
||||
private VipergirlsAuthService authService;
|
||||
|
||||
@Autowired
|
||||
private PersistenceService persistenceService;
|
||||
|
||||
@Autowired
|
||||
private AppSettingsService appSettingsService;
|
||||
|
||||
@Value("${base.dir}")
|
||||
private String baseDir;
|
||||
|
||||
@Getter
|
||||
private String dataPath;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
dataPath = baseDir + File.separator + ".vripper" + File.separator + "data.json";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
|
||||
persistenceService.restore();
|
||||
appSettingsService.restore();
|
||||
registerShutdownHook();
|
||||
|
||||
try {
|
||||
authService.authenticate();
|
||||
} catch (VripperException e) {
|
||||
logger.error("Cannot authenticate user with ViperGirls", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void registerShutdownHook() {
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(SpringContext::close));
|
||||
log.error("Failed to run the application", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
package tn.mnlr.vripper.entities;
|
||||
|
||||
import io.reactivex.disposables.Disposable;
|
||||
import io.reactivex.processors.BehaviorProcessor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.services.AppStateService;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
public class Image {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Image.class);
|
||||
|
||||
private AppStateService appStateService;
|
||||
|
||||
private Disposable subscription;
|
||||
|
||||
private final String type = "img";
|
||||
|
||||
private String postId;
|
||||
|
||||
private String postName;
|
||||
|
||||
private Host host;
|
||||
|
||||
private String url;
|
||||
|
||||
private int index;
|
||||
|
||||
private AtomicLong current = new AtomicLong(0);
|
||||
private Status status;
|
||||
private BehaviorProcessor<Image> imageStateProcessor;
|
||||
|
||||
@Setter
|
||||
private long total = 0;
|
||||
|
||||
public Image(String url, String postId, String postName, Host host, int index) {
|
||||
this.url = url;
|
||||
this.postId = postId;
|
||||
this.postName = postName;
|
||||
this.host = host;
|
||||
this.index = index;
|
||||
status = Status.STOPPED;
|
||||
imageStateProcessor = BehaviorProcessor.create();
|
||||
}
|
||||
|
||||
public void setAppStateService(AppStateService appStateService) {
|
||||
this.appStateService = appStateService;
|
||||
appStateService.getCurrentImages().put(this.url, this);
|
||||
appStateService.getLiveImageUpdates().onNext(this);
|
||||
}
|
||||
|
||||
public void setStatus(Status status) {
|
||||
this.status = status;
|
||||
update();
|
||||
}
|
||||
|
||||
public boolean isCompleted() {
|
||||
return status.equals(Status.COMPLETE);
|
||||
}
|
||||
|
||||
public void init() {
|
||||
if (appStateService == null) {
|
||||
logger.warn("Attempting to init the image whilst the App State is null, unexpected behaviour could occur from this");
|
||||
return;
|
||||
}
|
||||
cleanup();
|
||||
imageStateProcessor = BehaviorProcessor.create();
|
||||
subscription = imageStateProcessor
|
||||
.onBackpressureLatest()
|
||||
.doOnNext(appStateService::onImageUpdate)
|
||||
.subscribe();
|
||||
|
||||
current.set(0);
|
||||
status = Status.STOPPED;
|
||||
imageStateProcessor.onNext(this);
|
||||
}
|
||||
|
||||
public void cleanup() {
|
||||
if (imageStateProcessor != null) {
|
||||
imageStateProcessor.onComplete();
|
||||
}
|
||||
if (subscription != null) {
|
||||
subscription.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void setCurrent(int current) {
|
||||
this.current.set(current);
|
||||
update();
|
||||
}
|
||||
|
||||
public void increase(int read) {
|
||||
current.addAndGet(read);
|
||||
update();
|
||||
}
|
||||
|
||||
private void update() {
|
||||
if(imageStateProcessor == null) {
|
||||
return;
|
||||
}
|
||||
imageStateProcessor.onNext(this);
|
||||
if (isCompleted()) {
|
||||
imageStateProcessor.onComplete();
|
||||
subscription.dispose();
|
||||
imageStateProcessor = null;
|
||||
}
|
||||
}
|
||||
|
||||
public enum Status {
|
||||
PENDING, DOWNLOADING, COMPLETE, ERROR, STOPPED
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Image image = (Image) o;
|
||||
return url.equals(image.url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(url);
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package tn.mnlr.vripper.entities;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.services.AppStateService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Getter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
public class Post {
|
||||
|
||||
private AppStateService appStateService;
|
||||
|
||||
private Status status;
|
||||
|
||||
private final String type = "post";
|
||||
|
||||
private String postId;
|
||||
|
||||
private String threadTitle;
|
||||
|
||||
private String threadId;
|
||||
|
||||
private String title;
|
||||
|
||||
private String url;
|
||||
|
||||
private List<Image> images;
|
||||
|
||||
private Map<String, Object> metadata;
|
||||
|
||||
private AtomicInteger done = new AtomicInteger(0);
|
||||
|
||||
private int total;
|
||||
|
||||
private Set<String> hosts;
|
||||
|
||||
private boolean removed = false;
|
||||
|
||||
private String forum;
|
||||
|
||||
public Post(String title, String url, List<Image> images, Map<String, Object> metadata, String postId, String threadId, String threadTitle, String forum) {
|
||||
this.title = title;
|
||||
this.url = url;
|
||||
this.images = images;
|
||||
this.metadata = metadata;
|
||||
this.postId = postId;
|
||||
this.forum = forum;
|
||||
this.threadId = threadId;
|
||||
this.threadTitle = threadTitle;
|
||||
this.hosts = this.images.stream().map(Image::getHost).map(Host::getHost).collect(Collectors.toSet());
|
||||
total = images.size();
|
||||
status = Status.STOPPED;
|
||||
}
|
||||
|
||||
public void setAppStateService(AppStateService appStateService) {
|
||||
this.appStateService = appStateService;
|
||||
this.appStateService.getCurrentPosts().put(postId, this);
|
||||
this.appStateService.getLivePostsState().onNext(this);
|
||||
}
|
||||
|
||||
public void setRemoved(boolean removed) {
|
||||
this.removed = removed;
|
||||
updateNotification();
|
||||
}
|
||||
|
||||
public void increase() {
|
||||
done.incrementAndGet();
|
||||
updateNotification();
|
||||
}
|
||||
|
||||
public void setStatus(Status status) {
|
||||
this.status = status;
|
||||
updateNotification();
|
||||
}
|
||||
|
||||
private void updateNotification() {
|
||||
if (appStateService != null) {
|
||||
appStateService.getLivePostsState().onNext(this);
|
||||
}
|
||||
}
|
||||
|
||||
public enum Status {
|
||||
PENDING, DOWNLOADING, COMPLETE, ERROR, PARTIAL, STOPPED
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Post post = (Post) o;
|
||||
return postId.equals(post.postId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(postId);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package tn.mnlr.vripper.entities.mixin.persistance;
|
||||
|
||||
import com.fasterxml.jackson.databind.util.StdConverter;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
|
||||
public class HostToString extends StdConverter<Host, String> {
|
||||
|
||||
@Override
|
||||
public String convert(Host value) {
|
||||
return value.getClass().getSimpleName();
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package tn.mnlr.vripper.entities.mixin.persistance;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.reactivex.disposables.Disposable;
|
||||
import io.reactivex.processors.BehaviorProcessor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.services.AppStateService;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public abstract class ImagePersistanceMixin {
|
||||
|
||||
@JsonSerialize(converter = HostToString.class)
|
||||
@JsonDeserialize(converter = StringToHost.class)
|
||||
private Host host;
|
||||
|
||||
@JsonIgnore
|
||||
private BehaviorProcessor<Image> imageStateProcessor;
|
||||
|
||||
@JsonIgnore
|
||||
private Disposable subscription;
|
||||
|
||||
@JsonIgnore
|
||||
private String type;
|
||||
|
||||
@JsonIgnore
|
||||
public abstract boolean isCompleted();
|
||||
|
||||
@JsonIgnore
|
||||
private AppStateService appStateService;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package tn.mnlr.vripper.entities.mixin.persistance;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import tn.mnlr.vripper.services.AppStateService;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public abstract class PostPersistanceMixin {
|
||||
|
||||
@JsonIgnore
|
||||
private String type;
|
||||
|
||||
@JsonIgnore
|
||||
private AppStateService appStateService;
|
||||
|
||||
|
||||
@JsonIgnore
|
||||
private boolean removed;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package tn.mnlr.vripper.entities.mixin.persistance;
|
||||
|
||||
import com.fasterxml.jackson.databind.util.StdConverter;
|
||||
import tn.mnlr.vripper.SpringContext;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public class StringToHost extends StdConverter<String, Host> {
|
||||
|
||||
private Collection<Host> hosts = SpringContext.getBeansOfType(Host.class).values();
|
||||
|
||||
@Override
|
||||
public Host convert(String value) {
|
||||
return hosts.stream().filter(e -> e.getClass().getSimpleName().equals(value)).findAny().orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package tn.mnlr.vripper.entities.mixin.ui;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import io.reactivex.disposables.Disposable;
|
||||
import io.reactivex.processors.BehaviorProcessor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.services.AppStateService;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public abstract class ImageUIMixin {
|
||||
|
||||
@JsonIgnore
|
||||
private Host host;
|
||||
|
||||
@JsonIgnore
|
||||
private BehaviorProcessor<Image> imageStateProcessor;
|
||||
|
||||
@JsonIgnore
|
||||
private Disposable subscription;
|
||||
|
||||
@JsonIgnore
|
||||
private AppStateService appStateService;
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package tn.mnlr.vripper.entities.mixin.ui;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.services.AppStateService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public abstract class PostUIMixin {
|
||||
|
||||
@JsonIgnore
|
||||
private List<Image> images;
|
||||
|
||||
@JsonIgnore
|
||||
private AppStateService appStateService;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package tn.mnlr.vripper.exception;
|
||||
|
||||
public class QueueException extends Exception {
|
||||
|
||||
public QueueException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public QueueException(String message, Throwable e) {
|
||||
super(message, e);
|
||||
}
|
||||
|
||||
public QueueException(Throwable e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
@@ -8,8 +9,6 @@ import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
@@ -23,10 +22,9 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class AcidimgHost extends Host {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AcidimgHost.class);
|
||||
|
||||
private static final String host = "acidimg.cc";
|
||||
private static final String CONTINUE_BUTTON_XPATH = "//input[@id='continuebutton']";
|
||||
private static final String IMG_XPATH = "//img[@class='centred']";
|
||||
@@ -34,6 +32,10 @@ public class AcidimgHost extends Host {
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
|
||||
public AcidimgHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
return host;
|
||||
@@ -51,14 +53,14 @@ public class AcidimgHost extends Host {
|
||||
|
||||
Node contDiv;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", CONTINUE_BUTTON_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", CONTINUE_BUTTON_XPATH, url));
|
||||
contDiv = xpathService.getAsNode(doc, CONTINUE_BUTTON_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
if (contDiv != null) {
|
||||
logger.debug(String.format("Click button found for %s", url));
|
||||
log.debug(String.format("Click button found for %s", url));
|
||||
HttpClient client = cm.getClient().build();
|
||||
HttpPost httpPost = cm.buildHttpPost(url);
|
||||
httpPost.addHeader("Referer", url);
|
||||
@@ -70,9 +72,9 @@ public class AcidimgHost extends Host {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
logger.debug(String.format("Requesting %s", httpPost));
|
||||
log.debug(String.format("Requesting %s", httpPost));
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpPost, context)) {
|
||||
logger.debug(String.format("Cleaning response for %s", httpPost));
|
||||
log.debug(String.format("Cleaning response for %s", httpPost));
|
||||
doc = htmlProcessorService.clean(EntityUtils.toString(response.getEntity()));
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
} catch (Exception e) {
|
||||
@@ -82,18 +84,18 @@ public class AcidimgHost extends Host {
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
if(imgNode == null) {
|
||||
if (imgNode == null) {
|
||||
throw new HostException("Cannot find the image node");
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(String.format("Resolving name and image url for %s", url));
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = imgNode.getAttributes().getNamedItem("alt").getTextContent().trim();
|
||||
String imgUrl = imgNode.getAttributes().getNamedItem("src").getTextContent().trim();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
@@ -8,15 +9,16 @@ import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.impl.client.BasicCookieStore;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.exception.DownloadException;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.HtmlProcessorException;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
import tn.mnlr.vripper.q.DownloadJob;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
import tn.mnlr.vripper.services.*;
|
||||
|
||||
@@ -30,15 +32,18 @@ import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Iterator;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
abstract public class Host {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Host.class);
|
||||
|
||||
private static final int READ_BUFFER_SIZE = 8192;
|
||||
|
||||
private static final Byte LOCK = 0;
|
||||
|
||||
@Autowired
|
||||
protected HtmlProcessorService htmlProcessorService;
|
||||
|
||||
@@ -49,7 +54,7 @@ abstract public class Host {
|
||||
private AppSettingsService appSettingsService;
|
||||
|
||||
@Autowired
|
||||
private AppStateService appStateService;
|
||||
private DataService dataService;
|
||||
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
@@ -60,6 +65,13 @@ abstract public class Host {
|
||||
@Autowired
|
||||
private PathService pathService;
|
||||
|
||||
@Autowired
|
||||
private VipergirlsAuthService authService;
|
||||
|
||||
protected Host() {
|
||||
|
||||
}
|
||||
|
||||
abstract public String getHost();
|
||||
|
||||
abstract public String getLookup();
|
||||
@@ -68,98 +80,158 @@ abstract public class Host {
|
||||
return url.contains(getLookup());
|
||||
}
|
||||
|
||||
public void download(Image image, ImageFileData imageFileData) throws DownloadException, InterruptedException {
|
||||
public void download(final Post post, final Image image, final ImageFileData imageFileData, DownloadJob downloadJob) throws DownloadException, InterruptedException {
|
||||
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
context.setCookieStore(new BasicCookieStore());
|
||||
try {
|
||||
|
||||
appStateService.postDownloadingUpdate(image.getPostId());
|
||||
image.setStatus(Status.DOWNLOADING);
|
||||
image.setCurrent(0);
|
||||
dataService.updateImageStatus(image.getStatus(), image.getId());
|
||||
dataService.updateImageCurrent(image.getCurrent(), image.getId());
|
||||
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
context.setCookieStore(new BasicCookieStore());
|
||||
|
||||
synchronized (LOCK) {
|
||||
if (!post.getStatus().equals(Status.DOWNLOADING) && !post.getStatus().equals(Status.PARTIAL)) {
|
||||
post.setStatus(Status.DOWNLOADING);
|
||||
dataService.updatePostStatus(post.getStatus(), post.getId());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
imageFileData.setPageUrl(image.getUrl());
|
||||
|
||||
/*
|
||||
* HOST SPECIFIC
|
||||
*/
|
||||
logger.debug(String.format("Getting image url and name from %s using %s", image.getUrl(), this.getHost()));
|
||||
log.debug(String.format("Getting image url and name from %s using %s", image.getUrl(), this.getHost()));
|
||||
setNameAndUrl(image.getUrl(), imageFileData, context);
|
||||
logger.debug(String.format("Resolved name for %s: %s", image.getUrl(), imageFileData.getImageName()));
|
||||
logger.debug(String.format("Resolved image url for %s: %s", image.getUrl(), imageFileData.getImageUrl()));
|
||||
log.debug(String.format("Resolved name for %s: %s", image.getUrl(), imageFileData.getImageName()));
|
||||
log.debug(String.format("Resolved image url for %s: %s", image.getUrl(), imageFileData.getImageUrl()));
|
||||
|
||||
logger.debug(String.format("Building image request for %s", image.getUrl()));
|
||||
log.debug(String.format("Building image request for %s", image.getUrl()));
|
||||
setImageRequest(imageFileData);
|
||||
/*
|
||||
* END HOST SPECIFIC
|
||||
*/
|
||||
|
||||
String formatImageFileName = pathService.formatImageFileName(imageFileData.getImageName());
|
||||
logger.debug(String.format("Sanitizing image name from %s to %s", imageFileData.getImageName(), formatImageFileName));
|
||||
log.debug(String.format("Sanitizing image name from %s to %s", imageFileData.getImageName(), formatImageFileName));
|
||||
imageFileData.setImageName(formatImageFileName);
|
||||
File destinationFolder = pathService.getDownloadDestinationFolder(image.getPostId());
|
||||
logger.debug(String.format("Saving to %s", destinationFolder.getPath()));
|
||||
if (!destinationFolder.exists()) {
|
||||
logger.debug(String.format("Creating %s", destinationFolder.getPath()));
|
||||
if (destinationFolder.mkdirs()) {
|
||||
logger.debug(String.format("Folder %s is created", destinationFolder.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
HttpClient client = cm.getClient().build();
|
||||
|
||||
logger.debug(String.format("Downloading %s", imageFileData.getImageUrl()));
|
||||
log.debug(String.format("Downloading %s", imageFileData.getImageUrl()));
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) client.execute(imageFileData.getImageRequest(), context)) {
|
||||
|
||||
if (response.getStatusLine().getStatusCode() / 100 != 2) {
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
throw new DownloadException(String.format("Server returned code %d", response.getStatusLine().getStatusCode()));
|
||||
}
|
||||
|
||||
File outputFile = new File(destinationFolder.getPath() + File.separator + imageFileData.getImageName() + ".tmp");
|
||||
if (downloadJob.isStopped()) {
|
||||
return;
|
||||
}
|
||||
File destinationFolder;
|
||||
synchronized (LOCK) {
|
||||
Post updatedPost = dataService.findPostById(post.getId()).orElseThrow();
|
||||
if (updatedPost.getPostFolderName() == null) {
|
||||
pathService.createDefaultPostFolder(updatedPost);
|
||||
}
|
||||
destinationFolder = pathService.getDownloadDestinationFolder(updatedPost);
|
||||
authService.leaveThanks(updatedPost);
|
||||
}
|
||||
File outputFile = new File(destinationFolder.getPath() + File.separator + String.format("%03d_", image.getIndex()) + imageFileData.getImageName() + ".tmp");
|
||||
try (InputStream downloadStream = response.getEntity().getContent(); FileOutputStream fos = new FileOutputStream(outputFile)) {
|
||||
|
||||
if (downloadJob.isStopped()) {
|
||||
return;
|
||||
}
|
||||
|
||||
image.setTotal(response.getEntity().getContentLength());
|
||||
logger.debug(String.format("%s length is %d", imageFileData.getImageUrl(), image.getTotal()));
|
||||
logger.debug(String.format("Starting data transfer for %s", imageFileData.getImageUrl()));
|
||||
dataService.updateImageTotal(image.getTotal(), image.getId());
|
||||
|
||||
log.debug(String.format("%s length is %d", imageFileData.getImageUrl(), image.getTotal()));
|
||||
log.debug(String.format("Starting data transfer for %s", imageFileData.getImageUrl()));
|
||||
|
||||
byte[] buffer = new byte[READ_BUFFER_SIZE];
|
||||
int read;
|
||||
while ((read = downloadStream.read(buffer, 0, READ_BUFFER_SIZE)) != -1) {
|
||||
while ((read = downloadStream.read(buffer, 0, READ_BUFFER_SIZE)) != -1 && !downloadJob.isStopped()) {
|
||||
fos.write(buffer, 0, read);
|
||||
image.increase(read);
|
||||
downloadSpeedService.increase(read);
|
||||
dataService.updateImageCurrent(image.getCurrent(), image.getId());
|
||||
}
|
||||
fos.flush();
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
if (downloadJob.isStopped()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
checkImageTypeAndRename(outputFile, imageFileData.getImageName(), image.getIndex());
|
||||
File finalName = checkImageTypeAndRename(dataService.findPostById(post.getId()).orElseThrow(), outputFile, imageFileData.getImageName(), image.getIndex());
|
||||
imageFileData.setFileName(finalName.getName());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (Thread.interrupted()) {
|
||||
throw new InterruptedException("Download was interrupted");
|
||||
}
|
||||
throw new DownloadException(e);
|
||||
} finally {
|
||||
if (image.getCurrent() == image.getTotal()) {
|
||||
image.setStatus(Status.COMPLETE);
|
||||
} else if (downloadJob.isStopped()) {
|
||||
image.setStatus(Status.STOPPED);
|
||||
} else {
|
||||
image.setStatus(Status.ERROR);
|
||||
}
|
||||
dataService.updateImageStatus(image.getStatus(), image.getId());
|
||||
downloadJob.done();
|
||||
}
|
||||
}
|
||||
|
||||
private void checkImageTypeAndRename(File outputFile, String imageName, int index) throws HostException {
|
||||
String formatName;
|
||||
private File checkImageTypeAndRename(Post post, File outputFile, String imageName, int index) throws HostException {
|
||||
try (ImageInputStream iis = ImageIO.createImageInputStream(outputFile)) {
|
||||
Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
|
||||
if (!it.hasNext()) {
|
||||
throw new HostException("Image file is not recognized!");
|
||||
}
|
||||
ImageReader reader = it.next();
|
||||
formatName = reader.getFormatName();
|
||||
if (formatName.toUpperCase().equals("JPEG")) {
|
||||
formatName = "jpg";
|
||||
if (reader.getFormatName().toUpperCase().equals("JPEG")) {
|
||||
String imageNameLC = imageName.toLowerCase();
|
||||
if (!imageNameLC.endsWith("_jpg") && !imageNameLC.endsWith("_jpeg")) {
|
||||
imageName += ".jpg";
|
||||
} else {
|
||||
String toReplace = null;
|
||||
if (imageNameLC.endsWith("_jpg")) {
|
||||
toReplace = "_jpg";
|
||||
} else if (imageNameLC.endsWith("_jpeg")) {
|
||||
toReplace = "_jpeg";
|
||||
}
|
||||
if (toReplace != null) {
|
||||
imageName = imageName.substring(0, imageName.length() - toReplace.length()) + ".jpg";
|
||||
}
|
||||
}
|
||||
} else if (reader.getFormatName().toUpperCase().equals("PNG")) {
|
||||
String imageNameLC = imageName.toLowerCase();
|
||||
if (!imageNameLC.endsWith("_png")) {
|
||||
imageName += ".png";
|
||||
} else {
|
||||
String toReplace = null;
|
||||
if (imageNameLC.endsWith("_png")) {
|
||||
toReplace = "_png";
|
||||
}
|
||||
if (toReplace != null) {
|
||||
imageName = imageName.substring(0, imageName.length() - toReplace.length()) + ".png";
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new HostException("Failed to guess image format", e);
|
||||
}
|
||||
try {
|
||||
File outImage = new File(outputFile.getParent(), (appSettingsService.isForceOrder() ? String.format("%03d_", index) : "") + imageName + "." + formatName.toLowerCase());
|
||||
File downloadDestinationFolder = pathService.getDownloadDestinationFolder(post);
|
||||
File outImage = new File(downloadDestinationFolder, (appSettingsService.getSettings().getForceOrder() ? String.format("%03d_", index) : "") + imageName);
|
||||
if (outImage.exists() && outImage.delete()) {
|
||||
logger.debug(String.format("%s is deleted", outImage.toString()));
|
||||
log.debug(String.format("%s is deleted", outImage.toString()));
|
||||
}
|
||||
Files.move(outputFile.toPath(), outImage.toPath());
|
||||
return Files.move(outputFile.toPath(), outImage.toPath(), StandardCopyOption.ATOMIC_MOVE).toFile();
|
||||
} catch (Exception e) {
|
||||
throw new HostException("Failed to rename the image", e);
|
||||
}
|
||||
@@ -167,7 +239,7 @@ abstract public class Host {
|
||||
|
||||
final String getDefaultImageName(final String imgUrl) {
|
||||
String imageTitle = imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
|
||||
logger.debug(String.format("Extracting name from url %s: %s", imgUrl, imageTitle));
|
||||
log.debug(String.format("Extracting name from url %s: %s", imgUrl, imageTitle));
|
||||
return imgUrl;
|
||||
}
|
||||
|
||||
@@ -177,21 +249,21 @@ abstract public class Host {
|
||||
HttpClient client = cm.getClient().build();
|
||||
HttpGet httpGet = cm.buildHttpGet(url);
|
||||
Header[] headers;
|
||||
logger.debug(String.format("Requesting %s", url));
|
||||
log.debug(String.format("Requesting %s", url));
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpGet, context)) {
|
||||
if (response.getStatusLine().getStatusCode() / 100 != 2) {
|
||||
throw new HostException(String.format("Unexpected response code: %d", response.getStatusLine().getStatusCode()));
|
||||
}
|
||||
headers = response.getAllHeaders();
|
||||
basePage = EntityUtils.toString(response.getEntity());
|
||||
logger.debug(String.format("%s response: %n%s", url, basePage));
|
||||
log.debug(String.format("%s response: %n%s", url, basePage));
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
} catch (IOException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(String.format("Cleaning %s response", url));
|
||||
log.debug(String.format("Cleaning %s response", url));
|
||||
return new Response(htmlProcessorService.clean(basePage), headers);
|
||||
} catch (HtmlProcessorException e) {
|
||||
throw new HostException(e);
|
||||
@@ -220,15 +292,29 @@ abstract public class Host {
|
||||
|
||||
protected abstract void setNameAndUrl(final String url, final ImageFileData imageFileData, final HttpClientContext context) throws HostException;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Host host = (Host) o;
|
||||
return Objects.equals(getHost(), host.getHost());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getHost());
|
||||
}
|
||||
|
||||
@Getter
|
||||
public static class Response {
|
||||
|
||||
protected Response(Document document, Header[] headers) {
|
||||
this.document = document;
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
private Document document;
|
||||
private Header[] headers;
|
||||
private final Document document;
|
||||
private final Header[] headers;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
@@ -20,10 +19,9 @@ import tn.mnlr.vripper.services.ConnectionManager;
|
||||
import java.io.IOException;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ImageBamHost extends Host {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImageBamHost.class);
|
||||
|
||||
private static final String host = "imagebam.com";
|
||||
private static final String CONTINUE_BUTTON_XPATH = "//a[@title='Continue to your image']";
|
||||
private static final String IMG_XPATH = "//img[@class='image']";
|
||||
@@ -31,6 +29,10 @@ public class ImageBamHost extends Host {
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
|
||||
public ImageBamHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
return host;
|
||||
@@ -49,22 +51,22 @@ public class ImageBamHost extends Host {
|
||||
|
||||
Node contDiv;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", CONTINUE_BUTTON_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", CONTINUE_BUTTON_XPATH, url));
|
||||
contDiv = xpathService.getAsNode(doc, CONTINUE_BUTTON_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
if (contDiv != null) {
|
||||
logger.debug(String.format("Click button found for %s", url));
|
||||
log.debug(String.format("Click button found for %s", url));
|
||||
HttpClient client = cm.getClient().build();
|
||||
HttpGet httpGet = cm.buildHttpGet(url);
|
||||
httpGet.addHeader("Referer", url);
|
||||
logger.debug(String.format("Requesting %s", httpGet));
|
||||
log.debug(String.format("Requesting %s", httpGet));
|
||||
try (CloseableHttpResponse res = (CloseableHttpResponse) client.execute(httpGet, context)) {
|
||||
String s = EntityUtils.toString(res.getEntity());
|
||||
logger.debug(String.format("%s response is:%n%s", httpGet, s));
|
||||
logger.debug(String.format("Cleaning response for %s", httpGet));
|
||||
log.debug(String.format("%s response is:%n%s", httpGet, s));
|
||||
log.debug(String.format("Cleaning response for %s", httpGet));
|
||||
doc = htmlProcessorService.clean(s);
|
||||
EntityUtils.consumeQuietly(res.getEntity());
|
||||
} catch (IOException | HtmlProcessorException e) {
|
||||
@@ -74,20 +76,20 @@ public class ImageBamHost extends Host {
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(String.format("Resolving name and image url for %s", url));
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = imgNode.getAttributes().getNamedItem("id").getTextContent().trim();
|
||||
String imgUrl = imgNode.getAttributes().getNamedItem("src").getTextContent().trim();
|
||||
|
||||
imageFileData.setImageUrl(imgUrl);
|
||||
imageFileData.setImageName(imgTitle.isEmpty() ? imgUrl.substring(imgUrl.lastIndexOf('/') + 1) : imgTitle);
|
||||
} catch(Exception e) {
|
||||
} catch (Exception e) {
|
||||
throw new HostException("Unexpected error occurred", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
import tn.mnlr.vripper.services.ConnectionManager;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ImageTwistHost extends Host {
|
||||
|
||||
private static final String IMG_XPATH = "//img[contains(@class, 'img')]";
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImageTwistHost.class);
|
||||
private static final String host = "imagetwist.com";
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
|
||||
public ImageTwistHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
@@ -40,14 +39,14 @@ public class ImageTwistHost extends Host {
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(String.format("Resolving name and image url for %s", url));
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = Optional.ofNullable(imgNode.getAttributes().getNamedItem("alt")).map(Node::getTextContent).map(String::trim).orElse(null);
|
||||
String imgUrl = imgNode.getAttributes().getNamedItem("src").getTextContent().trim();
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ImageVenueHost extends Host {
|
||||
|
||||
private static final String host = "imagevenue.com";
|
||||
private static final String CONTINUE_BUTTON_XPATH = "//a[@title='Continue to ImageVenue']";
|
||||
private static final String IMG_XPATH = "//a[@data-toggle='full']/img";
|
||||
|
||||
public ImageVenueHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLookup() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setNameAndUrl(final String _url, final ImageFileData imageFileData, final HttpClientContext context) throws HostException {
|
||||
|
||||
String url = _url.replace("http://", "https://");
|
||||
|
||||
Response resp = getResponse(url, context);
|
||||
Document doc = resp.getDocument();
|
||||
|
||||
try {
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", CONTINUE_BUTTON_XPATH, url));
|
||||
if (xpathService.getAsNode(doc, CONTINUE_BUTTON_XPATH) != null) {
|
||||
//Button detected. No need to actually click it, just make the call again.
|
||||
resp = getResponse(url, context);
|
||||
doc = resp.getDocument();
|
||||
}
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
if (imgNode == null) {
|
||||
throw new HostException("Failed to locate image");
|
||||
}
|
||||
|
||||
try {
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = imgNode.getAttributes().getNamedItem("alt").getTextContent().trim();
|
||||
String imgUrl = imgNode.getAttributes().getNamedItem("src").getTextContent().trim();
|
||||
|
||||
imageFileData.setImageUrl(imgUrl);
|
||||
imageFileData.setImageName(imgTitle.isEmpty() ? imgUrl.substring(imgUrl.lastIndexOf('/') + 1) : imgTitle);
|
||||
} catch (Exception e) {
|
||||
throw new HostException("Unexpected error occurred", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,25 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
import tn.mnlr.vripper.services.ConnectionManager;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ImageZillaHost extends Host {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImageZillaHost.class);
|
||||
|
||||
private static final String host = "imagezilla.net";
|
||||
private static final String lookup = "imagezilla.net/show";
|
||||
private static final String IMG_XPATH = "//img[@id='photo']";
|
||||
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
public ImageZillaHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
@@ -41,10 +38,10 @@ public class ImageZillaHost extends Host {
|
||||
|
||||
String title;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
Node titleNode = xpathService.getAsNode(doc, IMG_XPATH).getAttributes().getNamedItem("title");
|
||||
logger.debug(String.format("Resolving name for %s", url));
|
||||
if(titleNode != null) {
|
||||
log.debug(String.format("Resolving name for %s", url));
|
||||
if (titleNode != null) {
|
||||
title = titleNode.getTextContent().trim();
|
||||
} else {
|
||||
title = null;
|
||||
@@ -53,7 +50,7 @@ public class ImageZillaHost extends Host {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
if(title == null || title.isEmpty()) {
|
||||
if (title == null || title.isEmpty()) {
|
||||
title = getDefaultImageName(url);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ImgSpiceHost extends Host {
|
||||
|
||||
private static final String host = "imgspice.com";
|
||||
private static final String IMG_XPATH = "//img[@id='imgpreview']";
|
||||
|
||||
public ImgSpiceHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLookup() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setNameAndUrl(final String _url, final ImageFileData imageFileData, final HttpClientContext context) throws HostException {
|
||||
|
||||
String url = _url.replace("http://", "https://");
|
||||
Response resp = getResponse(url, context);
|
||||
Document doc = resp.getDocument();
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = imgNode.getAttributes().getNamedItem("alt").getTextContent().trim();
|
||||
String imgUrl = imgNode.getAttributes().getNamedItem("src").getTextContent().trim();
|
||||
|
||||
imageFileData.setImageUrl(imgUrl);
|
||||
imageFileData.setImageName(imgTitle.isEmpty() ? imgUrl.substring(imgUrl.lastIndexOf('/') + 1) : imgTitle);
|
||||
} catch (Exception e) {
|
||||
throw new HostException("Unexpected error occurred", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
@@ -13,16 +12,19 @@ import tn.mnlr.vripper.q.ImageFileData;
|
||||
import tn.mnlr.vripper.services.ConnectionManager;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ImgboxHost extends Host {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImgboxHost.class);
|
||||
|
||||
private static final String host = "imgbox.com";
|
||||
private static final String IMG_XPATH = "//img[@id='img']";
|
||||
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
|
||||
public ImgboxHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
return host;
|
||||
@@ -40,14 +42,14 @@ public class ImgboxHost extends Host {
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(String.format("Resolving name and image url for %s", url));
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = imgNode.getAttributes().getNamedItem("title").getTextContent().trim();
|
||||
String imgUrl = imgNode.getAttributes().getNamedItem("src").getTextContent().trim();
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
@@ -8,8 +9,6 @@ import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
@@ -25,10 +24,9 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ImxHost extends Host {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImxHost.class);
|
||||
|
||||
private static final String host = "imx.to";
|
||||
private static final String CONTINUE_BUTTON_XPATH = "//*[@name='imgContinue']";
|
||||
private static final String IMG_XPATH = "//img[@class='centred']";
|
||||
@@ -56,7 +54,7 @@ public class ImxHost extends Host {
|
||||
Node contDiv;
|
||||
String value = null;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", CONTINUE_BUTTON_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", CONTINUE_BUTTON_XPATH, url));
|
||||
contDiv = xpathService.getAsNode(doc, CONTINUE_BUTTON_XPATH);
|
||||
Node node = contDiv.getAttributes().getNamedItem("value");
|
||||
if (node != null) {
|
||||
@@ -69,7 +67,7 @@ public class ImxHost extends Host {
|
||||
if (value == null) {
|
||||
throw new HostException("Failed to obtain value attribute from continue input");
|
||||
}
|
||||
logger.debug(String.format("Click button found for %s", url));
|
||||
log.debug(String.format("Click button found for %s", url));
|
||||
HttpClient client = cm.getClient().build();
|
||||
HttpPost httpPost = cm.buildHttpPost(url);
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
@@ -79,9 +77,9 @@ public class ImxHost extends Host {
|
||||
} catch (Exception e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
logger.debug(String.format("Requesting %s", httpPost));
|
||||
log.debug(String.format("Requesting %s", httpPost));
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpPost, context)) {
|
||||
logger.debug(String.format("Cleaning response for %s", httpPost));
|
||||
log.debug(String.format("Cleaning response for %s", httpPost));
|
||||
doc = htmlProcessorService.clean(EntityUtils.toString(response.getEntity()));
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
} catch (IOException | HtmlProcessorException e) {
|
||||
@@ -90,20 +88,20 @@ public class ImxHost extends Host {
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(String.format("Resolving name and image url for %s", url));
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = imgNode.getAttributes().getNamedItem("alt").getTextContent().trim();
|
||||
String imgUrl = imgNode.getAttributes().getNamedItem("src").getTextContent().trim();
|
||||
|
||||
imageFileData.setImageUrl(imgUrl);
|
||||
imageFileData.setImageName(imgTitle.isEmpty() ? imgUrl.substring(imgUrl.lastIndexOf('/') + 1) : imgTitle);
|
||||
} catch(Exception e) {
|
||||
} catch (Exception e) {
|
||||
throw new HostException("Unexpected error occurred", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,24 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
import tn.mnlr.vripper.services.ConnectionManager;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PimpandhostHost extends Host {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PimpandhostHost.class);
|
||||
|
||||
private static final String host = "pimpandhost.com";
|
||||
private static final String IMG_XPATH = "//img[contains(@class, 'original')]";
|
||||
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
public PimpandhostHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
@@ -48,14 +45,14 @@ public class PimpandhostHost extends Host {
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(String.format("Resolving name and image url for %s", url));
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = imgNode.getAttributes().getNamedItem("alt").getTextContent().trim();
|
||||
String imgUrl = "https:" + imgNode.getAttributes().getNamedItem("src").getTextContent().trim();
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PixRouteHost extends Host {
|
||||
|
||||
private static final String host = "pixroute.com";
|
||||
private static final String IMG_XPATH = "//img[@id='imgpreview']";
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLookup() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setNameAndUrl(final String _url, final ImageFileData imageFileData, final HttpClientContext context) throws HostException {
|
||||
|
||||
String url = _url.replace("http://", "https://");
|
||||
Document doc = getResponse(url, context).getDocument();
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
if (imgNode == null) {
|
||||
throw new HostException("Failed to locate image");
|
||||
}
|
||||
|
||||
try {
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
|
||||
imageFileData.setImageUrl(imgNode.getAttributes().getNamedItem("src").getTextContent().trim());
|
||||
imageFileData.setImageName(imgNode.getAttributes().getNamedItem("alt").getTextContent().trim());
|
||||
} catch (Exception e) {
|
||||
throw new HostException("Unexpected error occurred", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,25 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
import tn.mnlr.vripper.services.ConnectionManager;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PixhostHost extends Host {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PixhostHost.class);
|
||||
|
||||
private static final String host = "pixhost.to";
|
||||
private static final String lookup = "pixhost.to/show";
|
||||
private static final String IMG_XPATH = "//img[@id='image']";
|
||||
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
public PixhostHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
@@ -41,14 +38,14 @@ public class PixhostHost extends Host {
|
||||
|
||||
Node imgNode;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(String.format("Resolving name and image url for %s", url));
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = imgNode.getAttributes().getNamedItem("alt").getTextContent().trim();
|
||||
String imgUrl = imgNode.getAttributes().getNamedItem("src").getTextContent().trim();
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PixxxelsHost extends Host {
|
||||
|
||||
private static final String host = "pixxxels.cc";
|
||||
private static final String IMG_XPATH = "//*[@id='download']";
|
||||
private static final String TITLE_XPATH = "//*[contains(@class,'imagename')]";
|
||||
|
||||
public PixxxelsHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLookup() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setNameAndUrl(final String _url, final ImageFileData imageFileData, final HttpClientContext context) throws HostException {
|
||||
|
||||
String url = _url.replace("http://", "https://");
|
||||
Response resp = getResponse(url, context);
|
||||
Document doc = resp.getDocument();
|
||||
|
||||
Node imgNode, titleNode;
|
||||
try {
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
imgNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", TITLE_XPATH, url));
|
||||
titleNode = xpathService.getAsNode(doc, TITLE_XPATH);
|
||||
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = titleNode.getTextContent().trim();
|
||||
String imgUrl = imgNode.getAttributes().getNamedItem("href").getTextContent().trim();
|
||||
|
||||
imageFileData.setImageUrl(imgUrl);
|
||||
imageFileData.setImageName(imgTitle.isEmpty() ? imgUrl.substring(imgUrl.lastIndexOf('/') + 1) : imgTitle);
|
||||
} catch (Exception e) {
|
||||
throw new HostException("Unexpected error occurred", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PostImgHost extends Host {
|
||||
|
||||
private static final String host = "postimg.cc";
|
||||
private static final String TITLE_XPATH = "//span[contains(@class,'imagename')]";
|
||||
private static final String IMG_XPATH = "//a[@id='download']";
|
||||
|
||||
public PostImgHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLookup() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setNameAndUrl(final String _url, final ImageFileData imageFileData, final HttpClientContext context) throws HostException {
|
||||
|
||||
String url = _url.replace("http://", "https://");
|
||||
Document doc = getResponse(url, context).getDocument();
|
||||
|
||||
Node urlNode, titleNode;
|
||||
try {
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", TITLE_XPATH, url));
|
||||
titleNode = xpathService.getAsNode(doc, TITLE_XPATH);
|
||||
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", IMG_XPATH, url));
|
||||
urlNode = xpathService.getAsNode(doc, IMG_XPATH);
|
||||
} catch (XpathException e) {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
log.debug(String.format("Resolving name and image url for %s", url));
|
||||
String imgTitle = Optional.ofNullable(titleNode).map(node -> node.getTextContent().trim()).orElseGet(() -> getDefaultImageName(url));
|
||||
|
||||
imageFileData.setImageUrl(urlNode.getAttributes().getNamedItem("href").getTextContent().trim());
|
||||
imageFileData.setImageName(imgTitle);
|
||||
} catch (Exception e) {
|
||||
throw new HostException("Unexpected error occurred", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,25 @@
|
||||
package tn.mnlr.vripper.host;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.exception.HostException;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
import tn.mnlr.vripper.q.ImageFileData;
|
||||
import tn.mnlr.vripper.services.ConnectionManager;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class TurboImageHost extends Host {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(TurboImageHost.class);
|
||||
|
||||
private static final String host = "turboimagehost.com";
|
||||
private static final String TITLE_XPATH = "//div[contains(@class,'titleFullS')]/h1";
|
||||
private static final String IMG_XPATH = "//img[@id='uImage']";
|
||||
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
public TurboImageHost() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHost() {
|
||||
@@ -41,10 +38,10 @@ public class TurboImageHost extends Host {
|
||||
|
||||
String title;
|
||||
try {
|
||||
logger.debug(String.format("Looking for xpath expression %s in %s", TITLE_XPATH, url));
|
||||
log.debug(String.format("Looking for xpath expression %s in %s", TITLE_XPATH, url));
|
||||
Node titleNode = xpathService.getAsNode(doc, TITLE_XPATH);
|
||||
logger.debug(String.format("Resolving name for %s", url));
|
||||
if(titleNode != null) {
|
||||
log.debug(String.format("Resolving name for %s", url));
|
||||
if (titleNode != null) {
|
||||
title = titleNode.getTextContent().trim();
|
||||
} else {
|
||||
title = null;
|
||||
@@ -53,7 +50,7 @@ public class TurboImageHost extends Host {
|
||||
throw new HostException(e);
|
||||
}
|
||||
|
||||
if(title == null || title.isEmpty()) {
|
||||
if (title == null || title.isEmpty()) {
|
||||
title = getDefaultImageName(url);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package tn.mnlr.vripper.jpa;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.File;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Component
|
||||
@EnableScheduling
|
||||
public class Management {
|
||||
|
||||
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
private static final Pattern BACKUP_FILE_PATTERN = Pattern.compile("^db_(\\d{4}-\\d{2}-\\d{2})\\.tar\\.gz$");
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final String backupFolder;
|
||||
|
||||
@Autowired
|
||||
public Management(JdbcTemplate jdbcTemplate, @Value("${base.dir}") String baseDir) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.backupFolder = baseDir + File.separator + ".vripper" + File.separator + "backup";
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
@Scheduled(cron = "0 0 0 ? * *")
|
||||
private void backup() {
|
||||
|
||||
for (File file : Optional.ofNullable(new File(backupFolder).listFiles()).orElse(new File[]{})) {
|
||||
Matcher matcher = BACKUP_FILE_PATTERN.matcher(file.getName());
|
||||
if (matcher.find()) {
|
||||
LocalDate localDate = LocalDate.parse(matcher.group(1), FORMATTER);
|
||||
if (localDate.isEqual(LocalDate.now())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// create a backup file
|
||||
File backupFile = new File(backupFolder, String.format("db_%s.tar.gz", LocalDateTime.now().format(FORMATTER)));
|
||||
jdbcTemplate.execute(String.format("BACKUP DATABASE TO '%s' BLOCKING", backupFile.getPath()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package tn.mnlr.vripper.jpa.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
public class Image {
|
||||
|
||||
@JsonIgnore
|
||||
protected Long id;
|
||||
|
||||
@JsonIgnore
|
||||
private Host host;
|
||||
|
||||
private String url;
|
||||
|
||||
private int index;
|
||||
|
||||
private long current = 0;
|
||||
|
||||
private long total = 0;
|
||||
|
||||
private Status status;
|
||||
|
||||
private String postId;
|
||||
|
||||
@JsonIgnore
|
||||
private Long postIdRef;
|
||||
|
||||
public Image(String postId, String url, Host host, int index) {
|
||||
this.postId = postId;
|
||||
this.url = url;
|
||||
this.host = host;
|
||||
this.index = index;
|
||||
status = Status.STOPPED;
|
||||
}
|
||||
|
||||
|
||||
public void increase(int read) {
|
||||
current += read;
|
||||
}
|
||||
|
||||
public void init() {
|
||||
current = 0;
|
||||
status = Status.STOPPED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Image image = (Image) o;
|
||||
return Objects.equals(url, image.url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(url);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package tn.mnlr.vripper.jpa.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class Metadata {
|
||||
|
||||
@JsonIgnore
|
||||
private Long id;
|
||||
|
||||
private List<String> resolvedNames = Collections.emptyList();
|
||||
|
||||
private String postedBy;
|
||||
|
||||
private Long postIdRef;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package tn.mnlr.vripper.jpa.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
public class Post {
|
||||
|
||||
@JsonIgnore
|
||||
private Long id;
|
||||
|
||||
private Status status;
|
||||
|
||||
private String postId;
|
||||
|
||||
private String threadTitle;
|
||||
|
||||
private String threadId;
|
||||
|
||||
private String title;
|
||||
|
||||
private String url;
|
||||
|
||||
private int done;
|
||||
|
||||
private int total;
|
||||
|
||||
private Set<String> hosts;
|
||||
|
||||
private String forum;
|
||||
|
||||
@JsonIgnore
|
||||
private String securityToken;
|
||||
|
||||
@JsonIgnore
|
||||
private String postFolderName;
|
||||
|
||||
private boolean thanked;
|
||||
|
||||
private Set<String> previews = Collections.emptySet();
|
||||
|
||||
private Metadata metadata;
|
||||
|
||||
public Post(String title, String url, String postId, String threadId, String threadTitle, String forum, String securityToken) {
|
||||
this.title = title;
|
||||
this.url = url;
|
||||
this.postId = postId;
|
||||
this.forum = forum;
|
||||
this.threadId = threadId;
|
||||
this.threadTitle = threadTitle;
|
||||
this.securityToken = securityToken;
|
||||
status = Status.STOPPED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Post post = (Post) o;
|
||||
return Objects.equals(postId, post.postId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(postId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package tn.mnlr.vripper.jpa.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@ToString
|
||||
public class Queued {
|
||||
|
||||
@JsonIgnore
|
||||
private Long id;
|
||||
|
||||
private String link;
|
||||
|
||||
private String threadId;
|
||||
|
||||
private String postId;
|
||||
|
||||
private int total = 0;
|
||||
|
||||
private boolean loading = true;
|
||||
|
||||
public Queued(String link, String threadId, String postId) {
|
||||
this();
|
||||
this.link = link;
|
||||
this.threadId = threadId;
|
||||
this.postId = postId;
|
||||
}
|
||||
|
||||
public void done() {
|
||||
this.loading = false;
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
this.total++;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Queued that = (Queued) o;
|
||||
return Objects.equals(threadId, that.threadId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(threadId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package tn.mnlr.vripper.jpa.domain.enums;
|
||||
|
||||
public enum Status {
|
||||
PENDING, DOWNLOADING, COMPLETE, ERROR, STOPPED, PARTIAL
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package tn.mnlr.vripper.jpa.repositories;
|
||||
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface IImageRepository extends IRepository {
|
||||
|
||||
Image save(Image image);
|
||||
|
||||
void deleteAllByPostId(String postId);
|
||||
|
||||
List<Image> findByPostId(String postId);
|
||||
|
||||
Integer countError();
|
||||
|
||||
List<Image> findByPostIdAndIsNotCompleted(String postId);
|
||||
|
||||
int stopByPostIdAndIsNotCompleted(String postId);
|
||||
|
||||
List<Image> findByPostIdAndIsError(String postId);
|
||||
|
||||
Optional<Image> findById(Long id);
|
||||
|
||||
int updateStatus(Status status, Long id);
|
||||
|
||||
int updateCurrent(long current, Long id);
|
||||
|
||||
int updateTotal(long total, Long id);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package tn.mnlr.vripper.jpa.repositories;
|
||||
|
||||
import tn.mnlr.vripper.jpa.domain.Metadata;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface IMetadataRepository extends IRepository {
|
||||
|
||||
Metadata save(Metadata metadata);
|
||||
|
||||
Optional<Metadata> findById(Long id);
|
||||
|
||||
Optional<Metadata> findByPostId(String postId);
|
||||
|
||||
int deleteByPostId(String postId);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package tn.mnlr.vripper.jpa.repositories;
|
||||
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface IPostRepository extends IRepository {
|
||||
|
||||
Post save(Post post);
|
||||
|
||||
int delete(Long id);
|
||||
|
||||
Optional<Post> findByPostId(String postId);
|
||||
|
||||
List<String> findCompleted();
|
||||
|
||||
Optional<Post> findById(Long id);
|
||||
|
||||
List<Post> findAll();
|
||||
|
||||
boolean existByPostId(String postId);
|
||||
|
||||
int setDownloadingToStopped();
|
||||
|
||||
int deleteByPostId(String postId);
|
||||
|
||||
int updateStatus(Status status, Long id);
|
||||
|
||||
int updateDone(int done, Long id);
|
||||
|
||||
int updateFolderName(String postFolderName, Long id);
|
||||
|
||||
int updateTitle(String title, Long id);
|
||||
|
||||
int updateThanked(boolean thanked, Long id);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package tn.mnlr.vripper.jpa.repositories;
|
||||
|
||||
import tn.mnlr.vripper.jpa.domain.Queued;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface IQueuedRepository extends IRepository {
|
||||
Queued save(Queued queued);
|
||||
|
||||
Optional<Queued> findByThreadId(String threadId);
|
||||
|
||||
List<Queued> findAll();
|
||||
|
||||
Optional<Queued> findById(Long id);
|
||||
|
||||
int deleteByThreadId(String threadId);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package tn.mnlr.vripper.jpa.repositories;
|
||||
|
||||
public interface IRepository {
|
||||
|
||||
public void init();
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package tn.mnlr.vripper.jpa.repositories.impl;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
import tn.mnlr.vripper.jpa.repositories.IImageRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Service
|
||||
public class ImageRepository implements IImageRepository {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final AtomicLong counter = new AtomicLong(0);
|
||||
|
||||
@Autowired
|
||||
public ImageRepository(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
Long maxId = jdbcTemplate.queryForObject(
|
||||
"SELECT MAX(ID) FROM IMAGE",
|
||||
Long.class
|
||||
);
|
||||
if (maxId == null) {
|
||||
maxId = 0L;
|
||||
}
|
||||
counter.set(maxId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Image save(Image image) {
|
||||
long id = counter.incrementAndGet();
|
||||
jdbcTemplate.update(
|
||||
"INSERT INTO IMAGE (ID, CURRENT, HOST, INDEX, POST_ID, STATUS, TOTAL, URL, POST_ID_REF) VALUES (?,?,?,?,?,?,?,?,?)",
|
||||
id,
|
||||
image.getCurrent(),
|
||||
image.getHost().getHost(),
|
||||
image.getIndex(),
|
||||
image.getPostId(),
|
||||
image.getStatus().name(),
|
||||
image.getTotal(),
|
||||
image.getUrl(),
|
||||
image.getPostIdRef()
|
||||
);
|
||||
image.setId(id);
|
||||
return image;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAllByPostId(String postId) {
|
||||
jdbcTemplate.update("DELETE FROM IMAGE WHERE POST_ID = ?", postId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Image> findByPostId(String postId) {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT * FROM IMAGE WHERE POST_ID = ?",
|
||||
new Object[]{postId},
|
||||
new ImageRowMapper()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer countError() {
|
||||
return jdbcTemplate.queryForObject(
|
||||
"SELECT COUNT(*) FROM IMAGE AS image WHERE image.STATUS = 'ERROR'",
|
||||
Integer.class
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Image> findByPostIdAndIsNotCompleted(String postId) {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT * FROM IMAGE AS image WHERE image.POST_ID = ? AND image.STATUS <> 'COMPLETE'",
|
||||
new Object[]{postId},
|
||||
new ImageRowMapper()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int stopByPostIdAndIsNotCompleted(String postId) {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE IMAGE AS image SET image.STATUS = 'STOPPED' WHERE image.POST_ID = ? AND image.STATUS <> 'COMPLETE'",
|
||||
postId
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Image> findByPostIdAndIsError(String postId) {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT * FROM IMAGE AS image WHERE image.POST_ID = ? AND image.STATUS = 'ERROR'",
|
||||
new Object[]{postId},
|
||||
new ImageRowMapper()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Image> findById(Long id) {
|
||||
List<Image> images = jdbcTemplate.query(
|
||||
"SELECT * FROM IMAGE AS image WHERE image.ID = ?",
|
||||
new Object[]{id},
|
||||
new ImageRowMapper()
|
||||
);
|
||||
if (images.isEmpty()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return Optional.of(images.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateStatus(Status status, Long id) {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE IMAGE AS image SET image.STATUS = ? WHERE image.ID = ?",
|
||||
status.name(), id
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateCurrent(long current, Long id) {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE IMAGE AS image SET image.CURRENT = ? WHERE image.ID = ?",
|
||||
current, id
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateTotal(long total, Long id) {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE IMAGE AS image SET image.TOTAL = ? WHERE image.ID = ?",
|
||||
total, id
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package tn.mnlr.vripper.jpa.repositories.impl;
|
||||
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import tn.mnlr.vripper.SpringContext;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class ImageRowMapper implements RowMapper<Image> {
|
||||
|
||||
@Override
|
||||
public Image mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
Image image = new Image();
|
||||
image.setId(rs.getLong("ID"));
|
||||
String host = rs.getString("HOST");
|
||||
image.setHost(SpringContext.getBeansOfType(Host.class).values().stream().filter(e -> e.getHost().equals(host)).findAny().orElse(null));
|
||||
image.setUrl(rs.getString("URL"));
|
||||
image.setIndex(rs.getInt("INDEX"));
|
||||
image.setCurrent(rs.getLong("CURRENT"));
|
||||
image.setTotal(rs.getLong("TOTAL"));
|
||||
image.setStatus(Status.valueOf(rs.getString("STATUS")));
|
||||
image.setPostId(rs.getString("POST_ID"));
|
||||
image.setPostIdRef(rs.getLong("POST_ID_REF"));
|
||||
return image;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package tn.mnlr.vripper.jpa.repositories.impl;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.jpa.domain.Metadata;
|
||||
import tn.mnlr.vripper.jpa.repositories.IMetadataRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Service
|
||||
public class MetadataRepository implements IMetadataRepository {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final AtomicLong counter = new AtomicLong(0);
|
||||
|
||||
@Autowired
|
||||
public MetadataRepository(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
Long maxId = jdbcTemplate.queryForObject(
|
||||
"SELECT MAX(ID) FROM IMAGE",
|
||||
Long.class
|
||||
);
|
||||
if (maxId == null) {
|
||||
maxId = 0L;
|
||||
}
|
||||
counter.set(maxId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Metadata save(Metadata metadata) {
|
||||
long id = counter.incrementAndGet();
|
||||
jdbcTemplate.update(
|
||||
"INSERT INTO METADATA (ID, POSTED_BY, RESOLVED_NAMES, POST_ID_REF) VALUES (?,?,?,?)",
|
||||
id,
|
||||
metadata.getPostedBy(),
|
||||
String.join("%sep%", metadata.getResolvedNames()),
|
||||
metadata.getPostIdRef()
|
||||
);
|
||||
metadata.setId(id);
|
||||
return metadata;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Metadata> findById(Long id) {
|
||||
List<Metadata> metadata = jdbcTemplate.query(
|
||||
"SELECT * FROM METADATA AS metadata WHERE metadata.ID = ?",
|
||||
new Object[]{id},
|
||||
new MetadataRowMapper()
|
||||
);
|
||||
if (metadata.isEmpty()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return Optional.of(metadata.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Metadata> findByPostId(String postId) {
|
||||
List<Metadata> metadata = jdbcTemplate.query(
|
||||
"SELECT metadata.* FROM METADATA AS metadata INNER JOIN POST post ON post.ID = metadata.POST_ID_REF WHERE post.POST_ID = ?",
|
||||
new Object[]{postId},
|
||||
new MetadataRowMapper()
|
||||
);
|
||||
if (metadata.isEmpty()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return Optional.of(metadata.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteByPostId(String postId) {
|
||||
return jdbcTemplate.update(
|
||||
"DELETE FROM METADATA WHERE POST_ID_REF = (SELECT post.ID FROM POST AS post INNER JOIN METADATA metadata ON post.ID = metadata.POST_ID_REF WHERE post.POST_ID = ?)",
|
||||
postId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package tn.mnlr.vripper.jpa.repositories.impl;
|
||||
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import tn.mnlr.vripper.jpa.domain.Metadata;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public class MetadataRowMapper implements RowMapper<Metadata> {
|
||||
|
||||
@Override
|
||||
public Metadata mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
Metadata metadata = new Metadata();
|
||||
metadata.setId(rs.getLong("ID"));
|
||||
metadata.setPostedBy(rs.getString("POSTED_BY"));
|
||||
String resolvedNames = rs.getString("RESOLVED_NAMES");
|
||||
if (resolvedNames != null && !resolvedNames.isBlank()) {
|
||||
metadata.setResolvedNames(List.of(resolvedNames.split("%sep%")));
|
||||
}
|
||||
metadata.setPostIdRef(rs.getLong("POST_ID_REF"));
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package tn.mnlr.vripper.jpa.repositories.impl;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
import tn.mnlr.vripper.jpa.repositories.IPostRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Service
|
||||
public class PostRepository implements IPostRepository {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final AtomicLong counter = new AtomicLong(0);
|
||||
|
||||
@Autowired
|
||||
public PostRepository(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
Long maxId = jdbcTemplate.queryForObject(
|
||||
"SELECT MAX(ID) FROM POST",
|
||||
Long.class
|
||||
);
|
||||
if (maxId == null) {
|
||||
maxId = 0L;
|
||||
}
|
||||
counter.set(maxId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Post save(Post post) {
|
||||
long id = counter.incrementAndGet();
|
||||
jdbcTemplate.update(
|
||||
"INSERT INTO POST (ID, DONE, FORUM, HOSTS, POST_FOLDER_NAME, POST_ID, PREVIEWS, SECURITY_TOKEN, STATUS, THANKED, THREAD_ID, THREAD_TITLE, TITLE, TOTAL, URL) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
id,
|
||||
post.getDone(),
|
||||
post.getForum(),
|
||||
String.join(";", post.getHosts()),
|
||||
post.getPostFolderName(),
|
||||
post.getPostId(),
|
||||
String.join(";", post.getPreviews()),
|
||||
post.getSecurityToken(),
|
||||
post.getStatus().name(),
|
||||
post.isThanked(),
|
||||
post.getThreadId(),
|
||||
post.getThreadTitle(),
|
||||
post.getTitle(),
|
||||
post.getTotal(),
|
||||
post.getUrl()
|
||||
);
|
||||
post.setId(id);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int delete(Long id) {
|
||||
return jdbcTemplate.update(
|
||||
"DELETE FROM POST AS post WHERE post.ID = ?",
|
||||
id
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Post> findByPostId(String postId) {
|
||||
List<Post> posts = jdbcTemplate.query(
|
||||
"SELECT metadata.*,post.* FROM METADATA metadata FULL JOIN POST post ON metadata.POST_ID_REF = post.ID WHERE POST_ID = ?",
|
||||
new Object[]{postId},
|
||||
new PostRowMapper()
|
||||
);
|
||||
if (posts.isEmpty()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return Optional.of(posts.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> findCompleted() {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT POST_ID FROM POST WHERE status = 'COMPLETE' AND done >= total",
|
||||
((rs, rowNum) -> rs.getString("POST_ID"))
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Post> findById(Long id) {
|
||||
List<Post> posts = jdbcTemplate.query(
|
||||
"SELECT metadata.*,post.* FROM METADATA metadata FULL JOIN POST post ON metadata.POST_ID_REF = post.ID WHERE post.ID = ?",
|
||||
new Object[]{id},
|
||||
new PostRowMapper()
|
||||
);
|
||||
if (posts.isEmpty()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return Optional.of(posts.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Post> findAll() {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT metadata.*,post.* FROM METADATA metadata FULL JOIN POST post ON metadata.POST_ID_REF = post.ID",
|
||||
new PostRowMapper()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existByPostId(String postId) {
|
||||
Integer count = jdbcTemplate.queryForObject(
|
||||
"SELECT COUNT(*) FROM POST AS post WHERE post.POST_ID = ?",
|
||||
new Object[]{postId},
|
||||
Integer.class
|
||||
);
|
||||
if (count == null) {
|
||||
return false;
|
||||
} else {
|
||||
return count > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int setDownloadingToStopped() {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE POST AS post SET post.STATUS = 'STOPPED' WHERE post.STATUS = 'DOWNLOADING' OR post.STATUS = 'PARTIAL' OR post.STATUS = 'PENDING'"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteByPostId(String postId) {
|
||||
return jdbcTemplate.update(
|
||||
"DELETE FROM POST AS post WHERE post.POST_ID = ?",
|
||||
postId
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateStatus(Status status, Long id) {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE POST AS post SET post.STATUS = ? WHERE post.ID = ?",
|
||||
status.name(), id
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateDone(int done, Long id) {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE POST AS post SET post.DONE = ? WHERE post.ID = ?",
|
||||
done, id
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateFolderName(String postFolderName, Long id) {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE POST AS post SET post.POST_FOLDER_NAME = ? WHERE post.ID = ?",
|
||||
postFolderName, id
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateTitle(String title, Long id) {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE POST AS post SET post.TITLE = ? WHERE post.ID = ?",
|
||||
title, id
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateThanked(boolean thanked, Long id) {
|
||||
return jdbcTemplate.update(
|
||||
"UPDATE POST AS post SET post.THANKED = ? WHERE post.ID = ?",
|
||||
thanked, id
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package tn.mnlr.vripper.jpa.repositories.impl;
|
||||
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import tn.mnlr.vripper.jpa.domain.Metadata;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class PostRowMapper implements RowMapper<Post> {
|
||||
|
||||
private static final String DELIMITER = ";";
|
||||
|
||||
@Override
|
||||
public Post mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
|
||||
Post post = new Post();
|
||||
post.setId(rs.getLong("post.ID"));
|
||||
post.setStatus(Status.valueOf(rs.getString("STATUS")));
|
||||
post.setPostId(rs.getString("POST_ID"));
|
||||
post.setThreadTitle(rs.getString("THREAD_TITLE"));
|
||||
post.setThreadId(rs.getString("THREAD_ID"));
|
||||
post.setTitle(rs.getString("TITLE"));
|
||||
post.setUrl(rs.getString("URL"));
|
||||
post.setDone(rs.getInt("DONE"));
|
||||
post.setTotal(rs.getInt("TOTAL"));
|
||||
post.setHosts(Set.of(rs.getString("HOSTS").split(DELIMITER)));
|
||||
post.setForum(rs.getString("FORUM"));
|
||||
post.setSecurityToken(rs.getString("SECURITY_TOKEN"));
|
||||
post.setPostFolderName(rs.getString("POST_FOLDER_NAME"));
|
||||
post.setThanked(rs.getBoolean("THANKED"));
|
||||
String previews;
|
||||
if ((previews = rs.getString("PREVIEWS")) != null) {
|
||||
post.setPreviews(Set.of(previews.split(DELIMITER)));
|
||||
}
|
||||
|
||||
Long metadataId = rs.getLong("metadata.ID");
|
||||
if (!rs.wasNull()) {
|
||||
Metadata metadata = new Metadata();
|
||||
metadata.setId(metadataId);
|
||||
metadata.setPostIdRef(rs.getLong("POST_ID_REF"));
|
||||
String resolvedNames = rs.getString("RESOLVED_NAMES");
|
||||
if (resolvedNames != null && !resolvedNames.isBlank()) {
|
||||
metadata.setResolvedNames(List.of(resolvedNames.split("%sep%")));
|
||||
}
|
||||
metadata.setPostedBy(rs.getString("POSTED_BY"));
|
||||
post.setMetadata(metadata);
|
||||
}
|
||||
|
||||
return post;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package tn.mnlr.vripper.jpa.repositories.impl;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.jpa.domain.Queued;
|
||||
import tn.mnlr.vripper.jpa.repositories.IQueuedRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Service
|
||||
public class QueuedRepository implements IQueuedRepository {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final AtomicLong counter = new AtomicLong(0);
|
||||
|
||||
@Autowired
|
||||
public QueuedRepository(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
Long maxId = jdbcTemplate.queryForObject(
|
||||
"SELECT MAX(ID) FROM QUEUED",
|
||||
Long.class
|
||||
);
|
||||
if (maxId == null) {
|
||||
maxId = 0L;
|
||||
}
|
||||
counter.set(maxId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Queued save(Queued queued) {
|
||||
long id = counter.incrementAndGet();
|
||||
jdbcTemplate.update(
|
||||
"INSERT INTO QUEUED (ID, TOTAL, LINK, LOADING, POST_ID, THREAD_ID) values (?,?,?,?,?,?)",
|
||||
id,
|
||||
queued.getTotal(),
|
||||
queued.getLink(),
|
||||
queued.isLoading(),
|
||||
queued.getPostId(),
|
||||
queued.getThreadId()
|
||||
);
|
||||
queued.setId(id);
|
||||
return queued;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Queued> findByThreadId(String threadId) {
|
||||
List<Queued> queuedList = jdbcTemplate.query(
|
||||
"SELECT * FROM QUEUED AS queued WHERE queued.THREAD_ID = ?",
|
||||
new Object[]{threadId},
|
||||
new QueuedRowMapper()
|
||||
);
|
||||
if (queuedList.isEmpty()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return Optional.of(queuedList.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Queued> findAll() {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT * FROM QUEUED",
|
||||
new QueuedRowMapper()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Queued> findById(Long id) {
|
||||
List<Queued> queuedList = jdbcTemplate.query(
|
||||
"SELECT * FROM QUEUED AS queued WHERE queued.ID = ?",
|
||||
new Object[]{id},
|
||||
new QueuedRowMapper()
|
||||
);
|
||||
if (queuedList.isEmpty()) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return Optional.of(queuedList.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteByThreadId(String threadId) {
|
||||
return jdbcTemplate.update(
|
||||
"DELETE FROM QUEUED AS queued WHERE THREAD_ID = ?",
|
||||
threadId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package tn.mnlr.vripper.jpa.repositories.impl;
|
||||
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import tn.mnlr.vripper.jpa.domain.Queued;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueuedRowMapper implements RowMapper<Queued> {
|
||||
|
||||
@Override
|
||||
public Queued mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
Queued queued = new Queued();
|
||||
queued.setId(rs.getLong("ID"));
|
||||
queued.setLink(rs.getString("LINK"));
|
||||
queued.setThreadId(rs.getString("THREAD_ID"));
|
||||
queued.setPostId(rs.getString("POST_ID"));
|
||||
queued.setTotal(rs.getInt("TOTAL"));
|
||||
queued.setLoading(rs.getBoolean("LOADING"));
|
||||
return queued;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,44 @@
|
||||
package tn.mnlr.vripper.q;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.jodah.failsafe.function.CheckedRunnable;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class DownloadJob implements Callable<Image> {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DownloadJob.class);
|
||||
@Slf4j
|
||||
public class DownloadJob implements CheckedRunnable {
|
||||
|
||||
@Getter
|
||||
private final Image image;
|
||||
|
||||
@Getter
|
||||
private final Post post;
|
||||
|
||||
@Getter
|
||||
private final ImageFileData imageFileData = new ImageFileData();
|
||||
|
||||
DownloadJob(Image image) {
|
||||
@Getter
|
||||
private boolean stopped = false;
|
||||
|
||||
@Getter
|
||||
private boolean finished = false;
|
||||
|
||||
DownloadJob(Post post, Image image) {
|
||||
this.image = image;
|
||||
this.post = post;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Image call() throws Exception {
|
||||
|
||||
logger.debug(String.format("Starting downloading %s", image.getUrl()));
|
||||
image.setStatus(Image.Status.DOWNLOADING);
|
||||
image.setCurrent(0);
|
||||
image.getHost().download(image, imageFileData);
|
||||
image.setStatus(Image.Status.COMPLETE);
|
||||
return image;
|
||||
public void run() throws Exception {
|
||||
if (stopped) {
|
||||
done();
|
||||
return;
|
||||
}
|
||||
log.debug(String.format("Starting downloading %s", image.getUrl()));
|
||||
image.getHost().download(post, image, imageFileData, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -38,11 +46,20 @@ public class DownloadJob implements Callable<Image> {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
DownloadJob that = (DownloadJob) o;
|
||||
return image.equals(that.image);
|
||||
return Objects.equals(image, that.image) &&
|
||||
Objects.equals(post, that.post);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(image);
|
||||
return Objects.hash(image, post);
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
public void done() {
|
||||
finished = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
package tn.mnlr.vripper.q;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.entities.Post;
|
||||
import tn.mnlr.vripper.services.AppStateService;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class DownloadQ {
|
||||
|
||||
private static final List<Post.Status> FINISHED = Arrays.asList(Post.Status.ERROR, Post.Status.COMPLETE, Post.Status.STOPPED);
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DownloadQ.class);
|
||||
|
||||
@Autowired
|
||||
private AppStateService appStateService;
|
||||
|
||||
@Autowired
|
||||
private ExecutionService executionService;
|
||||
|
||||
private BlockingQueue<DownloadJob> downloadQ = new LinkedBlockingQueue<>();
|
||||
|
||||
@Getter
|
||||
private boolean notPauseQ = true;
|
||||
|
||||
public void put(Image image) throws InterruptedException {
|
||||
synchronized (appStateService) {
|
||||
logger.debug(String.format("Enqueuing a job for %s", image.getUrl()));
|
||||
image.init();
|
||||
DownloadJob downloadJob = new DownloadJob(image);
|
||||
downloadQ.put(downloadJob);
|
||||
appStateService.newDownloadJob(downloadJob);
|
||||
}
|
||||
}
|
||||
|
||||
DownloadJob take() throws InterruptedException {
|
||||
DownloadJob downloadJob = downloadQ.take();
|
||||
logger.debug(String.format("Retrieving a job for %s", downloadJob.getImage().getUrl()));
|
||||
return downloadJob;
|
||||
}
|
||||
|
||||
public synchronized void enqueue(Post post) throws InterruptedException {
|
||||
for (Image image : post.getImages()) {
|
||||
put(image);
|
||||
}
|
||||
}
|
||||
|
||||
public void restart(String postId) throws InterruptedException {
|
||||
synchronized (appStateService) {
|
||||
if (appStateService.getRunningPosts().get(postId) != null && appStateService.getRunningPosts().get(postId).get() > 0) {
|
||||
logger.warn(String.format("Cannot restart, jobs are currently running for post id %s", postId));
|
||||
return;
|
||||
}
|
||||
List<Image> images = appStateService.getPost(postId)
|
||||
.getImages()
|
||||
.stream()
|
||||
.filter(e -> !e.getStatus().equals(Image.Status.COMPLETE))
|
||||
.collect(Collectors.toList());
|
||||
if (images.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
appStateService.getPost(postId).setStatus(Post.Status.PENDING);
|
||||
logger.debug(String.format("Restarting %d jobs for post id %s", images.size(), postId));
|
||||
for (Image image : images) {
|
||||
put(image);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void removeScheduled(Image image) {
|
||||
synchronized (appStateService) {
|
||||
image.setStatus(Image.Status.STOPPED);
|
||||
logger.debug(String.format("Removing scheduled job for %s", image.getUrl()));
|
||||
|
||||
Iterator<DownloadJob> iterator = downloadQ.iterator();
|
||||
boolean removed = false;
|
||||
while (iterator.hasNext()) {
|
||||
DownloadJob next = iterator.next();
|
||||
if (next.getImage().getPostId().equals(image.getPostId())) {
|
||||
iterator.remove();
|
||||
appStateService.doneDownloadJob(image);
|
||||
logger.debug(String.format("Scheduled job for %s is removed", image.getUrl()));
|
||||
removed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!removed) {
|
||||
logger.debug(String.format("Job for %s does not exist", image.getUrl()));
|
||||
}
|
||||
|
||||
image.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
private void removeRunning(String postId) {
|
||||
logger.debug(String.format("Interrupting running jobs for post id %s", postId));
|
||||
executionService.stop(postId);
|
||||
}
|
||||
|
||||
|
||||
public void stop(String postId) {
|
||||
try {
|
||||
synchronized (appStateService) {
|
||||
if (FINISHED.contains(appStateService.getPost(postId).getStatus())) {
|
||||
return;
|
||||
}
|
||||
notPauseQ = false;
|
||||
appStateService.getPost(postId).setStatus(Post.Status.STOPPED);
|
||||
List<Image> images = appStateService.getPost(postId)
|
||||
.getImages()
|
||||
.stream()
|
||||
.filter(e -> !e.getStatus().equals(Image.Status.COMPLETE))
|
||||
.collect(Collectors.toList());
|
||||
if (images.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
logger.debug(String.format("Stopping %d jobs for post id %s", images.size(), postId));
|
||||
images.forEach(this::removeScheduled);
|
||||
removeRunning(postId);
|
||||
}
|
||||
} finally {
|
||||
notPauseQ = true;
|
||||
}
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return downloadQ.size();
|
||||
}
|
||||
|
||||
public void stopAll() {
|
||||
synchronized (appStateService) {
|
||||
appStateService.getCurrentPosts().values().stream().map(Post::getPostId).forEach(this::stop);
|
||||
}
|
||||
}
|
||||
|
||||
public void restartAll() throws InterruptedException {
|
||||
synchronized (appStateService) {
|
||||
for (Post post : appStateService.getCurrentPosts().values()) {
|
||||
String postId = post.getPostId();
|
||||
restart(postId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package tn.mnlr.vripper.q;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.jodah.failsafe.Failsafe;
|
||||
import tn.mnlr.vripper.SpringContext;
|
||||
import tn.mnlr.vripper.VripperApplication;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
import tn.mnlr.vripper.services.DataService;
|
||||
import tn.mnlr.vripper.services.MutexService;
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
@Slf4j
|
||||
public class ExecuteRunnable implements Runnable {
|
||||
|
||||
private final ExecutionService executionService;
|
||||
private final DataService dataService;
|
||||
private final MutexService mutexService;
|
||||
|
||||
private final DownloadJob downloadJob;
|
||||
|
||||
public ExecuteRunnable(final DownloadJob downloadJob) {
|
||||
executionService = SpringContext.getBean(ExecutionService.class);
|
||||
dataService = SpringContext.getBean(DataService.class);
|
||||
mutexService = SpringContext.getBean(MutexService.class);
|
||||
this.downloadJob = downloadJob;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
mutexService.createPostLock(downloadJob.getPost().getPostId());
|
||||
ReentrantLock mutex = mutexService.getPostLock(downloadJob.getPost().getPostId());
|
||||
mutex.lock();
|
||||
Failsafe.with(VripperApplication.retryPolicy)
|
||||
.onFailure(e -> {
|
||||
log.error(String.format("Failed to download %s after %d tries", downloadJob.getImage().getUrl(), e.getAttemptCount()), e.getFailure());
|
||||
downloadJob.getImage().setStatus(Status.ERROR);
|
||||
dataService.updateImageStatus(downloadJob.getImage().getStatus(), downloadJob.getImage().getId());
|
||||
})
|
||||
.onComplete(e -> {
|
||||
mutex.unlock();
|
||||
dataService.afterJobFinish(downloadJob.getImage(), downloadJob.getPost());
|
||||
executionService.afterJobFinish(downloadJob);
|
||||
log.debug(String.format("Finished downloading %s", downloadJob.getImage().getUrl()));
|
||||
}).run(downloadJob);
|
||||
}
|
||||
}
|
||||
@@ -1,160 +1,229 @@
|
||||
package tn.mnlr.vripper.q;
|
||||
|
||||
import net.jodah.failsafe.Failsafe;
|
||||
import net.jodah.failsafe.FailsafeException;
|
||||
import net.jodah.failsafe.RetryPolicy;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import lombok.NonNull;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
import tn.mnlr.vripper.services.AppSettingsService;
|
||||
import tn.mnlr.vripper.services.AppStateService;
|
||||
import tn.mnlr.vripper.services.DataService;
|
||||
import tn.mnlr.vripper.services.MutexService;
|
||||
import tn.mnlr.vripper.services.post.PostService;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ExecutionService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ExecutionService.class);
|
||||
private static final List<Status> FINISHED = Arrays.asList(Status.ERROR, Status.COMPLETE, Status.STOPPED);
|
||||
private final int MAX_POOL_SIZE = 12;
|
||||
|
||||
@Autowired
|
||||
private DownloadQ downloadQ;
|
||||
private final ConcurrentHashMap<Host, AtomicInteger> threadCount = new ConcurrentHashMap<>();
|
||||
private final ExecutorService executor = Executors.newFixedThreadPool(MAX_POOL_SIZE);
|
||||
private final BlockingQueue<DownloadJob> executionQueue = new LinkedBlockingQueue<>();
|
||||
private final List<DownloadJob> executing = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
@Autowired
|
||||
private AppSettingsService settings;
|
||||
|
||||
@Autowired
|
||||
private AppStateService appStateService;
|
||||
|
||||
private final AtomicInteger threadCount = new AtomicInteger();
|
||||
|
||||
private ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
private final PendingQ pendingQ;
|
||||
private final AppSettingsService settings;
|
||||
private final DataService dataService;
|
||||
private final PostService postService;
|
||||
private final MutexService mutexService;
|
||||
|
||||
private boolean pauseQ = false;
|
||||
private Thread executionThread;
|
||||
private Thread pollThread;
|
||||
|
||||
private RetryPolicy<Object> retryPolicy;
|
||||
|
||||
private List<DownloadJob> running = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
private Map<String, Future<?>> futures = new ConcurrentHashMap<>();
|
||||
@Autowired
|
||||
public ExecutionService(PendingQ pendingQ, AppSettingsService settings, DataService dataService, PostService postService, MutexService mutexService) {
|
||||
this.pendingQ = pendingQ;
|
||||
this.settings = settings;
|
||||
this.dataService = dataService;
|
||||
this.postService = postService;
|
||||
this.mutexService = mutexService;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
|
||||
retryPolicy = new RetryPolicy<>()
|
||||
.handleIf(e -> !(e instanceof InterruptedException))
|
||||
.withBackoff(10, 60, ChronoUnit.SECONDS)
|
||||
.withMaxRetries(4)
|
||||
.abortOn(InterruptedException.class)
|
||||
.onFailedAttempt(e -> logger.warn(String.format("#%d tries failed", e.getAttemptCount()), e.getLastFailure()));
|
||||
|
||||
executionThread = new Thread(this::start, "Executor thread");
|
||||
pollThread = new Thread(this::poll, "Polling thread");
|
||||
pollThread.start();
|
||||
executionThread.start();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
private void destroy() throws InterruptedException {
|
||||
logger.info("Shutting down ExecutionService");
|
||||
log.info("Shutting down ExecutionService");
|
||||
executionThread.interrupt();
|
||||
pollThread.interrupt();
|
||||
executor.shutdown();
|
||||
appStateService.getCurrentPosts().keySet().forEach(p -> {
|
||||
logger.debug(String.format("Stopping download jobs for %s", p));
|
||||
this.stop(p);
|
||||
dataService.findAllPosts().forEach(p -> {
|
||||
log.debug(String.format("Stopping download jobs for %s", p));
|
||||
this.stopRunning(p.getPostId());
|
||||
});
|
||||
executor.awaitTermination(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public void stop(String postId) {
|
||||
List<DownloadJob> data = running
|
||||
.stream()
|
||||
.filter(e -> e.getImage().getPostId().equals(postId))
|
||||
.peek(e -> e.getImage().setStatus(Image.Status.STOPPED))
|
||||
.collect(Collectors.toList());
|
||||
logger.debug(String.format("Interrupting %d jobs for post id %s", data.size(), postId));
|
||||
|
||||
data.forEach(e -> {
|
||||
futures.get(e.getImage().getUrl()).cancel(true);
|
||||
if(e.getImageFileData().getImageRequest() != null) {
|
||||
e.getImageFileData().getImageRequest().abort();
|
||||
private void stopRunning(@NonNull String postId) {
|
||||
List<DownloadJob> stopping = new ArrayList<>();
|
||||
Iterator<DownloadJob> iterator = executing.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
DownloadJob downloadJob = iterator.next();
|
||||
if (postId.equals(downloadJob.getPost().getPostId())) {
|
||||
downloadJob.stop();
|
||||
iterator.remove();
|
||||
stopping.add(downloadJob);
|
||||
}
|
||||
e.getImage().cleanup();
|
||||
});
|
||||
}
|
||||
|
||||
while (!stopping.isEmpty()) {
|
||||
stopping.removeIf(DownloadJob::isFinished);
|
||||
try {
|
||||
Thread.sleep(200);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean canRun() {
|
||||
boolean canRun = threadCount.get() < settings.getMaxThreads();
|
||||
if (canRun && downloadQ.isNotPauseQ()) {
|
||||
threadCount.incrementAndGet();
|
||||
public void stopAll(List<String> posIds) {
|
||||
if (posIds != null) {
|
||||
posIds.forEach(this::stop);
|
||||
} else {
|
||||
dataService.findAllPosts().forEach(p -> this.stop(p.getPostId()));
|
||||
}
|
||||
}
|
||||
|
||||
public void restartAll(List<String> posIds) {
|
||||
if (posIds != null) {
|
||||
posIds.forEach(this::restart);
|
||||
} else {
|
||||
dataService.findAllPosts().forEach(p -> this.restart(p.getPostId()));
|
||||
}
|
||||
}
|
||||
|
||||
private void restart(@NonNull String postId) {
|
||||
if (isPending(postId)) {
|
||||
log.warn(String.format("Cannot restart, jobs are currently running for post id %s", postId));
|
||||
return;
|
||||
}
|
||||
List<Image> images = dataService.findByPostIdAndIsNotCompleted(postId);
|
||||
if (images.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Post post = dataService.findPostByPostId(postId).orElseThrow();
|
||||
post.setStatus(Status.PENDING);
|
||||
dataService.updatePostStatus(post.getStatus(), post.getId());
|
||||
log.debug(String.format("Restarting %d jobs for post id %s", images.size(), postId));
|
||||
for (Image image : images) {
|
||||
try {
|
||||
pendingQ.put(post, image);
|
||||
} catch (InterruptedException e) {
|
||||
log.warn("Thread was interrupted", e);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isPending(String postId) {
|
||||
return pendingQ.isPending(postId);
|
||||
}
|
||||
|
||||
private void stop(String postId) {
|
||||
try {
|
||||
pauseQ = true;
|
||||
final Post post = dataService.findPostByPostId(postId).orElseThrow();
|
||||
if (post == null) {
|
||||
return;
|
||||
}
|
||||
if (FINISHED.contains(post.getStatus())) {
|
||||
return;
|
||||
}
|
||||
pendingQ.stop(post);
|
||||
stopRunning(postId);
|
||||
dataService.stopImagesByPostIdAndIsNotCompleted(postId);
|
||||
dataService.finishPost(post);
|
||||
postService.stopFetchingMetadata(post);
|
||||
} finally {
|
||||
pauseQ = false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean canRun(Host host) {
|
||||
boolean canRun;
|
||||
AtomicInteger count = threadCount.get(host);
|
||||
if (count == null) {
|
||||
threadCount.put(host, new AtomicInteger(0));
|
||||
}
|
||||
canRun = threadCount.get(host).get() < settings.getSettings().getMaxThreads() && (settings.getSettings().getMaxTotalThreads() == 0 ? threadCount.values().stream().mapToInt(AtomicInteger::get).sum() < MAX_POOL_SIZE : threadCount.values().stream().mapToInt(AtomicInteger::get).sum() < settings.getSettings().getMaxTotalThreads());
|
||||
if (canRun && !pauseQ) {
|
||||
threadCount.get(host).incrementAndGet();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
private void poll() {
|
||||
while (!Thread.interrupted()) {
|
||||
if (canRun()) {
|
||||
DownloadJob take;
|
||||
try {
|
||||
take = downloadQ.take();
|
||||
if (take == null) {
|
||||
continue;
|
||||
try {
|
||||
List<DownloadJob> peek = pendingQ.peek();
|
||||
for (DownloadJob downloadJob : peek) {
|
||||
if (canRun(downloadJob.getImage().getHost())) {
|
||||
executionQueue.offer(downloadJob);
|
||||
pendingQ.remove(downloadJob);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
|
||||
DownloadJob finalTake = take;
|
||||
Runnable task = () -> {
|
||||
running.add(finalTake);
|
||||
|
||||
Failsafe.with(retryPolicy)
|
||||
.onFailure(e -> {
|
||||
if (e.getFailure() instanceof InterruptedException || (e.getFailure() instanceof FailsafeException && e.getFailure().getCause() instanceof InterruptedException)) {
|
||||
logger.debug("Job successfully interrupted");
|
||||
return;
|
||||
}
|
||||
logger.error(String.format("Failed to download %s after %d tries", finalTake.getImage().getUrl(), e.getAttemptCount()), e.getFailure());
|
||||
finalTake.getImage().setStatus(Image.Status.ERROR);
|
||||
})
|
||||
.onComplete(e -> {
|
||||
appStateService.doneDownloadJob(finalTake.getImage());
|
||||
logger.debug(String.format("Finished downloading %s", finalTake.getImage().getUrl()));
|
||||
synchronized (threadCount) {
|
||||
threadCount.decrementAndGet();
|
||||
running.remove(finalTake);
|
||||
futures.remove(finalTake.getImage().getUrl());
|
||||
threadCount.notify();
|
||||
}
|
||||
})
|
||||
.get(finalTake::call);
|
||||
};
|
||||
logger.debug(String.format("Scheduling a job for %s", finalTake.getImage().getUrl()));
|
||||
futures.put(finalTake.getImage().getUrl(), executor.submit(task));
|
||||
} else {
|
||||
synchronized (threadCount) {
|
||||
try {
|
||||
threadCount.wait(2_000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
threadCount.wait(2_000);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void start() {
|
||||
while (!Thread.interrupted()) {
|
||||
try {
|
||||
push(executionQueue.take());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.error("Execution Service failed", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void push(DownloadJob downloadJob) {
|
||||
log.debug(String.format("Scheduling a job for %s", downloadJob.getImage().getUrl()));
|
||||
executor.execute(new ExecuteRunnable(downloadJob));
|
||||
executing.add(downloadJob);
|
||||
}
|
||||
|
||||
public synchronized void afterJobFinish(DownloadJob downloadJob) {
|
||||
int count = pendingQ.decrement(downloadJob.getPost().getPostId());
|
||||
if (count == 0) {
|
||||
dataService.finishPost(downloadJob.getPost());
|
||||
mutexService.removePostLock(downloadJob.getPost().getPostId());
|
||||
}
|
||||
threadCount.get(downloadJob.getImage().getHost()).decrementAndGet();
|
||||
executing.remove(downloadJob);
|
||||
synchronized (threadCount) {
|
||||
threadCount.notify();
|
||||
}
|
||||
}
|
||||
|
||||
public int runningCount() {
|
||||
return running.size();
|
||||
return executing.size();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ public class ImageFileData {
|
||||
|
||||
private String pageUrl;
|
||||
private String imageName;
|
||||
private String fileName;
|
||||
private String imageUrl;
|
||||
private HttpUriRequest imageRequest;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package tn.mnlr.vripper.q;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.services.AppSettingsService;
|
||||
import tn.mnlr.vripper.services.DataService;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.BlockingDeque;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.LinkedBlockingDeque;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PendingQ {
|
||||
|
||||
private final DataService dataService;
|
||||
private final AppSettingsService appSettingsService;
|
||||
private final List<Host> hosts;
|
||||
|
||||
private final ConcurrentHashMap<Host, BlockingDeque<DownloadJob>> pendingQ = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, AtomicInteger> toBeExecuted = new ConcurrentHashMap<>();
|
||||
|
||||
@Autowired
|
||||
public PendingQ(DataService dataService, AppSettingsService appSettingsService, List<Host> hosts) {
|
||||
this.dataService = dataService;
|
||||
this.appSettingsService = appSettingsService;
|
||||
this.hosts = hosts;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
hosts.forEach(host -> pendingQ.put(host, new LinkedBlockingDeque<>()));
|
||||
}
|
||||
|
||||
public void put(Post post, Image image) throws InterruptedException {
|
||||
log.debug(String.format("Enqueuing a job for %s", image.getUrl()));
|
||||
image.init();
|
||||
dataService.updateImageStatus(image.getStatus(), image.getId());
|
||||
dataService.updateImageCurrent(image.getCurrent(), image.getId());
|
||||
DownloadJob downloadJob = new DownloadJob(post, image);
|
||||
pendingQ.get(downloadJob.getImage().getHost()).putLast(downloadJob);
|
||||
checkKey(post.getPostId());
|
||||
toBeExecuted.get(post.getPostId()).incrementAndGet();
|
||||
}
|
||||
|
||||
private synchronized void checkKey(String postId) {
|
||||
if (!toBeExecuted.containsKey(postId)) {
|
||||
toBeExecuted.put(postId, new AtomicInteger(0));
|
||||
}
|
||||
}
|
||||
|
||||
public void remove(final DownloadJob downloadJob) {
|
||||
pendingQ.get(downloadJob.getImage().getHost()).remove(downloadJob);
|
||||
}
|
||||
|
||||
public List<DownloadJob> peek() {
|
||||
List<DownloadJob> downloadJobs = new ArrayList<>();
|
||||
if (hosts.size() == 0) {
|
||||
return downloadJobs;
|
||||
}
|
||||
for (Host host : hosts) {
|
||||
Iterator<DownloadJob> it = pendingQ.get(host).iterator();
|
||||
for (int i = 0; i < appSettingsService.getSettings().getMaxThreads(); i++) {
|
||||
DownloadJob downloadJob = it.hasNext() ? it.next() : null;
|
||||
if (downloadJob != null) {
|
||||
downloadJobs.add(downloadJob);
|
||||
}
|
||||
}
|
||||
}
|
||||
return downloadJobs;
|
||||
}
|
||||
|
||||
public void enqueue(Post post, Set<Image> images) throws InterruptedException {
|
||||
for (Image image : images) {
|
||||
put(post, image);
|
||||
}
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return toBeExecuted.values().stream().mapToInt(AtomicInteger::get).sum();
|
||||
}
|
||||
|
||||
public void stop(Post post) {
|
||||
Predicate<DownloadJob> predicate = next -> next.getImage().getPostId().equals(post.getPostId());
|
||||
for (Map.Entry<Host, BlockingDeque<DownloadJob>> entry : pendingQ.entrySet()) {
|
||||
entry.getValue().stream().filter(predicate).forEach(e -> decrement(post.getPostId()));
|
||||
entry.getValue().removeIf(predicate);
|
||||
decrement(post.getPostId());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isPending(String postId) {
|
||||
return toBeExecuted.containsKey(postId);
|
||||
}
|
||||
|
||||
public synchronized int decrement(String postId) {
|
||||
AtomicInteger counter = toBeExecuted.get(postId);
|
||||
if (counter == null) {
|
||||
return 0;
|
||||
}
|
||||
int count = counter.decrementAndGet();
|
||||
if (count == 0) {
|
||||
toBeExecuted.remove(postId);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
@@ -1,110 +1,161 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.SpringContext;
|
||||
import tn.mnlr.vripper.exception.ValidationException;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.prefs.BackingStoreException;
|
||||
import java.util.prefs.Preferences;
|
||||
|
||||
import static java.nio.file.StandardOpenOption.*;
|
||||
|
||||
@Service
|
||||
@Getter
|
||||
@Setter
|
||||
@Slf4j
|
||||
public class AppSettingsService {
|
||||
|
||||
@Value("${base.dir}")
|
||||
private String defaultDownloadPath;
|
||||
private final String MAX_TOTAL_THREADS = "MAX_TOTAL_THREADS";
|
||||
private final String baseDir;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AppSettingsService.class);
|
||||
private final Path configPath;
|
||||
private final ObjectMapper om = new ObjectMapper();
|
||||
|
||||
private Preferences prefs = Preferences.userNodeForPackage(AppSettingsService.class);
|
||||
private Settings settings = new Settings();
|
||||
|
||||
private final String DOWNLOAD_PATH = "DOWNLOAD_PATH";
|
||||
private final String MAX_THREADS = "MAX_THREADS";
|
||||
private final String AUTO_START = "AUTO_START";
|
||||
private final String V_LOGIN = "VLOGIN";
|
||||
private final String V_USERNAME = "VUSERNAME";
|
||||
private final String V_PASSWORD = "VPASSWORD";
|
||||
private final String V_THANKS = "VTHANKS";
|
||||
private final String DESKTOP_CLIPBOARD = "DESKTOP_CLIPBOARD";
|
||||
private final String FORCE_ORDER = "FORCE_ORDER";
|
||||
private final String SUBFOLDER = "SUBFOLDER";
|
||||
private final String THREADSUBFOLDER = "THREADSUBFOLDER";
|
||||
private final String CLEAR = "CLEAR";
|
||||
private final String DARK_THEME = "DARK_THEME";
|
||||
public AppSettingsService(@Value("${base.dir}") String baseDir) {
|
||||
this.baseDir = baseDir;
|
||||
this.configPath = Paths.get(baseDir, ".vripper", "config.json");
|
||||
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
}
|
||||
|
||||
private String downloadPath;
|
||||
private int maxThreads;
|
||||
private boolean autoStart;
|
||||
private boolean vLogin;
|
||||
private String vUsername;
|
||||
private String vPassword;
|
||||
private boolean vThanks;
|
||||
private boolean desktopClipboard;
|
||||
private boolean subLocation;
|
||||
private boolean threadSubLocation;
|
||||
private boolean forceOrder;
|
||||
private boolean clearCompleted;
|
||||
private boolean darkTheme;
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
restore();
|
||||
}
|
||||
|
||||
public void setVPassword(String vPassword) {
|
||||
if(vPassword.isEmpty()) {
|
||||
this.vPassword = "";
|
||||
public void newSettings(Settings settings) {
|
||||
|
||||
if (settings.getVLogin()) {
|
||||
if (!this.settings.getVPassword().equals(settings.getVPassword())) {
|
||||
settings.setVPassword(settings.getVPassword());
|
||||
}
|
||||
} else {
|
||||
this.vPassword = DigestUtils.md5Hex(vPassword);
|
||||
settings.setVUsername("");
|
||||
settings.setVPassword("");
|
||||
settings.setVThanks(false);
|
||||
}
|
||||
this.settings = settings;
|
||||
|
||||
save();
|
||||
}
|
||||
|
||||
public void restore() {
|
||||
try {
|
||||
settings = om.readValue(configPath.toFile(), Settings.class);
|
||||
try {
|
||||
check(this.settings);
|
||||
} catch (ValidationException e) {
|
||||
log.error(String.format("Your settings are invalid, either remove %s, or fix it", configPath.toString()), e);
|
||||
SpringContext.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Failed restore user settings", e);
|
||||
settings = new Settings();
|
||||
}
|
||||
|
||||
downloadPath = prefs.get(DOWNLOAD_PATH, defaultDownloadPath);
|
||||
maxThreads = prefs.getInt(MAX_THREADS, 4);
|
||||
autoStart = prefs.getBoolean(AUTO_START, true);
|
||||
vLogin = prefs.getBoolean(V_LOGIN, false);
|
||||
vUsername = prefs.get(V_USERNAME, "");
|
||||
vPassword = prefs.get(V_PASSWORD, "");
|
||||
vThanks = prefs.getBoolean(V_THANKS, false);
|
||||
desktopClipboard = prefs.getBoolean(DESKTOP_CLIPBOARD, false);
|
||||
forceOrder = prefs.getBoolean(FORCE_ORDER, false);
|
||||
subLocation = prefs.getBoolean(SUBFOLDER, false);
|
||||
threadSubLocation = prefs.getBoolean(THREADSUBFOLDER, false);
|
||||
clearCompleted = prefs.getBoolean(CLEAR, false);
|
||||
darkTheme = prefs.getBoolean(DARK_THEME, false);
|
||||
if (settings.getDownloadPath() == null) {
|
||||
settings.setDownloadPath(baseDir);
|
||||
}
|
||||
|
||||
if (settings.getMaxThreads() == null) {
|
||||
settings.setMaxThreads(4);
|
||||
}
|
||||
|
||||
if (settings.getMaxTotalThreads() == null) {
|
||||
settings.setMaxTotalThreads(0);
|
||||
}
|
||||
|
||||
if (settings.getAutoStart() == null) {
|
||||
settings.setAutoStart(true);
|
||||
}
|
||||
|
||||
if (settings.getVLogin() == null) {
|
||||
settings.setVLogin(false);
|
||||
}
|
||||
|
||||
if (settings.getVUsername() == null) {
|
||||
settings.setVUsername("");
|
||||
}
|
||||
|
||||
if (settings.getVPassword() == null) {
|
||||
settings.setVPassword("");
|
||||
}
|
||||
|
||||
if (settings.getVThanks() == null) {
|
||||
settings.setVThanks(false);
|
||||
}
|
||||
|
||||
if (settings.getDesktopClipboard() == null) {
|
||||
settings.setDesktopClipboard(false);
|
||||
}
|
||||
|
||||
if (settings.getForceOrder() == null) {
|
||||
settings.setForceOrder(false);
|
||||
}
|
||||
|
||||
if (settings.getSubLocation() == null) {
|
||||
settings.setSubLocation(false);
|
||||
}
|
||||
|
||||
if (settings.getThreadSubLocation() == null) {
|
||||
settings.setThreadSubLocation(false);
|
||||
}
|
||||
|
||||
if (settings.getClearCompleted() == null) {
|
||||
settings.setClearCompleted(false);
|
||||
}
|
||||
|
||||
if (settings.getDarkTheme() == null) {
|
||||
settings.setDarkTheme(false);
|
||||
}
|
||||
|
||||
if (settings.getViewPhotos() == null) {
|
||||
settings.setViewPhotos(false);
|
||||
}
|
||||
|
||||
if (settings.getNotification() == null) {
|
||||
settings.setNotification(false);
|
||||
}
|
||||
|
||||
|
||||
save();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void save() {
|
||||
|
||||
prefs.put(DOWNLOAD_PATH, downloadPath);
|
||||
prefs.putInt(MAX_THREADS, maxThreads);
|
||||
prefs.putBoolean(AUTO_START, autoStart);
|
||||
prefs.putBoolean(V_LOGIN, vLogin);
|
||||
prefs.put(V_USERNAME, vUsername);
|
||||
prefs.put(V_PASSWORD, vPassword);
|
||||
prefs.putBoolean(V_THANKS, vThanks);
|
||||
prefs.putBoolean(DESKTOP_CLIPBOARD, desktopClipboard);
|
||||
prefs.putBoolean(FORCE_ORDER, forceOrder);
|
||||
prefs.putBoolean(SUBFOLDER, subLocation);
|
||||
prefs.putBoolean(THREADSUBFOLDER, threadSubLocation);
|
||||
prefs.putBoolean(CLEAR, clearCompleted);
|
||||
prefs.putBoolean(DARK_THEME, darkTheme);
|
||||
|
||||
try {
|
||||
prefs.sync();
|
||||
} catch (BackingStoreException e) {
|
||||
logger.error("Failed to store user settings", e);
|
||||
// force disable gallery
|
||||
settings.setViewPhotos(false);
|
||||
|
||||
Files.write(configPath, om.writeValueAsBytes(settings), CREATE, WRITE, TRUNCATE_EXISTING, SYNC);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to store user settings", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,17 +173,21 @@ public class AppSettingsService {
|
||||
throw new ValidationException(String.format("%s is not a directory", settings.getDownloadPath()));
|
||||
}
|
||||
|
||||
if (settings.getMaxTotalThreads() < 0 || settings.getMaxTotalThreads() > 12) {
|
||||
throw new ValidationException(String.format("Invalid max global concurrent download settings, values must be in [%d,%d]", 0, 12));
|
||||
}
|
||||
|
||||
if (settings.getMaxThreads() < 1 || settings.getMaxThreads() > 4) {
|
||||
throw new ValidationException(String.format("Invalid max concurrent download settings, values must be in [%d,%d]", 1, 4));
|
||||
}
|
||||
}
|
||||
|
||||
public Theme getTheme() {
|
||||
return new Theme(this.darkTheme);
|
||||
return new Theme(this.settings.getDarkTheme());
|
||||
}
|
||||
|
||||
public void setTheme(Theme theme) {
|
||||
this.darkTheme = theme.darkTheme;
|
||||
this.settings.setDarkTheme(theme.darkTheme);
|
||||
save();
|
||||
}
|
||||
|
||||
@@ -149,46 +204,50 @@ public class AppSettingsService {
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public static class Settings {
|
||||
|
||||
@JsonProperty("downloadPath")
|
||||
private String downloadPath;
|
||||
@JsonProperty("maxThreads")
|
||||
private int maxThreads;
|
||||
private Integer maxThreads;
|
||||
@JsonProperty("maxTotalThreads")
|
||||
private Integer maxTotalThreads;
|
||||
@JsonProperty("autoStart")
|
||||
private boolean autoStart;
|
||||
private Boolean autoStart;
|
||||
@JsonProperty("vLogin")
|
||||
private boolean vLogin;
|
||||
private Boolean vLogin;
|
||||
@JsonProperty("vUsername")
|
||||
private String vUsername;
|
||||
@JsonProperty("vPassword")
|
||||
private String vPassword;
|
||||
@JsonProperty("vThanks")
|
||||
private boolean vThanks;
|
||||
private Boolean vThanks;
|
||||
@JsonProperty("desktopClipboard")
|
||||
private boolean desktopClipboard;
|
||||
private Boolean desktopClipboard;
|
||||
@JsonProperty("forceOrder")
|
||||
private boolean forceOrder;
|
||||
private Boolean forceOrder;
|
||||
@JsonProperty("subLocation")
|
||||
private boolean subLocation;
|
||||
private Boolean subLocation;
|
||||
@JsonProperty("threadSubLocation")
|
||||
private boolean threadSubLocation;
|
||||
private Boolean threadSubLocation;
|
||||
@JsonProperty("clearCompleted")
|
||||
private boolean clearCompleted;
|
||||
private Boolean clearCompleted;
|
||||
@JsonProperty("viewPhotos")
|
||||
private Boolean viewPhotos;
|
||||
@JsonProperty("notification")
|
||||
private Boolean notification;
|
||||
@JsonProperty("darkTheme")
|
||||
private Boolean darkTheme;
|
||||
|
||||
public Settings(String downloadPath, int maxThreads, boolean autoStart, boolean vLogin, String vUsername, String vPassword, boolean vThanks, boolean desktopClipboard, boolean forceOrder, boolean subLocation, boolean threadSubLocation, boolean clearCompleted) {
|
||||
this.downloadPath = downloadPath;
|
||||
this.maxThreads = maxThreads;
|
||||
this.autoStart = autoStart;
|
||||
this.vLogin = vLogin;
|
||||
this.vUsername = vUsername;
|
||||
this.vPassword = vPassword;
|
||||
this.vThanks = vThanks;
|
||||
this.desktopClipboard = desktopClipboard;
|
||||
this.forceOrder = forceOrder;
|
||||
this.subLocation = subLocation;
|
||||
this.threadSubLocation = threadSubLocation;
|
||||
this.clearCompleted = clearCompleted;
|
||||
public void setVPassword(String vPassword) {
|
||||
if (vPassword == null || vPassword.isEmpty()) {
|
||||
this.vPassword = "";
|
||||
} else {
|
||||
this.vPassword = DigestUtils.md5Hex(vPassword);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import io.reactivex.processors.PublishProcessor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.entities.Post;
|
||||
import tn.mnlr.vripper.q.DownloadJob;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@Getter
|
||||
public class AppStateService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AppStateService.class);
|
||||
|
||||
private Map<String, Image> currentImages = new ConcurrentHashMap<>();
|
||||
|
||||
private Map<String, Post> currentPosts = new ConcurrentHashMap<>();
|
||||
|
||||
private Map<String, AtomicInteger> runningPosts = new ConcurrentHashMap<>();
|
||||
|
||||
private Map<String, QueuedVGLink> grabQueue = new ConcurrentHashMap<>();
|
||||
|
||||
private PublishProcessor<QueuedVGLink> liveGrabQueue = PublishProcessor.create();
|
||||
|
||||
private PublishProcessor<Image> liveImageUpdates = PublishProcessor.create();
|
||||
|
||||
private PublishProcessor<Post> livePostsState = PublishProcessor.create();
|
||||
|
||||
@Autowired
|
||||
private PersistenceService persistenceService;
|
||||
|
||||
@Autowired
|
||||
private AppSettingsService appSettingsService;
|
||||
|
||||
public void onImageUpdate(Image imageState) {
|
||||
|
||||
persistenceService.getProcessor().onNext(currentPosts);
|
||||
|
||||
liveImageUpdates.onNext(imageState);
|
||||
if (imageState.isCompleted()) {
|
||||
|
||||
Post postState = currentPosts.get(imageState.getPostId());
|
||||
postState.increase();
|
||||
}
|
||||
}
|
||||
|
||||
public Post getPost(String postId) {
|
||||
return currentPosts.get(postId);
|
||||
}
|
||||
|
||||
public synchronized void newDownloadJob(DownloadJob downloadJob) {
|
||||
String postId = downloadJob.getImage().getPostId();
|
||||
checkKeyRunningPosts(postId);
|
||||
runningPosts.get(postId).incrementAndGet();
|
||||
}
|
||||
|
||||
public synchronized void postDownloadingUpdate(String postId) {
|
||||
Post post = currentPosts.get(postId);
|
||||
if (!post.getStatus().equals(Post.Status.DOWNLOADING)) {
|
||||
post.setStatus(Post.Status.DOWNLOADING);
|
||||
livePostsState.onNext(post);
|
||||
}
|
||||
}
|
||||
|
||||
public void doneDownloadJob(Image image) {
|
||||
String postId = image.getPostId();
|
||||
int i = runningPosts.get(postId).decrementAndGet();
|
||||
Post post = currentPosts.get(postId);
|
||||
if(image.getStatus().equals(Image.Status.ERROR)) {
|
||||
post.setStatus(Post.Status.PARTIAL);
|
||||
}
|
||||
if (i == 0) {
|
||||
if (post.getImages().stream().map(Image::getStatus).anyMatch(e -> e.equals(Image.Status.ERROR))) {
|
||||
post.setStatus(Post.Status.ERROR);
|
||||
} else {
|
||||
if (!Post.Status.STOPPED.equals(post.getStatus())) {
|
||||
post.setStatus(Post.Status.COMPLETE);
|
||||
if (appSettingsService.isClearCompleted()) {
|
||||
remove(image.getPostId());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void checkKeyRunningPosts(String key) {
|
||||
if (!runningPosts.containsKey(key)) {
|
||||
runningPosts.put(key, new AtomicInteger(0));
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void remove(String postId) {
|
||||
currentPosts.get(postId).setRemoved(true);
|
||||
runningPosts.remove(postId);
|
||||
currentPosts.remove(postId);
|
||||
currentImages.entrySet().removeIf(entry -> entry.getValue().getPostId().equals(postId));
|
||||
persistenceService.getProcessor().onNext(currentPosts);
|
||||
}
|
||||
|
||||
public synchronized List<String> clearAll() {
|
||||
List<String> toRemove = this.currentPosts
|
||||
.values()
|
||||
.stream()
|
||||
.filter(e -> e.getStatus().equals(Post.Status.COMPLETE) && e.getDone().get() >= e.getTotal())
|
||||
.map(Post::getPostId)
|
||||
.collect(Collectors.toList());
|
||||
toRemove.forEach(this::remove);
|
||||
return toRemove;
|
||||
}
|
||||
|
||||
public synchronized List<String> removeAll() {
|
||||
List<String> toRemove = this.currentPosts
|
||||
.values()
|
||||
.stream()
|
||||
.map(Post::getPostId)
|
||||
.collect(Collectors.toList());
|
||||
toRemove.forEach(this::remove);
|
||||
return toRemove;
|
||||
}
|
||||
|
||||
|
||||
@Getter
|
||||
public static class CachedThread {
|
||||
|
||||
private Map<String, Post> posts = new ConcurrentHashMap<>();
|
||||
private AtomicInteger parsed = new AtomicInteger(0);
|
||||
|
||||
@Setter
|
||||
private int total = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import io.reactivex.Scheduler;
|
||||
import io.reactivex.schedulers.Schedulers;
|
||||
import lombok.Getter;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
public class CommonExecutor {
|
||||
@Getter
|
||||
private final ExecutorService generalExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
|
||||
private final ExecutorService schedulerExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
|
||||
|
||||
@Getter
|
||||
private final Scheduler scheduler = Schedulers.from(schedulerExecutor);
|
||||
|
||||
@PreDestroy
|
||||
private void destroy() throws InterruptedException {
|
||||
generalExecutor.shutdown();
|
||||
generalExecutor.awaitTermination(10, TimeUnit.SECONDS);
|
||||
schedulerExecutor.shutdown();
|
||||
schedulerExecutor.awaitTermination(10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
@@ -26,9 +26,9 @@ public class ConnectionManager {
|
||||
private PoolingHttpClientConnectionManager pcm;
|
||||
|
||||
private RequestConfig rc = RequestConfig.custom()
|
||||
.setConnectionRequestTimeout(10_000)
|
||||
.setConnectTimeout(10_000)
|
||||
.setSocketTimeout(10_000)
|
||||
.setConnectionRequestTimeout(5_000)
|
||||
.setConnectTimeout(5_000)
|
||||
.setSocketTimeout(5_000)
|
||||
.setCookieSpec(CookieSpecs.STANDARD)
|
||||
.build();
|
||||
|
||||
@@ -54,13 +54,13 @@ public class ConnectionManager {
|
||||
}
|
||||
|
||||
public HttpGet buildHttpGet(String url) {
|
||||
HttpGet httpGet = new HttpGet(url);
|
||||
HttpGet httpGet = new HttpGet(url.replace(" ", "+"));
|
||||
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
|
||||
return httpGet;
|
||||
}
|
||||
|
||||
public HttpPost buildHttpPost(String url) {
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
HttpPost httpPost = new HttpPost(url.replace(" ", "+"));
|
||||
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
|
||||
return httpPost;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import io.reactivex.Observable;
|
||||
import io.reactivex.processors.PublishProcessor;
|
||||
import lombok.NonNull;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.Metadata;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.jpa.domain.Queued;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
import tn.mnlr.vripper.jpa.repositories.IImageRepository;
|
||||
import tn.mnlr.vripper.jpa.repositories.IMetadataRepository;
|
||||
import tn.mnlr.vripper.jpa.repositories.IPostRepository;
|
||||
import tn.mnlr.vripper.jpa.repositories.IQueuedRepository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
@Slf4j
|
||||
public class DataService {
|
||||
|
||||
private final IPostRepository postRepository;
|
||||
private final IImageRepository imageRepository;
|
||||
private final IQueuedRepository queuedRepository;
|
||||
private final IMetadataRepository metadataRepository;
|
||||
private final AppSettingsService appSettingsService;
|
||||
|
||||
private final PublishProcessor<Long> liveGrabQueue = PublishProcessor.create();
|
||||
private final PublishProcessor<Long> liveImageUpdates = PublishProcessor.create();
|
||||
private final PublishProcessor<Long> livePostsState = PublishProcessor.create();
|
||||
|
||||
private final PublishProcessor<String> postRemove = PublishProcessor.create();
|
||||
private final PublishProcessor<String> queueRemove = PublishProcessor.create();
|
||||
|
||||
public Observable<Long> liveQueue() {
|
||||
return liveGrabQueue.toObservable();
|
||||
}
|
||||
|
||||
public Observable<Long> livePost() {
|
||||
return livePostsState.toObservable();
|
||||
}
|
||||
|
||||
public Observable<Long> liveImage() {
|
||||
return liveImageUpdates.toObservable();
|
||||
}
|
||||
|
||||
public Observable<String> queueRemove() {
|
||||
return queueRemove.toObservable();
|
||||
}
|
||||
|
||||
public Observable<String> postRemove() {
|
||||
return postRemove.toObservable();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public DataService(IPostRepository postRepository, IImageRepository imageRepository, IQueuedRepository queuedRepository, IMetadataRepository metadataRepository, AppSettingsService appSettingsService) {
|
||||
this.postRepository = postRepository;
|
||||
this.imageRepository = imageRepository;
|
||||
this.queuedRepository = queuedRepository;
|
||||
this.metadataRepository = metadataRepository;
|
||||
this.appSettingsService = appSettingsService;
|
||||
}
|
||||
|
||||
private void save(Post post) {
|
||||
postRepository.save(post);
|
||||
livePostsState.onNext(post.getId());
|
||||
}
|
||||
|
||||
private void save(Queued queued) {
|
||||
queuedRepository.save(queued);
|
||||
liveGrabQueue.onNext(queued.getId());
|
||||
}
|
||||
|
||||
private void save(Image image) {
|
||||
imageRepository.save(image);
|
||||
liveImageUpdates.onNext(image.getId());
|
||||
}
|
||||
|
||||
public boolean exists(String postId) {
|
||||
return postRepository.existByPostId(postId);
|
||||
}
|
||||
|
||||
public void newPost(Post post, Collection<Image> images) {
|
||||
save(post);
|
||||
images.forEach(image -> {
|
||||
image.setPostIdRef(post.getId());
|
||||
save(image);
|
||||
});
|
||||
}
|
||||
|
||||
public void setDownloadingToStopped() {
|
||||
postRepository.setDownloadingToStopped();
|
||||
}
|
||||
|
||||
public synchronized void afterJobFinish(Image image, Post post) {
|
||||
if (image.getStatus().equals(Status.COMPLETE)) {
|
||||
post.setDone(post.getDone() + 1);
|
||||
updatePostDone(post.getDone(), post.getId());
|
||||
} else if (image.getStatus().equals(Status.ERROR)) {
|
||||
post.setStatus(Status.PARTIAL);
|
||||
updatePostStatus(post.getStatus(), post.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private void updatePostDone(int done, Long id) {
|
||||
livePostsState.onNext(id);
|
||||
postRepository.updateDone(done, id);
|
||||
}
|
||||
|
||||
public void finishPost(@NonNull Post post) {
|
||||
if (!imageRepository.findByPostIdAndIsError(post.getPostId()).isEmpty()) {
|
||||
post.setStatus(Status.ERROR);
|
||||
updatePostStatus(post.getStatus(), post.getId());
|
||||
} else {
|
||||
if (post.getDone() < post.getTotal()) {
|
||||
post.setStatus(Status.STOPPED);
|
||||
updatePostStatus(post.getStatus(), post.getId());
|
||||
} else {
|
||||
post.setStatus(Status.COMPLETE);
|
||||
updatePostStatus(post.getStatus(), post.getId());
|
||||
if (appSettingsService.getSettings().getClearCompleted()) {
|
||||
remove(post.getPostId());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void remove(@NonNull final String postId) {
|
||||
imageRepository.deleteAllByPostId(postId);
|
||||
metadataRepository.deleteByPostId(postId);
|
||||
postRepository.deleteByPostId(postId);
|
||||
postRemove.onNext(postId);
|
||||
}
|
||||
|
||||
public void newQueueLink(@NonNull final Queued queued) {
|
||||
save(queued);
|
||||
}
|
||||
|
||||
public void removeQueueLink(@NonNull final String threadId) {
|
||||
queuedRepository.deleteByThreadId(threadId);
|
||||
queueRemove.onNext(threadId);
|
||||
}
|
||||
|
||||
public List<String> clearCompleted() {
|
||||
List<String> completed = postRepository.findCompleted();
|
||||
completed.forEach(this::remove);
|
||||
return completed;
|
||||
}
|
||||
|
||||
public void removeAll(final List<String> postIds) {
|
||||
if (postIds != null && !postIds.isEmpty()) {
|
||||
for (String postId : postIds) {
|
||||
remove(postId);
|
||||
}
|
||||
} else {
|
||||
postRepository.findAll().forEach(p -> remove(p.getPostId()));
|
||||
}
|
||||
}
|
||||
|
||||
public List<Image> findByPostIdAndIsNotCompleted(@NonNull String postId) {
|
||||
return imageRepository.findByPostIdAndIsNotCompleted(postId);
|
||||
|
||||
}
|
||||
|
||||
public long countErrorImages() {
|
||||
return imageRepository.countError();
|
||||
}
|
||||
|
||||
public List<Image> findImagesByPostId(String postId) {
|
||||
return imageRepository.findByPostId(postId);
|
||||
}
|
||||
|
||||
public Iterable<Post> findAllPosts() {
|
||||
return postRepository.findAll();
|
||||
}
|
||||
|
||||
public Optional<Post> findPostByPostId(String postId) {
|
||||
return postRepository.findByPostId(postId);
|
||||
}
|
||||
|
||||
public void stopImagesByPostIdAndIsNotCompleted(String postId) {
|
||||
imageRepository.stopByPostIdAndIsNotCompleted(postId);
|
||||
}
|
||||
|
||||
public Optional<Queued> findQueuedByThreadId(String threadId) {
|
||||
return queuedRepository.findByThreadId(threadId);
|
||||
}
|
||||
|
||||
public Iterable<Queued> findAllQueued() {
|
||||
return queuedRepository.findAll();
|
||||
}
|
||||
|
||||
public Optional<Post> findPostById(Long aLong) {
|
||||
return postRepository.findById(aLong);
|
||||
}
|
||||
|
||||
public Optional<Image> findImageById(Long aLong) {
|
||||
return imageRepository.findById(aLong);
|
||||
}
|
||||
|
||||
public Optional<Queued> findQueuedById(Long aLong) {
|
||||
return queuedRepository.findById(aLong);
|
||||
}
|
||||
|
||||
public void setMetadata(Post post, Metadata metadata) {
|
||||
metadata.setPostIdRef(post.getId());
|
||||
metadataRepository.save(metadata);
|
||||
livePostsState.onNext(post.getId());
|
||||
}
|
||||
|
||||
public Optional<Metadata> findMetadataByPostId(String postId) {
|
||||
return metadataRepository.findByPostId(postId);
|
||||
}
|
||||
|
||||
public void updateImageStatus(Status status, Long id) {
|
||||
imageRepository.updateStatus(status, id);
|
||||
liveImageUpdates.onNext(id);
|
||||
}
|
||||
|
||||
public void updateImageCurrent(long current, Long id) {
|
||||
imageRepository.updateCurrent(current, id);
|
||||
liveImageUpdates.onNext(id);
|
||||
}
|
||||
|
||||
public void updateImageTotal(long total, Long id) {
|
||||
imageRepository.updateTotal(total, id);
|
||||
liveImageUpdates.onNext(id);
|
||||
}
|
||||
|
||||
public void updatePostStatus(Status status, Long id) {
|
||||
postRepository.updateStatus(status, id);
|
||||
livePostsState.onNext(id);
|
||||
}
|
||||
|
||||
public void updatePostFolderName(String postFolderName, Long id) {
|
||||
postRepository.updateFolderName(postFolderName, id);
|
||||
livePostsState.onNext(id);
|
||||
}
|
||||
|
||||
public void updatePostTitle(String title, Long id) {
|
||||
postRepository.updateTitle(title, id);
|
||||
livePostsState.onNext(id);
|
||||
}
|
||||
|
||||
public void updatePostThanked(boolean thanked, Long id) {
|
||||
postRepository.updateThanked(thanked, id);
|
||||
livePostsState.onNext(id);
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,14 @@ import lombok.Getter;
|
||||
@Getter
|
||||
public class DownloadSpeed {
|
||||
|
||||
private final String type = "downSpeed";
|
||||
private String speed;
|
||||
private final String speed;
|
||||
|
||||
public DownloadSpeed(long bytes) {
|
||||
speed = formatSI(bytes);
|
||||
}
|
||||
|
||||
private String formatSI(long bytes) {
|
||||
return humanReadableByteCount(bytes, true);
|
||||
return humanReadableByteCount(bytes, false);
|
||||
}
|
||||
|
||||
private String humanReadableByteCount(long bytes, boolean si) {
|
||||
|
||||
@@ -14,10 +14,11 @@ public class DownloadSpeedService {
|
||||
|
||||
private AtomicLong read = new AtomicLong(0);
|
||||
|
||||
@Getter
|
||||
private long currentValue;
|
||||
|
||||
@Getter
|
||||
private PublishProcessor<Long> readBytesPerSecond = PublishProcessor.create();
|
||||
private final PublishProcessor<Long> readBytesPerSecond = PublishProcessor.create();
|
||||
|
||||
private boolean allowWrite = false;
|
||||
|
||||
|
||||
@@ -7,15 +7,12 @@ import java.util.Objects;
|
||||
@Getter
|
||||
public class GlobalState {
|
||||
|
||||
private final String type = "globalState";
|
||||
private long running;
|
||||
private long queued;
|
||||
private long remaining;
|
||||
private long error;
|
||||
private final long running;
|
||||
private final long remaining;
|
||||
private final long error;
|
||||
|
||||
GlobalState(long running, long queued, long remaining, long error) {
|
||||
GlobalState(long running, long remaining, long error) {
|
||||
this.running = running;
|
||||
this.queued = queued;
|
||||
this.remaining = remaining;
|
||||
this.error = error;
|
||||
}
|
||||
@@ -25,11 +22,11 @@ public class GlobalState {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
GlobalState that = (GlobalState) o;
|
||||
return running == that.running && queued == that.queued && remaining == that.remaining && error == that.error;
|
||||
return running == that.running && remaining == that.remaining && error == that.error;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(type, running, queued, remaining, error);
|
||||
return Objects.hash(running, remaining, error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,47 +6,36 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.q.DownloadQ;
|
||||
import tn.mnlr.vripper.q.ExecutionService;
|
||||
import tn.mnlr.vripper.q.PendingQ;
|
||||
|
||||
@Service
|
||||
@EnableScheduling
|
||||
public class GlobalStateService {
|
||||
|
||||
@Autowired
|
||||
private DownloadQ downloadQ;
|
||||
|
||||
@Autowired
|
||||
private ExecutionService executionService;
|
||||
|
||||
@Autowired
|
||||
private AppStateService appStateService;
|
||||
private final PendingQ pendingQ;
|
||||
private final ExecutionService executionService;
|
||||
private final DataService dataService;
|
||||
|
||||
@Getter
|
||||
private GlobalState currentState;
|
||||
|
||||
@Getter
|
||||
private PublishProcessor<GlobalState> liveGlobalState = PublishProcessor.create();
|
||||
private final PublishProcessor<GlobalState> liveGlobalState = PublishProcessor.create();
|
||||
|
||||
public GlobalStateService() {
|
||||
@Autowired
|
||||
public GlobalStateService(PendingQ pendingQ, ExecutionService executionService, DataService dataService) {
|
||||
this.pendingQ = pendingQ;
|
||||
this.executionService = executionService;
|
||||
this.dataService = dataService;
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 3000)
|
||||
private void interval() {
|
||||
GlobalState newGlobalState = new GlobalState(
|
||||
executionService.runningCount(),
|
||||
downloadQ.size(),
|
||||
appStateService.getCurrentImages()
|
||||
.values()
|
||||
.stream()
|
||||
.filter(e -> e.getTotal() == 0 || e.getTotal() != e.getCurrent().get())
|
||||
.count(),
|
||||
appStateService.getCurrentImages()
|
||||
.values()
|
||||
.stream()
|
||||
.filter(e -> e.getStatus().equals(Image.Status.ERROR))
|
||||
.count());
|
||||
pendingQ.size(),
|
||||
dataService.countErrorImages());
|
||||
if (!newGlobalState.equals(currentState)) {
|
||||
currentState = newGlobalState;
|
||||
liveGlobalState.onNext(currentState);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
@Service
|
||||
public class MutexService {
|
||||
|
||||
private final Map<String, ReentrantLock> postLock = new ConcurrentHashMap<>();
|
||||
|
||||
public synchronized void createPostLock(String postId) {
|
||||
if (!postLock.containsKey(postId)) {
|
||||
postLock.put(postId, new ReentrantLock());
|
||||
}
|
||||
}
|
||||
|
||||
public void removePostLock(String postId) {
|
||||
postLock.remove(postId);
|
||||
}
|
||||
|
||||
public ReentrantLock getPostLock(String postId) {
|
||||
return postLock.get(postId);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,123 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import lombok.NonNull;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.entities.Post;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PathService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PathService.class);
|
||||
private final AppSettingsService appSettingsService;
|
||||
private final DataService dataService;
|
||||
private final MutexService mutexService;
|
||||
|
||||
private final CommonExecutor commonExecutor;
|
||||
|
||||
@Autowired
|
||||
private AppStateService appStateService;
|
||||
|
||||
@Autowired
|
||||
private AppSettingsService appSettingsService;
|
||||
|
||||
public final File getDownloadDestinationFolder(String postId) {
|
||||
Post post = appStateService.getCurrentPosts().get(postId);
|
||||
String postTitle = post.getTitle();
|
||||
String threadTitle = post.getThreadTitle();
|
||||
File sourceFolder = appSettingsService.isSubLocation() ? new File(appSettingsService.getDownloadPath(), sanitize(post.getForum())) : new File(appSettingsService.getDownloadPath());
|
||||
sourceFolder = appSettingsService.isThreadSubLocation() ? new File(sourceFolder, threadTitle) : sourceFolder;
|
||||
return new File(sourceFolder, sanitize(postTitle + "_" + postId));
|
||||
public PathService(AppSettingsService appSettingsService, DataService dataService, MutexService mutexService, CommonExecutor commonExecutor) {
|
||||
this.appSettingsService = appSettingsService;
|
||||
this.dataService = dataService;
|
||||
this.mutexService = mutexService;
|
||||
this.commonExecutor = commonExecutor;
|
||||
}
|
||||
|
||||
public final String sanitize(final String folderName) {
|
||||
public final File getDownloadDestinationFolder(Post post) {
|
||||
return _getDownloadDestinationFolder(post.getForum(), post.getThreadTitle(), post.getPostFolderName());
|
||||
}
|
||||
|
||||
private File _getDownloadDestinationFolder(@NonNull String forum, @NonNull String threadTitle, @NonNull String title) {
|
||||
File sourceFolder = appSettingsService.getSettings().getSubLocation() ? new File(appSettingsService.getSettings().getDownloadPath(), sanitize(forum)) : new File(appSettingsService.getSettings().getDownloadPath());
|
||||
sourceFolder = appSettingsService.getSettings().getThreadSubLocation() ? new File(sourceFolder, threadTitle) : sourceFolder;
|
||||
return new File(sourceFolder, title);
|
||||
}
|
||||
|
||||
public final void createDefaultPostFolder(Post post) {
|
||||
File sourceFolder = _getDownloadDestinationFolder(post.getForum(), post.getThreadTitle(), sanitize(post.getTitle()));
|
||||
File destFolder = makeDirs(sourceFolder);
|
||||
post.setPostFolderName(destFolder.getName());
|
||||
dataService.updatePostFolderName(post.getPostFolderName(), post.getId());
|
||||
}
|
||||
|
||||
public final void rename(@NonNull String postId, @NonNull String altName) {
|
||||
commonExecutor.getGeneralExecutor().submit(() -> {
|
||||
|
||||
ReentrantLock postLock = mutexService.getPostLock(postId);
|
||||
if (postLock != null) {
|
||||
postLock.lock();
|
||||
}
|
||||
|
||||
try {
|
||||
Optional<Post> _post = dataService.findPostByPostId(postId);
|
||||
if (_post.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Post post = _post.get();
|
||||
if (altName.equals(post.getTitle())) {
|
||||
return;
|
||||
}
|
||||
post.setTitle(altName);
|
||||
dataService.updatePostTitle(post.getTitle(), post.getId());
|
||||
if (post.getPostFolderName() == null) {
|
||||
return;
|
||||
}
|
||||
File newDestFolder = makeDirs(_getDownloadDestinationFolder(post.getForum(), post.getThreadTitle(), sanitize(altName)));
|
||||
File currentDesFolder = getDownloadDestinationFolder(post);
|
||||
post.setPostFolderName(newDestFolder.getName());
|
||||
dataService.updatePostFolderName(post.getPostFolderName(), post.getId());
|
||||
|
||||
List<File> files = Optional.ofNullable(currentDesFolder.listFiles()).stream().flatMap(Arrays::stream).filter(e -> !e.getName().endsWith(".tmp")).collect(Collectors.toList());
|
||||
for (File f : files) {
|
||||
try {
|
||||
Files.move(f.toPath(), Paths.get(newDestFolder.toString(), f.toPath().getFileName().toString()), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (IOException e) {
|
||||
log.error(String.format("Failed to move files from %s to %s", currentDesFolder.toString(), newDestFolder.toString()), e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!currentDesFolder.delete()) {
|
||||
log.warn(String.format("Failed to remove %s", currentDesFolder.toString()));
|
||||
}
|
||||
} finally {
|
||||
if (postLock != null) {
|
||||
postLock.unlock();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private File makeDirs(@NonNull final File sourceFolder) {
|
||||
int counter = 1;
|
||||
File folder = sourceFolder;
|
||||
|
||||
while (folder.exists()) {
|
||||
folder = new File(sourceFolder.toString() + '.' + counter++);
|
||||
}
|
||||
|
||||
if (!folder.mkdirs()) {
|
||||
throw new RuntimeException(String.format("Failed to create the folder %s", sourceFolder.toString()));
|
||||
}
|
||||
|
||||
return folder;
|
||||
}
|
||||
|
||||
private String sanitize(final String folderName) {
|
||||
String sanitizedFolderName = folderName.replaceAll("\\.|\\\\|/|\\||:|\\?|\\*|\"|<|>|\\p{Cntrl}", "_");
|
||||
logger.debug(String.format("%s sanitized to %s", folderName, sanitizedFolderName));
|
||||
log.debug(String.format("%s sanitized to %s", folderName, sanitizedFolderName));
|
||||
return sanitizedFolderName;
|
||||
}
|
||||
|
||||
@@ -41,13 +128,6 @@ public class PathService {
|
||||
* @return Sanitized local path string
|
||||
*/
|
||||
public final String formatImageFileName(String imageName) {
|
||||
int extensionIndex = imageName.lastIndexOf('.');
|
||||
String fileName;
|
||||
if (extensionIndex != -1) {
|
||||
fileName = imageName.substring(0, extensionIndex);
|
||||
} else {
|
||||
fileName = imageName;
|
||||
}
|
||||
return sanitize(fileName);
|
||||
return sanitize(imageName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.reactivex.disposables.Disposable;
|
||||
import io.reactivex.processors.PublishProcessor;
|
||||
import lombok.Getter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.SpringContext;
|
||||
import tn.mnlr.vripper.VripperApplication;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.entities.Post;
|
||||
import tn.mnlr.vripper.entities.mixin.persistance.ImagePersistanceMixin;
|
||||
import tn.mnlr.vripper.entities.mixin.persistance.PostPersistanceMixin;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
public class PersistenceService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PersistenceService.class);
|
||||
|
||||
@Autowired
|
||||
private AppStateService stateService;
|
||||
|
||||
@Autowired
|
||||
private VripperApplication.AppCommandRunner appCommandRunner;
|
||||
|
||||
private ObjectMapper om;
|
||||
|
||||
private Disposable subscription;
|
||||
|
||||
@Getter
|
||||
private PublishProcessor<Map<String, Post>> processor = PublishProcessor.create();
|
||||
|
||||
private PersistenceService() {
|
||||
om = new ObjectMapper();
|
||||
om.addMixIn(Image.class, ImagePersistanceMixin.class);
|
||||
om.addMixIn(Post.class, PostPersistanceMixin.class);
|
||||
subscription = processor
|
||||
.onBackpressureLatest()
|
||||
.buffer(10, TimeUnit.SECONDS)
|
||||
.filter(e -> !e.isEmpty())
|
||||
.map(e -> e.get(0))
|
||||
.doOnNext(this::persist)
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
File dataFile = new File(appCommandRunner.getDataPath());
|
||||
if (!dataFile.exists()) {
|
||||
try {
|
||||
if (dataFile.getParentFile().mkdirs()) {
|
||||
logger.debug(String.format("%s is created", dataFile.getParentFile().toString()));
|
||||
}
|
||||
if (!dataFile.getParentFile().isDirectory() || !dataFile.getParentFile().canWrite()) {
|
||||
logger.error(String.format("Unable to write in %s", dataFile.getParent()));
|
||||
SpringContext.close();
|
||||
}
|
||||
|
||||
if (dataFile.createNewFile()) {
|
||||
logger.debug("Data file successfully created");
|
||||
try (FileWriter fw = new FileWriter(dataFile)) {
|
||||
fw.write("{}");
|
||||
}
|
||||
} else {
|
||||
logger.warn("Data file already exists");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
logger.error("Unable to create data file", e);
|
||||
SpringContext.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void preDestroy() {
|
||||
this.subscription.dispose();
|
||||
logger.info(String.format("Destroying %s", PersistenceService.class.getSimpleName()));
|
||||
logger.info("Persisting data before destroying");
|
||||
this.persist(stateService.getCurrentPosts());
|
||||
}
|
||||
|
||||
private void persist(Map<String, Post> currentPosts) {
|
||||
|
||||
try (PrintWriter out = new PrintWriter(appCommandRunner.getDataPath(), StandardCharsets.UTF_8)) {
|
||||
out.print(om.writeValueAsString(currentPosts));
|
||||
} catch (IOException e) {
|
||||
logger.error("Failed to persist app state", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Post> read(String content) {
|
||||
|
||||
try {
|
||||
return om.readValue(content, om.getTypeFactory().constructMapType(HashMap.class, String.class, Post.class));
|
||||
} catch (IOException e) {
|
||||
logger.error("Failed to read app state", e);
|
||||
long timestamp = new Date().getTime();
|
||||
logger.warn(String.format("trying to rename old data file from %s to %s", appCommandRunner.getDataPath(), appCommandRunner.getDataPath() + "." + timestamp + ".old"));
|
||||
try {
|
||||
Files.move(new File(appCommandRunner.getDataPath()).toPath(), new File(appCommandRunner.getDataPath() + "." + timestamp + ".old").toPath());
|
||||
} catch (IOException ex) {
|
||||
logger.error(String.format("Failed to rename %s to %s", appCommandRunner.getDataPath(), appCommandRunner.getDataPath() + ".old"));
|
||||
SpringContext.close();
|
||||
}
|
||||
}
|
||||
|
||||
return new HashMap<>();
|
||||
}
|
||||
|
||||
public void restore() {
|
||||
|
||||
String jsonContent = null;
|
||||
try {
|
||||
jsonContent = String.join("", Files.readAllLines(Paths.get(appCommandRunner.getDataPath()), StandardCharsets.UTF_8));
|
||||
} catch (Exception e) {
|
||||
logger.error("data file cannot be read, previous state cannot be restored", e);
|
||||
SpringContext.close();
|
||||
}
|
||||
|
||||
Map<String, Post> read = read(jsonContent);
|
||||
|
||||
stateService.getCurrentPosts().clear();
|
||||
stateService.getCurrentPosts().putAll(read);
|
||||
stateService.getCurrentPosts().values().forEach(p -> {
|
||||
if (Arrays.asList(Post.Status.DOWNLOADING, Post.Status.PARTIAL, Post.Status.PENDING).contains(p.getStatus())) {
|
||||
p.setStatus(Post.Status.STOPPED);
|
||||
}
|
||||
});
|
||||
|
||||
stateService.getCurrentImages().clear();
|
||||
read.values().stream().flatMap(e -> e.getImages().stream()).forEach(e -> {
|
||||
e.setAppStateService(stateService);
|
||||
stateService.getCurrentImages().put(e.getUrl(), e);
|
||||
});
|
||||
|
||||
read.values().forEach(e -> e.setAppStateService(stateService));
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.entities.Post;
|
||||
import tn.mnlr.vripper.exception.PostParseException;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.q.DownloadQ;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class PostParser {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PostParser.class);
|
||||
|
||||
static final String VR_API = "https://vipergirls.to/vr.php";
|
||||
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
|
||||
@Autowired
|
||||
private AppStateService appStateService;
|
||||
|
||||
@Autowired
|
||||
private VipergirlsAuthService authService;
|
||||
|
||||
@Autowired
|
||||
private AppSettingsService appSettingsService;
|
||||
|
||||
@Autowired
|
||||
private DownloadQ downloadQ;
|
||||
|
||||
@Autowired
|
||||
private VipergirlsAuthService vipergirlsAuthService;
|
||||
|
||||
@Autowired
|
||||
private List<Host> supportedHosts;
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
|
||||
}
|
||||
|
||||
public void addPost(String postId, String threadId) throws PostParseException {
|
||||
|
||||
if (appStateService.getCurrentPosts().containsKey(postId)) {
|
||||
logger.warn(String.format("skipping %s, already loaded", postId));
|
||||
return;
|
||||
}
|
||||
|
||||
VRPostParser vrPostParser = new VRPostParser(threadId, postId, cm, vipergirlsAuthService, supportedHosts);
|
||||
Post post = vrPostParser.parse();
|
||||
|
||||
post.setAppStateService(appStateService);
|
||||
post.getImages().forEach(e -> e.setAppStateService(appStateService));
|
||||
authService.leaveThanks(post.getUrl(), post.getPostId());
|
||||
if (appSettingsService.isAutoStart()) {
|
||||
logger.debug("Auto start downloads option is enabled");
|
||||
logger.debug(String.format("Starting to enqueue %d jobs for %s", post.getImages().size(), post.getUrl()));
|
||||
post.setStatus(Post.Status.PENDING);
|
||||
try {
|
||||
downloadQ.enqueue(post);
|
||||
} catch (InterruptedException e) {
|
||||
logger.warn("Interruption was caught");
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
logger.debug(String.format("Done enqueuing jobs for %s", post.getUrl()));
|
||||
} else {
|
||||
post.setStatus(Post.Status.STOPPED);
|
||||
logger.debug("Auto start downloads option is disabled");
|
||||
}
|
||||
}
|
||||
|
||||
public VRThreadParser createVRThreadParser(String threadId) {
|
||||
return new VRThreadParser(threadId, cm, vipergirlsAuthService);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
@ToString
|
||||
public class QueuedVGLink {
|
||||
|
||||
private final String type = "grabQueue";
|
||||
private final String link;
|
||||
private final String threadId;
|
||||
private final String postId;
|
||||
@Setter
|
||||
boolean removed;
|
||||
|
||||
public QueuedVGLink(String link, String threadId, String postId) {
|
||||
this.link = link;
|
||||
this.threadId = threadId;
|
||||
this.postId = postId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
QueuedVGLink that = (QueuedVGLink) o;
|
||||
return Objects.equals(link, that.link);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(link);
|
||||
}
|
||||
}
|
||||
@@ -4,46 +4,41 @@ import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import lombok.Getter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import lombok.NonNull;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.VripperApplication;
|
||||
import tn.mnlr.vripper.exception.PostParseException;
|
||||
import tn.mnlr.vripper.jpa.domain.Queued;
|
||||
import tn.mnlr.vripper.services.post.CachedPost;
|
||||
import tn.mnlr.vripper.services.post.PostService;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class VGHandler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VGHandler.class);
|
||||
|
||||
@Autowired
|
||||
private AppStateService appStateService;
|
||||
|
||||
@Autowired
|
||||
private PostParser postParser;
|
||||
private final DataService dataService;
|
||||
private final PostService postService;
|
||||
private final CommonExecutor commonExecutor;
|
||||
|
||||
@Getter
|
||||
private LoadingCache<String, List<VRPostState>> cache;
|
||||
private final LoadingCache<Queued, List<CachedPost>> cache;
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
@Autowired
|
||||
public VGHandler(DataService dataService, PostService postService, CommonExecutor commonExecutor) {
|
||||
this.dataService = dataService;
|
||||
this.postService = postService;
|
||||
this.commonExecutor = commonExecutor;
|
||||
|
||||
CacheLoader<String, List<VRPostState>> loader = new CacheLoader<>() {
|
||||
CacheLoader<Queued, List<CachedPost>> loader = new CacheLoader<>() {
|
||||
@Override
|
||||
public List<VRPostState> load(String threadId) throws Exception {
|
||||
VRThreadParser vrThreadParser = postParser.createVRThreadParser(threadId);
|
||||
List<VRPostState> posts = new ArrayList<>();
|
||||
vrThreadParser.parse();
|
||||
vrThreadParser.getPostPublishProcessor()
|
||||
.onBackpressureBuffer()
|
||||
.blockingSubscribe(posts::add);
|
||||
return posts;
|
||||
public List<CachedPost> load(@NonNull Queued queuedVGLink) throws Exception {
|
||||
VRThreadParser vrThreadParser = new VRThreadParser(queuedVGLink);
|
||||
return vrThreadParser.parse();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -52,35 +47,40 @@ public class VGHandler {
|
||||
.build(loader);
|
||||
}
|
||||
|
||||
public void handle(List<QueuedVGLink> queuedVGLinks) throws Exception {
|
||||
for (QueuedVGLink queuedVGLink : queuedVGLinks) {
|
||||
if (queuedVGLink.getPostId() != null) {
|
||||
postParser.addPost(queuedVGLink.getPostId(), queuedVGLink.getThreadId());
|
||||
public void handle(List<Queued> queuedList) throws Exception {
|
||||
for (Queued queued : queuedList) {
|
||||
if (queued.getPostId() != null) {
|
||||
postService.addPost(queued.getPostId(), queued.getThreadId());
|
||||
} else {
|
||||
appStateService.getGrabQueue().put(queuedVGLink.getLink(), queuedVGLink);
|
||||
appStateService.getLiveGrabQueue().onNext(queuedVGLink);
|
||||
|
||||
Callable<Void> cl = () -> {
|
||||
List<VRPostState> vrPostStates = cache.get(queuedVGLink.getThreadId());
|
||||
logger.debug(String.format("%d found for %s", vrPostStates.size(), queuedVGLink.getLink()));
|
||||
if (vrPostStates.size() == 1) {
|
||||
postParser.addPost(vrPostStates.get(0).getPostId(), vrPostStates.get(0).getThreadId());
|
||||
remove(queuedVGLink.getLink());
|
||||
logger.debug(String.format("threadId %s, postId %s is added automatically for download", queuedVGLink.getThreadId(), queuedVGLink.getPostId()));
|
||||
Runnable runnable = () -> {
|
||||
List<CachedPost> cachedPosts;
|
||||
try {
|
||||
cachedPosts = cache.get(queued);
|
||||
} catch (ExecutionException e) {
|
||||
log.error(String.format("Failed to add post with thread id %s, postId %s", queued.getThreadId(), queued.getPostId()), e);
|
||||
return;
|
||||
}
|
||||
queued.setTotal(cachedPosts.size());
|
||||
queued.done();
|
||||
log.debug(String.format("%d found for %s", cachedPosts.size(), queued.getLink()));
|
||||
if (cachedPosts.size() == 1) {
|
||||
try {
|
||||
postService.addPost(cachedPosts.get(0).getPostId(), cachedPosts.get(0).getThreadId());
|
||||
} catch (PostParseException e) {
|
||||
log.error(String.format("Failed to add post with postId %s", cachedPosts.get(0).getPostId()), e);
|
||||
return;
|
||||
}
|
||||
log.debug(String.format("threadId %s, postId %s is added automatically for download", queued.getThreadId(), queued.getPostId()));
|
||||
} else {
|
||||
dataService.newQueueLink(queued);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
VripperApplication.commonExecutor.submit(cl);
|
||||
commonExecutor.getGeneralExecutor().submit(runnable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void remove(String url) {
|
||||
Optional.ofNullable(appStateService.getGrabQueue().remove(url)).ifPresent(e -> {
|
||||
e.setRemoved(true);
|
||||
appStateService.getLiveGrabQueue().onNext(e);
|
||||
});
|
||||
public void remove(String threadId) {
|
||||
dataService.removeQueueLink(threadId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import lombok.Getter;
|
||||
import net.jodah.failsafe.Failsafe;
|
||||
import net.jodah.failsafe.RetryPolicy;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.xml.sax.Attributes;
|
||||
import org.xml.sax.helpers.DefaultHandler;
|
||||
import tn.mnlr.vripper.entities.Image;
|
||||
import tn.mnlr.vripper.entities.Post;
|
||||
import tn.mnlr.vripper.exception.DownloadException;
|
||||
import tn.mnlr.vripper.exception.PostParseException;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
|
||||
import javax.xml.parsers.SAXParserFactory;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static tn.mnlr.vripper.services.PostParser.VR_API;
|
||||
|
||||
class VRPostParser {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VRPostParser.class);
|
||||
|
||||
private static SAXParserFactory factory = SAXParserFactory.newInstance();
|
||||
|
||||
private static RetryPolicy<Object> retryPolicy = new RetryPolicy<>()
|
||||
.handleIf(e -> e instanceof IOException)
|
||||
.withBackoff(5, 30, ChronoUnit.SECONDS)
|
||||
.withMaxRetries(4)
|
||||
.abortOn(InterruptedException.class)
|
||||
.onFailedAttempt(e -> logger.warn(String.format("#%d tries failed", e.getAttemptCount()), e.getLastFailure()));
|
||||
|
||||
private final String threadId;
|
||||
private final String postId;
|
||||
private final ConnectionManager cm;
|
||||
private final VipergirlsAuthService vipergirlsAuthService;
|
||||
private final List<Host> supportedHosts;
|
||||
|
||||
VRPostParser(String threadId, String postId, ConnectionManager cm, VipergirlsAuthService vipergirlsAuthService, List<Host> supportedHosts) {
|
||||
this.threadId = threadId;
|
||||
this.postId = postId;
|
||||
this.cm = cm;
|
||||
this.vipergirlsAuthService = vipergirlsAuthService;
|
||||
this.supportedHosts = supportedHosts;
|
||||
}
|
||||
|
||||
public Post parse() throws PostParseException {
|
||||
|
||||
logger.debug(String.format("Parsing post %s", postId));
|
||||
HttpGet httpGet;
|
||||
try {
|
||||
URIBuilder uriBuilder = new URIBuilder(VR_API);
|
||||
uriBuilder.setParameter("p", postId);
|
||||
httpGet = cm.buildHttpGet(uriBuilder.build());
|
||||
} catch (URISyntaxException e) {
|
||||
throw new PostParseException(e);
|
||||
}
|
||||
VRPostHandler handler = new VRPostHandler(threadId, postId, supportedHosts);
|
||||
AtomicReference<Throwable> thr = new AtomicReference<>();
|
||||
logger.debug(String.format("Requesting %s", httpGet));
|
||||
Post post = Failsafe.with(retryPolicy)
|
||||
.onFailure(e -> thr.set(e.getFailure()))
|
||||
.get(() -> {
|
||||
HttpClient connection = cm.getClient().build();
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) connection.execute(httpGet, vipergirlsAuthService.getContext())) {
|
||||
if (response.getStatusLine().getStatusCode() / 100 != 2) {
|
||||
throw new DownloadException(String.format("Unexpected response code '%d' for %s", response.getStatusLine().getStatusCode(), httpGet));
|
||||
}
|
||||
|
||||
try {
|
||||
factory.newSAXParser().parse(new BufferedInputStream(response.getEntity().getContent()), handler);
|
||||
return handler.getParsedPost();
|
||||
} catch (Exception e) {
|
||||
throw new PostParseException(String.format("Failed to parse thread %s, post %s", threadId, postId), e);
|
||||
} finally {
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
}
|
||||
}
|
||||
});
|
||||
if (thr.get() != null || post == null) {
|
||||
logger.error(String.format("parsing failed for thread %s, post %s", threadId, postId), thr.get());
|
||||
throw new PostParseException(thr.get());
|
||||
}
|
||||
return post;
|
||||
}
|
||||
}
|
||||
|
||||
class VRPostHandler extends DefaultHandler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VRPostHandler.class);
|
||||
|
||||
private final List<Host> supportedHosts;
|
||||
|
||||
private final String threadId;
|
||||
private final String postId;
|
||||
private String threadTitle;
|
||||
|
||||
private int previewCounter = 0;
|
||||
private int index = 0;
|
||||
|
||||
private String postTitle;
|
||||
private int imageCount;
|
||||
|
||||
private String forum;
|
||||
|
||||
private List<String> previews = new ArrayList<>();
|
||||
private List<Image> images = new ArrayList<>();
|
||||
@Getter
|
||||
private Post parsedPost;
|
||||
|
||||
VRPostHandler(String threadId, String postId, List<Host> supportedHosts) {
|
||||
this.threadId = threadId;
|
||||
this.postId = postId;
|
||||
this.supportedHosts = supportedHosts;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startDocument() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startElement(String uri, String localName, String qName, Attributes attributes) {
|
||||
|
||||
switch (qName.toLowerCase()) {
|
||||
case "forum":
|
||||
forum = attributes.getValue("title").trim();
|
||||
break;
|
||||
case "thread":
|
||||
threadTitle = attributes.getValue("title").trim();
|
||||
break;
|
||||
case "post":
|
||||
imageCount = Integer.parseInt(attributes.getValue("imagecount").trim());
|
||||
postTitle = Optional.ofNullable(attributes.getValue("title")).map(e -> e.trim().isEmpty() ? null : e.trim()).orElse(threadTitle);
|
||||
break;
|
||||
case "image":
|
||||
index++;
|
||||
if (previewCounter++ < 4) {
|
||||
Optional.ofNullable(attributes.getValue("thumb_url")).map(String::trim).ifPresent(thumbUrl -> previews.add(thumbUrl));
|
||||
}
|
||||
|
||||
String mainUrl = Optional.ofNullable(attributes.getValue("main_url")).map(String::trim).orElse(null);
|
||||
if (mainUrl != null) {
|
||||
Host foundHost = supportedHosts.stream().filter(host -> host.isSupported(mainUrl)).findFirst().orElse(null);
|
||||
if (foundHost != null) {
|
||||
logger.debug(String.format("Found supported host %s for %s", foundHost.getClass().getSimpleName(), mainUrl));
|
||||
images.add(new Image(mainUrl, postId, postTitle, foundHost, index));
|
||||
} else {
|
||||
logger.warn(String.format("unsupported host for %s, skipping", mainUrl));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endElement(String uri, String localName, String qName) {
|
||||
if ("post".equals(qName.toLowerCase())) {
|
||||
if (imageCount != 0) {
|
||||
HashMap<String, Object> metadata = new HashMap<>();
|
||||
metadata.put("PREVIEWS", previews);
|
||||
parsedPost = new Post(
|
||||
postTitle,
|
||||
String.format("https://vipergirls.to/threads/%s/?p=%s&viewfull=1#post%s", threadId, postId, postId),
|
||||
images,
|
||||
metadata,
|
||||
postId,
|
||||
threadId,
|
||||
threadTitle,
|
||||
forum
|
||||
);
|
||||
}
|
||||
index = 0;
|
||||
previewCounter = 0;
|
||||
previews = new ArrayList<>();
|
||||
images = new ArrayList<>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
public class VRPostState {
|
||||
private final String type = "postParse";
|
||||
private final String threadId;
|
||||
private String postId;
|
||||
private int number;
|
||||
private String title;
|
||||
private int imageCount;
|
||||
private String url;
|
||||
private List<String> previews;
|
||||
|
||||
VRPostState(String threadId, String postId, int number, String title, int imageCount, String url, List<String> previews) {
|
||||
this.threadId = threadId;
|
||||
this.postId = postId;
|
||||
this.number = number;
|
||||
this.title = title;
|
||||
this.imageCount = imageCount;
|
||||
this.previews = previews;
|
||||
this.url = url;
|
||||
}
|
||||
}
|
||||
@@ -1,73 +1,63 @@
|
||||
package tn.mnlr.vripper.services;
|
||||
|
||||
import io.reactivex.processors.ReplayProcessor;
|
||||
import lombok.Getter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.jodah.failsafe.Failsafe;
|
||||
import net.jodah.failsafe.RetryPolicy;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.xml.sax.Attributes;
|
||||
import org.xml.sax.helpers.DefaultHandler;
|
||||
import tn.mnlr.vripper.SpringContext;
|
||||
import tn.mnlr.vripper.VripperApplication;
|
||||
import tn.mnlr.vripper.exception.DownloadException;
|
||||
import tn.mnlr.vripper.exception.PostParseException;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.jpa.domain.Queued;
|
||||
import tn.mnlr.vripper.services.post.CachedPost;
|
||||
|
||||
import javax.xml.parsers.SAXParserFactory;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static tn.mnlr.vripper.services.PostParser.VR_API;
|
||||
|
||||
@Slf4j
|
||||
public class VRThreadParser {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VRThreadParser.class);
|
||||
private static final String VR_API = "https://vipergirls.to/vr.php";
|
||||
|
||||
private static RetryPolicy<Object> retryPolicy = new RetryPolicy<>()
|
||||
.handleIf(e -> e instanceof IOException)
|
||||
.withBackoff(5, 30, ChronoUnit.SECONDS)
|
||||
.withMaxRetries(4)
|
||||
.abortOn(InterruptedException.class)
|
||||
.onFailedAttempt(e -> logger.warn(String.format("#%d tries failed", e.getAttemptCount()), e.getLastFailure()));
|
||||
private static SAXParserFactory factory = SAXParserFactory.newInstance();
|
||||
@Getter
|
||||
private final ReplayProcessor<VRPostState> postPublishProcessor = ReplayProcessor.create();
|
||||
private final String threadId;
|
||||
private static final SAXParserFactory factory = SAXParserFactory.newInstance();
|
||||
private final Queued queued;
|
||||
private final ConnectionManager cm;
|
||||
private final VipergirlsAuthService vipergirlsAuthService;
|
||||
|
||||
|
||||
VRThreadParser(String threadId, ConnectionManager cm, VipergirlsAuthService vipergirlsAuthService) {
|
||||
this.threadId = threadId;
|
||||
this.cm = cm;
|
||||
this.vipergirlsAuthService = vipergirlsAuthService;
|
||||
VRThreadParser(Queued queued) {
|
||||
this.queued = queued;
|
||||
this.cm = SpringContext.getBean(ConnectionManager.class);
|
||||
this.vipergirlsAuthService = SpringContext.getBean(VipergirlsAuthService.class);
|
||||
}
|
||||
|
||||
public Void parse() throws PostParseException {
|
||||
public List<CachedPost> parse() throws PostParseException {
|
||||
|
||||
logger.debug(String.format("Parsing thread %s", threadId));
|
||||
log.debug(String.format("Parsing thread %s", queued));
|
||||
HttpGet httpGet;
|
||||
try {
|
||||
URIBuilder uriBuilder = new URIBuilder(VR_API);
|
||||
uriBuilder.setParameter("t", threadId);
|
||||
uriBuilder.setParameter("t", queued.getThreadId());
|
||||
httpGet = cm.buildHttpGet(uriBuilder.build());
|
||||
} catch (URISyntaxException e) {
|
||||
throw new PostParseException(e);
|
||||
}
|
||||
|
||||
VRThreadHandler handler = new VRThreadHandler(threadId, postPublishProcessor);
|
||||
VRThreadHandler handler = new VRThreadHandler(queued);
|
||||
AtomicReference<Throwable> thr = new AtomicReference<>();
|
||||
logger.debug(String.format("Requesting %s", httpGet));
|
||||
Failsafe.with(retryPolicy)
|
||||
log.debug(String.format("Requesting %s", httpGet));
|
||||
List<CachedPost> posts = Failsafe.with(VripperApplication.retryPolicy)
|
||||
.onFailure(e -> thr.set(e.getFailure()))
|
||||
.get(() -> {
|
||||
HttpClient connection = cm.getClient().build();
|
||||
@@ -78,37 +68,41 @@ public class VRThreadParser {
|
||||
|
||||
try {
|
||||
factory.newSAXParser().parse(new BufferedInputStream(response.getEntity().getContent()), handler);
|
||||
return handler.getPosts();
|
||||
} catch (Exception e) {
|
||||
throw new PostParseException(String.format("Failed to parse thread %s", threadId), e);
|
||||
throw new PostParseException(String.format("Failed to parse thread %s", queued), e);
|
||||
} finally {
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
if (thr.get() != null) {
|
||||
logger.error(String.format("parsing failed for thread %s", threadId), thr.get());
|
||||
log.error(String.format("parsing failed for thread %s", queued), thr.get());
|
||||
throw new PostParseException(thr.get());
|
||||
}
|
||||
return null;
|
||||
return posts;
|
||||
}
|
||||
}
|
||||
|
||||
class VRThreadHandler extends DefaultHandler {
|
||||
|
||||
private final String threadId;
|
||||
private final ReplayProcessor<VRPostState> vrPostPublishProcessor;
|
||||
private final Queued queued;
|
||||
private final Collection<Host> supportedHosts;
|
||||
private final Map<Host, AtomicInteger> hostMap = new HashMap<>();
|
||||
private List<String> previews = new ArrayList<>();
|
||||
private String threadTitle;
|
||||
private String postId;
|
||||
private String postTitle;
|
||||
private int imageCount;
|
||||
private int postCounter;
|
||||
private int previewCounter = 0;
|
||||
private List<String> previews = new ArrayList<>();
|
||||
|
||||
VRThreadHandler(String threadId, ReplayProcessor<VRPostState> vrPostPublishProcessor) {
|
||||
this.vrPostPublishProcessor = vrPostPublishProcessor;
|
||||
this.threadId = threadId;
|
||||
@Getter
|
||||
private List<CachedPost> posts = new ArrayList<>();
|
||||
|
||||
VRThreadHandler(Queued queued) {
|
||||
this.queued = queued;
|
||||
this.supportedHosts = SpringContext.getBeansOfType(Host.class).values();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -129,8 +123,12 @@ class VRThreadHandler extends DefaultHandler {
|
||||
postTitle = Optional.ofNullable(attributes.getValue("title")).map(e -> e.trim().isEmpty() ? null : e.trim()).orElse(threadTitle);
|
||||
break;
|
||||
case "image":
|
||||
Optional.ofNullable(attributes.getValue("main_url"))
|
||||
.map(String::trim)
|
||||
.flatMap(mainUrl -> supportedHosts.stream().filter(host -> host.isSupported(mainUrl)).findFirst())
|
||||
.ifPresent(host -> Optional.ofNullable(hostMap.get(host)).ifPresentOrElse(AtomicInteger::incrementAndGet, () -> hostMap.put(host, new AtomicInteger(0))));
|
||||
if (previewCounter++ < 4) {
|
||||
Optional.ofNullable(attributes.getValue("thumb_url")).map(String::trim).ifPresent(thumbUrl -> previews.add(thumbUrl));
|
||||
Optional.ofNullable(attributes.getValue("thumb_url")).map(String::trim).ifPresent(previews::add);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -140,23 +138,26 @@ class VRThreadHandler extends DefaultHandler {
|
||||
public void endElement(String uri, String localName, String qName) {
|
||||
if ("post".equals(qName.toLowerCase())) {
|
||||
if (imageCount != 0) {
|
||||
vrPostPublishProcessor.onNext(new VRPostState(
|
||||
threadId,
|
||||
posts.add(new CachedPost(
|
||||
queued.getThreadId(),
|
||||
postId,
|
||||
postCounter,
|
||||
postTitle,
|
||||
imageCount,
|
||||
String.format("https://vipergirls.to/threads/%s/?p=%s&viewfull=1#post%s", threadId, postId, postId),
|
||||
previews
|
||||
String.format("https://vipergirls.to/threads/?p=%s&viewfull=1#post%s", postId, postId),
|
||||
previews,
|
||||
hostMap.entrySet().stream().filter(v -> v.getValue().get() > 0).map(e -> e.getKey().getHost() + " (" + e.getValue().get() + ")").collect(Collectors.joining(", "))
|
||||
));
|
||||
queued.increment();
|
||||
}
|
||||
previewCounter = 0;
|
||||
previews = new ArrayList<>();
|
||||
hostMap.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endDocument() {
|
||||
vrPostPublishProcessor.onComplete();
|
||||
queued.done();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@ package tn.mnlr.vripper.services;
|
||||
|
||||
import io.reactivex.processors.PublishProcessor;
|
||||
import lombok.Getter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.cookie.Cookie;
|
||||
@@ -13,79 +13,72 @@ import org.apache.http.impl.client.BasicCookieStore;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import tn.mnlr.vripper.VripperApplication;
|
||||
import tn.mnlr.vripper.exception.VripperException;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class VipergirlsAuthService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VipergirlsAuthService.class);
|
||||
|
||||
@Autowired
|
||||
private ConnectionManager cm;
|
||||
|
||||
@Autowired
|
||||
private HtmlProcessorService htmlProcessorService;
|
||||
|
||||
@Autowired
|
||||
private XpathService xpathService;
|
||||
|
||||
@Autowired
|
||||
private AppSettingsService appSettingsService;
|
||||
private final ConnectionManager cm;
|
||||
private final AppSettingsService appSettingsService;
|
||||
private final CommonExecutor commonExecutor;
|
||||
private final DataService dataService;
|
||||
|
||||
@Getter
|
||||
private HttpClientContext context = HttpClientContext.create();
|
||||
private final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
@Getter
|
||||
private boolean authenticated = false;
|
||||
|
||||
@Getter
|
||||
private String loggedUser;
|
||||
private String loggedUser = "";
|
||||
|
||||
@Getter
|
||||
private PublishProcessor<String> loggedInUser = PublishProcessor.create();
|
||||
private final PublishProcessor<String> loggedInUser = PublishProcessor.create();
|
||||
|
||||
@Autowired
|
||||
public VipergirlsAuthService(ConnectionManager cm, AppSettingsService appSettingsService, CommonExecutor commonExecutor, DataService dataService) {
|
||||
this.cm = cm;
|
||||
this.appSettingsService = appSettingsService;
|
||||
this.commonExecutor = commonExecutor;
|
||||
this.dataService = dataService;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
context.setCookieStore(new BasicCookieStore());
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
private void destroy() throws InterruptedException {
|
||||
logger.info("Shutting down VipergirlsAuthService");
|
||||
VripperApplication.commonExecutor.shutdown();
|
||||
VripperApplication.commonExecutor.awaitTermination(10, TimeUnit.SECONDS);
|
||||
try {
|
||||
authenticate();
|
||||
} catch (VripperException e) {
|
||||
log.error("Cannot authenticate user with ViperGirls", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void authenticate() throws VripperException {
|
||||
|
||||
logger.info("Authenticating using ViperGirls credentials");
|
||||
log.info("Authenticating using ViperGirls credentials");
|
||||
authenticated = false;
|
||||
|
||||
if(!appSettingsService.isVLogin()) {
|
||||
logger.debug("Authentication option is disabled");
|
||||
if (!appSettingsService.getSettings().getVLogin()) {
|
||||
log.debug("Authentication option is disabled");
|
||||
context.getCookieStore().clear();
|
||||
loggedUser = "";
|
||||
loggedInUser.onNext(loggedUser);
|
||||
return;
|
||||
}
|
||||
|
||||
String username = appSettingsService.getVUsername();
|
||||
String password = appSettingsService.getVPassword();
|
||||
String username = appSettingsService.getSettings().getVUsername();
|
||||
String password = appSettingsService.getSettings().getVPassword();
|
||||
|
||||
if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
|
||||
logger.error("Cannot authenticate with ViperGirls credentials, username or password is empty");
|
||||
log.error("Cannot authenticate with ViperGirls credentials, username or password is empty");
|
||||
context.getCookieStore().clear();
|
||||
loggedUser = "";
|
||||
loggedInUser.onNext(loggedUser);
|
||||
@@ -95,14 +88,10 @@ public class VipergirlsAuthService {
|
||||
HttpPost postAuth = cm.buildHttpPost("https://vipergirls.to/login.php?do=login");
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
params.add(new BasicNameValuePair("vb_login_username", username));
|
||||
params.add(new BasicNameValuePair("vb_login_password", ""));
|
||||
params.add(new BasicNameValuePair("vb_login_password_hint", "Password"));
|
||||
|
||||
params.add(new BasicNameValuePair("cookieuser", "1"));
|
||||
params.add(new BasicNameValuePair("securitytoken", "guest"));
|
||||
params.add(new BasicNameValuePair("do", "login"));
|
||||
params.add(new BasicNameValuePair("vb_login_md5password", password));
|
||||
params.add(new BasicNameValuePair("vb_login_md5password_utf", password));
|
||||
try {
|
||||
postAuth.setEntity(new UrlEncodedFormEntity(params));
|
||||
} catch (Exception e) {
|
||||
@@ -123,7 +112,7 @@ public class VipergirlsAuthService {
|
||||
throw new VripperException(String.format("Unexpected response code returned %s", response.getStatusLine().getStatusCode()));
|
||||
}
|
||||
String responseBody = EntityUtils.toString(response.getEntity());
|
||||
logger.debug(String.format("Authentication with ViperGirls response body:%n%s", responseBody));
|
||||
log.debug(String.format("Authentication with ViperGirls response body:%n%s", responseBody));
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
if (context.getCookieStore().getCookies().stream().map(Cookie::getName).noneMatch(e -> e.equals("vg_userid"))) {
|
||||
throw new VripperException("Failed to authenticate user with ViperRipper");
|
||||
@@ -140,75 +129,44 @@ public class VipergirlsAuthService {
|
||||
}
|
||||
authenticated = true;
|
||||
loggedUser = username;
|
||||
logger.info(String.format("Authenticated: %s", username));
|
||||
log.info(String.format("Authenticated: %s", username));
|
||||
loggedInUser.onNext(loggedUser);
|
||||
}
|
||||
|
||||
void leaveThanks(String postUrl, String postId) {
|
||||
VripperApplication.commonExecutor.submit(() -> {
|
||||
if (!appSettingsService.isVLogin()) {
|
||||
logger.debug("Authentication with ViperGirls option is disabled");
|
||||
return;
|
||||
}
|
||||
if (!appSettingsService.isVThanks()) {
|
||||
logger.debug("Leave thanks option is disabled");
|
||||
return;
|
||||
}
|
||||
if (!authenticated) {
|
||||
logger.error("You are not authenticated");
|
||||
return;
|
||||
}
|
||||
public void leaveThanks(Post post) {
|
||||
if (!appSettingsService.getSettings().getVLogin()) {
|
||||
log.debug("Authentication with ViperGirls option is disabled");
|
||||
return;
|
||||
}
|
||||
if (!appSettingsService.getSettings().getVThanks()) {
|
||||
log.debug("Leave thanks option is disabled");
|
||||
return;
|
||||
}
|
||||
if (!authenticated) {
|
||||
log.error("You are not authenticated");
|
||||
return;
|
||||
}
|
||||
if (post.isThanked()) {
|
||||
log.debug("Already left a thanks");
|
||||
return;
|
||||
}
|
||||
commonExecutor.getGeneralExecutor().submit(() -> {
|
||||
try {
|
||||
postThanks(postId, getSecurityToken(postUrl));
|
||||
postThanks(post);
|
||||
} catch (Exception e) {
|
||||
logger.error(String.format("Failed to leave a thanks for url %s, post id %s", postUrl, postId), e);
|
||||
log.error(String.format("Failed to leave a thanks for url %s, post id %s", post.getUrl(), post.getPostId()), e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private String getSecurityToken(String url) throws VripperException {
|
||||
|
||||
String securityToken;
|
||||
|
||||
HttpGet httpGet = cm.buildHttpGet(url);
|
||||
httpGet.addHeader("Referer", "https://vipergirls.to/");
|
||||
httpGet.addHeader("Host", "vipergirls.to");
|
||||
|
||||
CloseableHttpClient client = cm.getClient().build();
|
||||
|
||||
try (CloseableHttpResponse response = client.execute(httpGet, context)) {
|
||||
|
||||
String postPage = EntityUtils.toString(response.getEntity());
|
||||
Document document = htmlProcessorService.clean(postPage);
|
||||
|
||||
String thanksUrl = xpathService
|
||||
.getAsNode(document, "//li[contains(@id,'post_')][not(contains(@id,'post_thank'))]//a[@class='post_thanks_button']")
|
||||
.getAttributes()
|
||||
.getNamedItem("href")
|
||||
.getTextContent()
|
||||
.trim();
|
||||
|
||||
securityToken = Arrays.stream(thanksUrl.split("&"))
|
||||
.filter(v -> v.startsWith("securitytoken"))
|
||||
.findAny()
|
||||
.orElse("")
|
||||
.replace("securitytoken=", "");
|
||||
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
} catch (Exception e) {
|
||||
throw new VripperException(e);
|
||||
}
|
||||
return securityToken;
|
||||
}
|
||||
|
||||
private void postThanks(String postId, String securityKey) throws VripperException {
|
||||
private void postThanks(Post post) throws VripperException {
|
||||
|
||||
HttpPost postThanks = cm.buildHttpPost("https://vipergirls.to/post_thanks.php");
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
params.add(new BasicNameValuePair("do", "post_thanks_add"));
|
||||
params.add(new BasicNameValuePair("using_ajax", "1"));
|
||||
params.add(new BasicNameValuePair("p", postId));
|
||||
params.add(new BasicNameValuePair("securitytoken", securityKey));
|
||||
params.add(new BasicNameValuePair("p", post.getPostId()));
|
||||
params.add(new BasicNameValuePair("securitytoken", post.getSecurityToken()));
|
||||
try {
|
||||
postThanks.setEntity(new UrlEncodedFormEntity(params));
|
||||
} catch (Exception e) {
|
||||
@@ -221,9 +179,17 @@ public class VipergirlsAuthService {
|
||||
CloseableHttpClient client = cm.getClient().build();
|
||||
|
||||
try (CloseableHttpResponse response = client.execute(postThanks, context)) {
|
||||
if (response.getStatusLine().getStatusCode() / 100 == 2) {
|
||||
post.setThanked(true);
|
||||
dataService.updatePostThanked(post.isThanked(), post.getId());
|
||||
}
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
} catch (Exception e) {
|
||||
throw new VripperException(e);
|
||||
}
|
||||
|
||||
if (!post.isThanked()) {
|
||||
throw new VripperException("Failed to leave");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package tn.mnlr.vripper.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import tn.mnlr.vripper.exception.XpathException;
|
||||
|
||||
import javax.xml.xpath.XPath;
|
||||
@@ -21,4 +22,12 @@ public class XpathService {
|
||||
}
|
||||
}
|
||||
|
||||
public NodeList getAsNodeList(Node source, String xpathExpression) throws XpathException {
|
||||
try {
|
||||
return (NodeList) xpath.compile(xpathExpression).evaluate(source, XPathConstants.NODESET);
|
||||
} catch (Exception e) {
|
||||
throw new XpathException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package tn.mnlr.vripper.services.post;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
public class CachedPost {
|
||||
private final String type = "postParse";
|
||||
private final String threadId;
|
||||
private final String postId;
|
||||
private final int number;
|
||||
private final String title;
|
||||
private final int imageCount;
|
||||
private final String url;
|
||||
private final List<String> previews;
|
||||
private final String hosts;
|
||||
|
||||
public CachedPost(String threadId, String postId, int number, String title, int imageCount, String url, List<String> previews, String hosts) {
|
||||
this.threadId = threadId;
|
||||
this.postId = postId;
|
||||
this.number = number;
|
||||
this.title = title;
|
||||
this.imageCount = imageCount;
|
||||
this.previews = previews;
|
||||
this.url = url;
|
||||
this.hosts = hosts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package tn.mnlr.vripper.services.post;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import lombok.Getter;
|
||||
import lombok.NonNull;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.jodah.failsafe.Failsafe;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import tn.mnlr.vripper.VripperApplication;
|
||||
import tn.mnlr.vripper.exception.DownloadException;
|
||||
import tn.mnlr.vripper.exception.PostParseException;
|
||||
import tn.mnlr.vripper.jpa.domain.Metadata;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.services.ConnectionManager;
|
||||
import tn.mnlr.vripper.services.HtmlProcessorService;
|
||||
import tn.mnlr.vripper.services.VipergirlsAuthService;
|
||||
import tn.mnlr.vripper.services.XpathService;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MetadataCache {
|
||||
|
||||
@Getter
|
||||
static class Key {
|
||||
private final String postId;
|
||||
private final String threadId;
|
||||
private final String url;
|
||||
|
||||
Key(String postId, String threadId, String url) {
|
||||
this.postId = postId;
|
||||
this.threadId = threadId;
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Key key = (Key) o;
|
||||
return Objects.equals(postId, key.postId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(postId);
|
||||
}
|
||||
}
|
||||
|
||||
private static final List<String> dictionary = Arrays.asList("download", "link", "rapidgator", "filefactory", "filefox");
|
||||
|
||||
private final LoadingCache<Key, Metadata> cache;
|
||||
private final ConnectionManager cm;
|
||||
private final VipergirlsAuthService vipergirlsAuthService;
|
||||
private final HtmlProcessorService htmlProcessorService;
|
||||
private final XpathService xpathService;
|
||||
|
||||
@Autowired
|
||||
public MetadataCache(ConnectionManager cm, VipergirlsAuthService vipergirlsAuthService, HtmlProcessorService htmlProcessorService, XpathService xpathService) {
|
||||
this.cm = cm;
|
||||
this.vipergirlsAuthService = vipergirlsAuthService;
|
||||
this.htmlProcessorService = htmlProcessorService;
|
||||
this.xpathService = xpathService;
|
||||
|
||||
CacheLoader<Key, Metadata> loader = new CacheLoader<>() {
|
||||
@Override
|
||||
public Metadata load(@NonNull Key key) {
|
||||
return fetchMetadata(key);
|
||||
}
|
||||
};
|
||||
cache = CacheBuilder.newBuilder()
|
||||
.expireAfterWrite(30, TimeUnit.MINUTES)
|
||||
.build(loader);
|
||||
}
|
||||
|
||||
public Metadata get(Post post) throws ExecutionException {
|
||||
Metadata metadata = new Metadata();
|
||||
Metadata cachedMetadata = cache.get(new Key(post.getPostId(), post.getThreadId(), post.getUrl()));
|
||||
metadata.setPostedBy(cachedMetadata.getPostedBy());
|
||||
metadata.setResolvedNames(List.copyOf(cachedMetadata.getResolvedNames()));
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private Metadata fetchMetadata(Key key) {
|
||||
HttpGet httpGet = cm.buildHttpGet(key.getUrl());
|
||||
Metadata metadata = new Metadata();
|
||||
Failsafe.with(VripperApplication.retryPolicy)
|
||||
.onFailure(e -> {
|
||||
if (e.getFailure() instanceof InterruptedException || e.getFailure().getCause() instanceof InterruptedException) {
|
||||
log.debug("Fetching interrupted");
|
||||
return;
|
||||
}
|
||||
log.error(String.format("Error occurred when getting post metadata, postId %s", key.getPostId()), e.getFailure());
|
||||
})
|
||||
.run(() -> {
|
||||
HttpClient connection = cm.getClient().build();
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) connection.execute(httpGet, vipergirlsAuthService.getContext())) {
|
||||
if (response.getStatusLine().getStatusCode() / 100 != 2) {
|
||||
throw new DownloadException(String.format("Unexpected response code '%d' for %s", response.getStatusLine().getStatusCode(), httpGet));
|
||||
}
|
||||
try {
|
||||
if (Thread.interrupted()) {
|
||||
return;
|
||||
}
|
||||
Document document = htmlProcessorService.clean(EntityUtils.toString(response.getEntity()));
|
||||
Node postNode = xpathService.getAsNode(document, String.format("//li[@id='post_%s']/div[contains(@class, 'postdetails')]", key.getPostId()));
|
||||
String postedBy = xpathService.getAsNode(postNode, "./div[contains(@class, 'userinfo')]//a[contains(@class, 'username')]//font").getTextContent().trim();
|
||||
metadata.setPostedBy(postedBy);
|
||||
|
||||
Node node = xpathService.getAsNode(document, String.format("//div[@id='post_message_%s']", key.getPostId()));
|
||||
metadata.setResolvedNames(findTitleInContent(node));
|
||||
} catch (Exception e) {
|
||||
throw new PostParseException(String.format("Failed to parse thread %s, post %s", key.getThreadId(), key.getPostId()), e);
|
||||
} finally {
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
}
|
||||
}
|
||||
});
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private List<String> findTitleInContent(Node node) {
|
||||
List<String> altTitle = new ArrayList<>();
|
||||
findTitle(node, altTitle, new AtomicBoolean(true));
|
||||
return altTitle.stream().distinct().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private void findTitle(Node node, List<String> altTitle, AtomicBoolean keepGoing) {
|
||||
if (!keepGoing.get()) {
|
||||
return;
|
||||
}
|
||||
if (node.getNodeName().equals("a") || node.getNodeName().equals("img")) {
|
||||
keepGoing.set(false);
|
||||
return;
|
||||
}
|
||||
if (node.getNodeType() == Node.ELEMENT_NODE) {
|
||||
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
|
||||
Node item = node.getChildNodes().item(i);
|
||||
findTitle(item, altTitle, keepGoing);
|
||||
if (!keepGoing.get()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
} else if (node.getNodeType() == Node.TEXT_NODE) {
|
||||
String text = node.getTextContent().trim();
|
||||
if (!text.isBlank() && dictionary.stream().noneMatch(e -> text.toLowerCase().contains(e.toLowerCase()))) {
|
||||
altTitle.add(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package tn.mnlr.vripper.services.post;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.jodah.failsafe.FailsafeException;
|
||||
import org.apache.http.impl.execchain.RequestAbortedException;
|
||||
import tn.mnlr.vripper.SpringContext;
|
||||
import tn.mnlr.vripper.jpa.domain.Metadata;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.services.DataService;
|
||||
|
||||
@Slf4j
|
||||
public class MetadataRunnable implements Runnable {
|
||||
|
||||
@Getter
|
||||
private final Post post;
|
||||
|
||||
private final MetadataCache metadataCache;
|
||||
private final DataService dataService;
|
||||
|
||||
public MetadataRunnable(Post post) {
|
||||
this.post = post;
|
||||
this.metadataCache = SpringContext.getBean(MetadataCache.class);
|
||||
this.dataService = SpringContext.getBean(DataService.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Metadata metadata = metadataCache.get(post);
|
||||
dataService.setMetadata(post, metadata);
|
||||
} catch (Exception e) {
|
||||
if (e.getCause() instanceof InterruptedException || (e.getCause() instanceof FailsafeException && (e.getCause().getCause() instanceof InterruptedException || e.getCause().getCause() instanceof RequestAbortedException))) {
|
||||
return;
|
||||
}
|
||||
log.error(String.format("Failed to get metadata for postId %s", post.getPostId()), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package tn.mnlr.vripper.services.post;
|
||||
|
||||
import lombok.Getter;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
public class ParseResult {
|
||||
|
||||
private final Post post;
|
||||
|
||||
@Getter
|
||||
private final Set<Image> images;
|
||||
|
||||
ParseResult(Post post, Set<Image> images) {
|
||||
this.post = post;
|
||||
this.images = images;
|
||||
}
|
||||
|
||||
public Optional<Post> getPost() {
|
||||
return Optional.ofNullable(post);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package tn.mnlr.vripper.services.post;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tn.mnlr.vripper.exception.PostParseException;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
import tn.mnlr.vripper.jpa.domain.enums.Status;
|
||||
import tn.mnlr.vripper.q.PendingQ;
|
||||
import tn.mnlr.vripper.services.AppSettingsService;
|
||||
import tn.mnlr.vripper.services.CommonExecutor;
|
||||
import tn.mnlr.vripper.services.DataService;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PostService {
|
||||
|
||||
private final AppSettingsService appSettingsService;
|
||||
private final PendingQ pendingQ;
|
||||
private final DataService dataService;
|
||||
private final CommonExecutor commonExecutor;
|
||||
private final Map<String, Future<?>> fetchingMetadata = new ConcurrentHashMap<>();
|
||||
|
||||
@Autowired
|
||||
public PostService(AppSettingsService appSettingsService, PendingQ pendingQ, DataService dataService, DataService dataService1, CommonExecutor commonExecutor) {
|
||||
this.appSettingsService = appSettingsService;
|
||||
this.pendingQ = pendingQ;
|
||||
this.dataService = dataService1;
|
||||
this.commonExecutor = commonExecutor;
|
||||
}
|
||||
|
||||
public void addPost(String postId, String threadId) throws PostParseException {
|
||||
|
||||
if (dataService.exists(postId)) {
|
||||
log.warn(String.format("skipping %s, already loaded", postId));
|
||||
return;
|
||||
}
|
||||
|
||||
VRPostParser vrPostParser = new VRPostParser(threadId, postId);
|
||||
ParseResult parseResult = vrPostParser.parse();
|
||||
if (parseResult.getPost().isEmpty()) {
|
||||
throw new PostParseException(String.format("parsing failed for thread %s, post %s", threadId, postId));
|
||||
}
|
||||
|
||||
Post post = parseResult.getPost().get();
|
||||
Set<Image> images = parseResult.getImages();
|
||||
|
||||
dataService.newPost(post, images);
|
||||
|
||||
// Metadata thread
|
||||
fetchingMetadata.put(post.getPostId(), commonExecutor.getGeneralExecutor().submit(new MetadataRunnable(post)));
|
||||
|
||||
if (appSettingsService.getSettings().getAutoStart()) {
|
||||
log.debug("Auto start downloads option is enabled");
|
||||
post.setStatus(Status.PENDING);
|
||||
try {
|
||||
pendingQ.enqueue(post, images);
|
||||
} catch (InterruptedException e) {
|
||||
log.warn("Interruption was caught");
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
log.debug(String.format("Done enqueuing jobs for %s", post.getUrl()));
|
||||
} else {
|
||||
post.setStatus(Status.STOPPED);
|
||||
log.debug("Auto start downloads option is disabled");
|
||||
}
|
||||
dataService.updatePostStatus(post.getStatus(), post.getId());
|
||||
}
|
||||
|
||||
public void stopFetchingMetadata(Post post) {
|
||||
this.fetchingMetadata.forEach((k, v) -> {
|
||||
if (k.equals(post.getPostId())) {
|
||||
v.cancel(true);
|
||||
}
|
||||
});
|
||||
fetchingMetadata.remove(post.getPostId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package tn.mnlr.vripper.services.post;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.xml.sax.Attributes;
|
||||
import org.xml.sax.helpers.DefaultHandler;
|
||||
import tn.mnlr.vripper.SpringContext;
|
||||
import tn.mnlr.vripper.host.Host;
|
||||
import tn.mnlr.vripper.jpa.domain.Image;
|
||||
import tn.mnlr.vripper.jpa.domain.Post;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
class VRApiPostHandler extends DefaultHandler {
|
||||
|
||||
private final Collection<Host> supportedHosts;
|
||||
|
||||
private final String threadId;
|
||||
private final String postId;
|
||||
private final String postUrl;
|
||||
private final Set<Image> images = new HashSet<>();
|
||||
private Set<String> previews = new HashSet<>();
|
||||
private String threadTitle;
|
||||
private String postTitle;
|
||||
private String forum;
|
||||
private String userHash;
|
||||
private int index = 0;
|
||||
|
||||
private Post parsedPost;
|
||||
|
||||
VRApiPostHandler(String threadId, String postId) {
|
||||
this.threadId = threadId;
|
||||
this.postId = postId;
|
||||
this.postUrl = String.format("https://vipergirls.to/threads/%s/?p=%s&viewfull=1#post%s", this.threadId, this.postId, this.postId);
|
||||
this.supportedHosts = SpringContext.getBeansOfType(Host.class).values();
|
||||
}
|
||||
|
||||
|
||||
public ParseResult getParsedPost() {
|
||||
return new ParseResult(parsedPost, images);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startDocument() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startElement(String uri, String localName, String qName, Attributes attributes) {
|
||||
|
||||
switch (qName.toLowerCase()) {
|
||||
case "forum":
|
||||
forum = attributes.getValue("title").trim();
|
||||
break;
|
||||
case "user":
|
||||
userHash = attributes.getValue("hash").trim();
|
||||
break;
|
||||
case "thread":
|
||||
threadTitle = attributes.getValue("title").trim();
|
||||
break;
|
||||
case "post":
|
||||
postTitle = Optional.ofNullable(attributes.getValue("title")).map(e -> e.trim().isEmpty() ? null : e.trim()).orElse(threadTitle);
|
||||
parsedPost = new Post(
|
||||
postTitle,
|
||||
postUrl,
|
||||
postId,
|
||||
threadId,
|
||||
threadTitle,
|
||||
forum,
|
||||
userHash
|
||||
);
|
||||
break;
|
||||
case "image":
|
||||
index++;
|
||||
if (previews.size() < 4) {
|
||||
Optional.ofNullable(attributes.getValue("thumb_url")).map(String::trim).ifPresent(previews::add);
|
||||
}
|
||||
|
||||
String mainUrl = Optional.ofNullable(attributes.getValue("main_url")).map(String::trim).orElse(null);
|
||||
if (mainUrl != null) {
|
||||
Host foundHost = supportedHosts.stream().filter(host -> host.isSupported(mainUrl)).findFirst().orElse(null);
|
||||
if (foundHost != null) {
|
||||
log.debug(String.format("Found supported host %s for %s", foundHost.getClass().getSimpleName(), mainUrl));
|
||||
images.add(new Image(postId, mainUrl, foundHost, index));
|
||||
} else {
|
||||
log.warn(String.format("unsupported host for %s, skipping", mainUrl));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endElement(String uri, String localName, String qName) {
|
||||
if ("post".equals(qName.toLowerCase())) {
|
||||
parsedPost.setTotal(images.size());
|
||||
if (!previews.isEmpty()) {
|
||||
parsedPost.setPreviews(previews);
|
||||
}
|
||||
parsedPost.setHosts(images.stream().map(Image::getHost).map(Host::getHost).collect(Collectors.toSet()));
|
||||
index = 0;
|
||||
previews = new HashSet<>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package tn.mnlr.vripper.services.post;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.jodah.failsafe.Failsafe;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import tn.mnlr.vripper.SpringContext;
|
||||
import tn.mnlr.vripper.VripperApplication;
|
||||
import tn.mnlr.vripper.exception.DownloadException;
|
||||
import tn.mnlr.vripper.exception.PostParseException;
|
||||
import tn.mnlr.vripper.services.ConnectionManager;
|
||||
import tn.mnlr.vripper.services.VipergirlsAuthService;
|
||||
|
||||
import javax.xml.parsers.SAXParserFactory;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@Slf4j
|
||||
public class VRPostParser {
|
||||
|
||||
private static final String VR_API = "https://vipergirls.to/vr.php";
|
||||
|
||||
private static final SAXParserFactory factory = SAXParserFactory.newInstance();
|
||||
|
||||
private final String threadId;
|
||||
private final String postId;
|
||||
private final ConnectionManager cm;
|
||||
private final VipergirlsAuthService vipergirlsAuthService;
|
||||
|
||||
public VRPostParser(String threadId, String postId) {
|
||||
this.threadId = threadId;
|
||||
this.postId = postId;
|
||||
this.cm = SpringContext.getBean(ConnectionManager.class);
|
||||
this.vipergirlsAuthService = SpringContext.getBean(VipergirlsAuthService.class);
|
||||
}
|
||||
|
||||
public ParseResult parse() throws PostParseException {
|
||||
|
||||
log.debug(String.format("Parsing post %s", postId));
|
||||
HttpGet httpGet;
|
||||
try {
|
||||
URIBuilder uriBuilder = new URIBuilder(VR_API);
|
||||
uriBuilder.setParameter("p", postId);
|
||||
httpGet = cm.buildHttpGet(uriBuilder.build());
|
||||
} catch (URISyntaxException e) {
|
||||
throw new PostParseException(e);
|
||||
}
|
||||
|
||||
AtomicReference<Throwable> thr = new AtomicReference<>();
|
||||
VRApiPostHandler handler = new VRApiPostHandler(threadId, postId);
|
||||
log.debug(String.format("Requesting %s", httpGet));
|
||||
ParseResult post = getPost(httpGet, handler, thr);
|
||||
if (thr.get() != null) {
|
||||
log.error(String.format("parsing failed for thread %s, post %s", threadId, postId), thr.get());
|
||||
throw new PostParseException(thr.get());
|
||||
}
|
||||
return post;
|
||||
}
|
||||
|
||||
private ParseResult getPost(HttpGet httpGet, VRApiPostHandler handler, AtomicReference<Throwable> thr) {
|
||||
return Failsafe.with(VripperApplication.retryPolicy)
|
||||
.onFailure(e -> thr.set(e.getFailure()))
|
||||
.get(() -> {
|
||||
HttpClient connection = cm.getClient().build();
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) connection.execute(httpGet, vipergirlsAuthService.getContext())) {
|
||||
if (response.getStatusLine().getStatusCode() / 100 != 2) {
|
||||
throw new DownloadException(String.format("Unexpected response code '%d' for %s", response.getStatusLine().getStatusCode(), httpGet));
|
||||
}
|
||||
|
||||
factory.newSAXParser().parse(response.getEntity().getContent(), handler);
|
||||
EntityUtils.consumeQuietly(response.getEntity());
|
||||
return handler.getParsedPost();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package tn.mnlr.vripper.web;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocket;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
|
||||
import tn.mnlr.vripper.web.wsendpoints.WebSocketHandler;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSocket
|
||||
public class WebSocketConfig implements WebSocketConfigurer {
|
||||
|
||||
@Autowired
|
||||
private WebSocketHandler handler;
|
||||
|
||||
@Override
|
||||
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||
registry.addHandler(handler, "/endpoint").setAllowedOrigins("*").withSockJS().setClientLibraryUrl("../../assets/sockjs.min.js");
|
||||
}
|
||||
}
|
||||